text
stringlengths
28
935k
meta
stringlengths
137
139
red_pajama_subset
stringclasses
1 value
\subsection{Crash of Memcached servers} In these experiments, Memcached is stopped on a subset of the caching server nodes. An experiment has a total duration of 600 seconds. We have an initial phase of 200 seconds (\emph{warm-up}), in which the system and the workload execute without faults; then, we have a second phase of 200 seconds (\emph{fault-injection}), in which the fault is actually injected in the system; and a final phase of 200 seconds (\emph{recovery}), in which the fault is removed from the system. Several experiments were performed by increasing the number of failed servers, to evaluate how this affects the behavior of the system and its fault tolerance mechanisms. When Memcached nodes crash, the three middleware platforms react in different ways. Client requests can experience three possible outcomes, as summarized in \figurename{}~\ref{fig:node_failure_results}: \emph{done} (i.e., the key-value pair is correctly set or retrieved), \emph{misses} (i.e., the key-value pair cannot be retrieved because of the fault, despite it is actually stored by the caching tier); \emph{errors} (i.e., the middleware returns an error signal to the clients). By using Twemproxy, we have cache misses both during the failure and the recovery phase (two values are reported in the cells of the table). Moreover, when the number of failed server is higher than 4, we observe a significant throughput decrease and latency increase, due to the timeouts required to activate the node ejection mechanism. We found that cache misses during the recovery phase are even more than during the fault-injection phase due to a redistribution of the keys in the nodes that are still alive. \figurename~\ref{fig:misses} shows in detail this behaviour: after 200s a subset of memcached nodes are stopped and restarted after 200s. During the fault, the part of the keys are redistributed in the remaining nodes. Those keys are potential future cache misses during the recovery phase due to another change in the topology. This behavior happens because Twemproxy does not provide mechanisms for data replication that could mask data losses during node failures, and does not support online topology changes without redistributing keys among the nodes. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/Node_failure.pdf} \caption{Performance under Memcached crash failures} \label{fig:node_failure_results} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/misses.pdf} \caption{Cache miss rate during experiments with crash of Memcached servers} \label{fig:misses} \end{figure} Mcrouter and Dynomite both support failure detection and data replication. Under the same conditions, Mcrouter is able to mask Memcached failures without significant latency and throughput variation when only 1-out-of-3 servers with the same data are crashed. If two nodes with the same data are crashed, there are timeouts errors, since the only alive server becomes overloaded. The unresponsive nodes are promptly detected and removed from the topology and thus we did not found effects on the latency, which remained stable up to 10 out of 30 node failures. Dynomite is also capable to mask node crashes. However, due to the specific peer-to-peer architecture of Dynomite, when the failed node is in the same rack of the coordinator, and the received responses from other racks are different (such as a cache miss and a cache value), the coordinator always replies with the local rack response \cite{dynomiteConsistency} which is an error . Moreover, in case of two-out-of-three crashed nodes with the same data, all requests to these data experience a failure due to the impossibility to reach the quorum. Thus, differently from Mcrouter, the system does not suffer from an overload of the only available replica, but the clients can experience data unavailability (i.e., service errors). \subsection{Unbalanced overloads of Memcached servers} In this scenario, a subset of the caching servers experiences an overload, which does not simply cause a fail-stop behavior (such as crashes, which are explicitly notified by the OS), but degrades the performance of the servers without explicit failure notifications. In all of the middleware platforms, the data and the requests are distributed among nodes using a stateless and fixed scheme, by computing a deterministic hash function on the keys (\emph{consistent hashing}). This approach selects a node (or a subset of nodes) only on the basis of the key, without considering the workload of the nodes across the datacenter. This can result in an uneven distribution of the workload, such as when most of the users' requests are on a specific resource (\emph{hot-spot}), or when there is physical resource contention on specific nodes. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/Unbalanced_load.png} \caption{Performance under unbalanced overloads of Memcached nodes.} \label{fig:unbalanced_load_results} \end{figure} \figurename~\ref{fig:unbalanced_load_results} shows the percentage of requests done for the three middleware platforms, when injecting overloads on an increasing number of caching servers. In Twemproxy, the presence of unbalanced overloads significantly affects the performance, since these nodes are slowed-down, but are not enough to trigger the ejection mechanism and keys reallocation. It is interesting to note the absence of correlation between the number of failed servers and the number of timeouts errors. This means that having just one or several overloaded nodes has the same impact on performance. We looked at resource utilization metrics of the non-overloaded nodes, and found that these nodes are under-performing much below their normal load, despite they are not directly targeted by fault injection. This behavior occurred because most of the requests in the Twemproxy queue were waiting on the network sockets opened towards the overloaded nodes, and could not be quickly re-sent to another node. Therefore, the effects of one faulty node propagate through the middleware to the whole caching tier. Among the three middleware platforms, Mcrouter is the one most robust against unbalanced overloads, as there is no degradation of the rate of requests done (\figurename{}~\ref{fig:unbalanced_load_results}). The fault does not impact on the throughput and latency of the caching tier. Resource utilization remains stable in non-overloaded nodes, and only saturates on the overloaded ones. This behavior was due to the failover mechanism, which is able to detect the overloaded nodes, mark them as \emph{soft TKO} as shown in the logs in \figurename{}~\ref{fig:logs}, and remove them from the list of routes. Thus, Mcrouter addresses both overloads and crashes of servers in a similar way. Thanks to the exclusion of failed servers, requests are directly sent to another node without any waiting time, thus achieving a stable latency. Regardless of the pool of the overloaded nodes (in the same pool, or in different ones), performance is not affected. \begin{figure*}[ht] \centering \includegraphics[width=0.9\textwidth]{figures/logs.pdf} \caption{Mcrouter logs during unbalancing overloads.} \label{fig:logs} \end{figure*} Instead, when we inject an overload in two nodes with the same data, performance is inevitably degrades. In our experiments, throughput reduces by 85\% and latency grows by two orders of magnitude. The overloaded nodes alternate between states (active vs. \emph{soft TKO}), with one node active and the other unavailable, and vice versa. This behavior increases latency, since \texttt{set} requests cause the middleware to wait for responses from an overloaded node to achieve a majority. In the case of \texttt{get} requests, part of them are sent to an overloaded node. \begin{figure*}[ht] \centering \includegraphics[width=0.9\textwidth]{figures/vcpu_unbalancing.pdf} \caption{Average vCPU usage before (blue) and after (red) unbalanced overload injection.} \label{fig:dynomite_unbalanced_cpu} \end{figure*} Dynomite is not able to properly manage unbalanced overloads. The average throughput decreases proportionally with the increase of overloaded servers (\figurename{}~\ref{fig:unbalanced_load_results}). In this middleware platform, the throughput degrades due to the high latency of requests processed by the overloaded servers. \figurename~\ref{fig:dynomite_unbalanced_cpu} shows the effects of the overload of two out of thirty servers on the cpu usage of the remaining nodes. In particular we observe a significant cpu usage reduction across the whole datastore cluster. Requests for a given key can experience a high or low latency, depending on whether an overloaded node is chosen among the nodes of the quorum. Differently from the Twemproxy case, Dynomite does not propagate the effect of overloaded nodes to the remaining servers. \subsection{Network link bottlenecks} In these experiments, we inject faults in the caching tier by reducing the network bandwidth of a group of servers. In this case, the fault affects a group of Memcached servers that are hosted on the same host, to reproduce a fault (e.g., network congestion) happening at the infrastructure level. Restricting the bandwidth leads to a bottleneck in the network. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/Network_link_failure.png} \caption{Performance under network link bottlenecks.} \label{fig:link_failure_results} \end{figure} In Twemproxy, bottlenecks in a subset of connections affect the caching tier as a whole system, as the overall throughput and latency degrade, showed in \figurename{}~\ref{fig:link_failure_results}. The standard deviation of latency becomes an order of magnitude higher than the average, which indicates the unbalance of the latency for different requests. Since the latency does not increase for all requests, there are not enough timeouts to trigger the ejection mechanism. The throughput degrades to $20,000$ reqs/sec, which represents a reduction of 82\% when compared to $115,000$ reqs/sec reached under a normal condition. As in the case of unbalanced overloads, in Twemproxy all nodes are impacted by the effects of the fault. Network bottlenecks are the only kind of fault that have an impact on the performance of Mcrouter. We have a sharp increase of latency, as shown in \figurename{}~\ref{fig:link_failure_results}, and a decrease of the throughput, with some requests that experience errors. The throughput decreases from $45,000$ reqs/sec under normal conditions to $8,500$ under faults, and the average latency increases from $2.8$ ms to $142.3$ ms under faults. Dynomite is able to manage the reduction of network bandwidth, as these faults are transparent to the clients. We found that there is no variation in throughput, and we do not have any request with errors. Comparing latency with vs. without faults (\figurename{}~\ref{fig:link_failure_results}), we notice a small increase of latency (from $2.8$ ms to $4.2$ ms under faults) which cannot be considered statistically significant. This behavior is due to the peer-to-peer architecture adopted by Dynomite. Indeed, one of the main advantages of the peer-to-peer architecture is that it increases tolerance to faults related to a specific connection. By creating several connections between nodes in a rack, the bandwidth reduction of few connections does not affect performance, since requests are forwarded to the other connections. Thus, this approach is effective at isolating the problem. The effects of the fault do not propagate across the system, which is why the performance of the caching tier as a whole is not significantly affected. \subsection{Twitter Twemproxy} Twemproxy (aka Nutcracker) is a fast and light-weight proxy for the Memcached protocol. Twemproxy was developed by Twitter to reduce open connections towards cache nodes, by deploying a local proxy on every front-end node. Thanks to protocol pipelining and sharding, Twemproxy improves horizontal scalability of distributed caching. Twemproxy allows to create a pool of cache servers to distribute the data and to reduce the amount of connections. To send a request to any of those servers, the client contacts Twemproxy, which routes the request to a Memcached server. The same Twemproxy instance can manage different pools, by setting different listening ports to each pool. The number of connections between the client and Twemproxy, and between Twemproxy and each server is set through a configuration file. It is interesting to note that the ``read my last write'' constraint does not necessarily hold true when Twemproxy is configured with more than one connection per server. Twemproxy shards data automatically across multiple servers. To decide the destination server for a request, a \emph{request hashing} function is applied to the key of the request to select a shard; then, based on a chosen random distribution, the request is routed to a Memcached server in the shard. Twemproxy provides 12 different hash functions (i.e., \texttt{one\_at\_a\_time}, \texttt{MD5}, \texttt{CRC16}, \texttt{CRC32}, \texttt{FNV1\_64}, etc.) and 3 different distributions (i.e., ketama, modula, random). It allows the application to use only part of the key (\emph{hashtag}) to calculate the hash function. When the hashtag option is enabled, only part of the key is used as input for the hash function. This option allows the application to map different keys to the same server, as long as the part of the key within the tag is the same. When a failure occurs, Twemproxy provides a mechanism to exclude the failed server. It detects the failure after a number of failed requests (set in a configuration file), ejects the failed server from the pool, and redistributes the key among the remaining servers. Client requests are routed to the active servers; at regular intervals, some requests are sent to the failed server to check its status. When the failed server returns active, it is added back to the pool and the key is distributed again. Twemproxy increases observability using logs and stats. Stats can be at the granularity of server pool or individual servers, through a monitoring port. In the configuration file, it is possible to define the monitoring port and the aggregation interval. Companies that use Twemproxy in production include Pinterest, Snapchat, Flikr and Yahoo!. \subsection{Facebook Mcrouter} Mcrouter is a Memcached protocol router to handle traffic to, from, and between thousands of cache servers across dozens of clusters, distributed at geographical scale. It is a key component of the cache infrastructure at Facebook and Instagram, where Mcrouter handles nearly 5 billion requests per second at peak. It uses the standard ASCII Memcached protocol to provide a transparent layer between clients and servers, and adds advanced features that make it more than a simple proxy. In the Mcrouter terminology, a Memcached server is a \emph{destination}, and a set of destinations is a \emph{pool}. Mcrouter adopts a client/server architecture: every Mcrouter instance communicates with several pools, without any communication between different pools. Several clients can connect to a single Mcrouter instance and share the outgoing connections, reducing the number of open connections. Looking at the Facebook infrastructure at a high level, one or more pools with Mcrouter instances and clients define a \emph{cluster}, and clusters together create a \emph{region}. Mcrouter is configured with a graph of small routing modules, called \emph{route handles}, which share a common interface (route a request, return a reply), and which can be combined. The configuration can be changed online to adapt routing to a transient situation, such as adding and warming up a new node. Since the configuration is checked and loaded by a background thread, there is no extra latency from the client point of view. Mcrouter supports sharding in order to adapt the datastore tier to the growth of data. The data distribution among servers is based on a key hash. In this way, different keys are evenly distributed across different destinations, and requests for the same key are served by the same destination. It is possible to choose between different hash functions (e.g., \texttt{CH3}, weighted \texttt{CH3}, or \texttt{CRC32}). Keys in the same pool compete for the same amount of memory, and are evicted in the same way. Mcrouter also provides a feature, namely \emph{prefix routing}, that allows applications to control data distribution on different pools, by using different key prefixes. This feature is valuable since applications generate and store data of different complexity (e.g., caching the results of complex computations), and they can prevent cache misses on ``expensive'' data by using different prefixes than ``cheap'', so that they do not compete for the same memory space. Mcrouter supports data replication. Read and write requests are managed in a different way: writes are replicated to all hosts in the pool, while reads are routed to a single replica, chosen separately for each client, to achieve a higher read rate. To increase fault tolerance, Mcrouter also provides destination health monitoring and automatic failover. When a destination is marked as unresponsive, the incoming requests will be routed to another destination. At the same time, health check requests will be sent in the background, and as soon as a health check is successful, Mcrouter will send the requests to the original destination again. Mcrouter distinguishes between \emph{soft errors} (e.g., data timeouts), which are tolerated to happen a few times in a row, and \emph{hard errors} (e.g., connection refused), which cause a host to be marked unresponsive immediately. The health monitoring parameters are set up through command line options. It is possible to define the number of data timeouts to declare a \emph{soft TKO} (``technical knockout''), the maximum number of destinations allowed to be in soft TKO state at the same time, and the health check frequency. The health check requests (\emph{TKO probes}) are sent with an exponentially increasing interval, whose initial and maximum length (in ms) is configurable. The actual intervals have an additional random jitter of up to 50\% to avoid overloading a single failed host with TKO probes from different Mcrouters. Mcrouter provides mechanisms to check the current configuration. Through an admin request, it is possible to verify what is the route of a specifc request. Given the operation and the key, the response from Mcrouter will be the server that owns the data. It is possible to get the route handle graph that a given request would traverse. These requests allow administrators to get insights on the actual state of the system, e.g., to show how the routing changes when a failure occurs. \subsection{Netflix Dynomite} Dynomite is a middleware solution implemented by Netflix. The main purpose of Dynomite is to transform a single server datastore into a peer-to-peer, clustered and linearly scalable system that preserves native client/server protocols of the datastores, such as the Redis and Memcached protocols. A Dynomite cluster consists of multiple \emph{data centers} (DC). A data center is a group of \emph{racks}, and a rack is a group of \emph{nodes}. Each rack consists of the entire dataset, which is partitioned across several nodes in that rack. A client can connect to any node on a Dynomite cluster when sending a request. If the node that receives the request owns the data, it gives the response; otherwise, the node forwards the request to the node that owns the data in the same rack. Dynomite is designed to be a sharding and replication layer. Sharding is achieved as in distributed hash tables \cite{chi2017hashing,tanenbaum2007distributed}: Request keys are hashed to obtain a \emph{token} (an integer value); the range of all possible token values is partitioned among the nodes, by assigning to each node a unique token value; the keys that fall in the sub-range ending with the node's unique token are assigned to that node. To achieve replication, datasets are replicated among all the racks. When a node receives a \texttt{set} request, it acts as a coordinator, by writing data in the node of its rack which owns the token, and by forwarding the request to the corresponding nodes in other racks and data centers. Every node knows the distribution of the token in the nodes of all data centers through to the configuration file. Using a similar technique for \texttt{get} requests, it is possible to increase data availability and tolerate node failures. The configuration file defines the topology, the number of connections and the token range partitioning among the nodes. Moreover, it is possible to configure one of three confidence levels writes and reads: \begin{itemize} \item \textbf{DC\_ONE}: requests are propagated synchronously only in the local rack, and asynchronously replicated to other racks and regions; \item \textbf{DC\_QUORUM}: requests are sent synchronously to a quorum of servers in the local data center, and asynchronously to the rest. This configuration writes to a set of nodes that forms a quorum. If responses are different, the first response that the coordinator received is returned; \item \textbf{DC\_SAFE\_QUORUM}: similar to DC\_QUORUM, but data checksums have to match. \end{itemize} Dynomite makes the caching system tolerant to failures of one or few servers (i.e., less than the size of the quorum) through replication, but it does not provide any failover detection or online reconfiguration. This makes the system less dynamic. For example, to add a new node you have to recompute all tokens, update the configuration file, and restart all processes. Failover detection, token reconfiguration, and other features are provided from other components in the Dyno ecosystem, like Dynomite-manager or Dyno client. Dynomite provides REST APIs for checking the state of some parameters (e.g., the confidence level), but this does not include routing (i.e., where a key is stored or read from). \subsection{Qualitative comparison of fault-tolerance mechanisms} Both Mcrouter and Dynomite adopt replication as strategy to achieve transparent fault tolerance. Of course, this strategy has a major impact on performance, since a single request turns in multiple operations on several machines. Given the same settings (number of clients, connections, threads, etc.), the throughput of the caching system can significantly degrade when enabling replication: for example, if throughput without replication reaches $20,000$ reqs/sec, it can settle to $5,500$ reqs/sec when using a replication factor of three. The same is not necessarily true for latency, which is of the same order of magnitude in all cases. Being able to use replication without affecting latency is the reason why major service providers are using this strategy despite lower throughput, since latency is the key performance indicator that mostly influences the Quality of Experience. Mcrouter has a more complete failure management, as compared to the previous ones. It consists on monitoring the health state of destinations and detecting failures. By default, it converts all \texttt{get} errors into cache misses, so that the application can still work even if there is no replication and a high amount of errors occur. Similar considerations on misses and errors also apply for Twemproxy. When keys are redistributed among nodes after a failure, Twemproxy turns the timeouts into cache misses. Both Twemproxy and Mcrouter rely on knowledge about the infrastructure and its failures to be configured with appropriate values, e.g., for the frequency of monitoring, the timeouts, and the replication policies. The main factors driving the configuration are: the fault duration, the throughput, and the amount of data on each server. For example, if we have a throughput of 20k \texttt{set} reqs/sec, and 100k keys on each node, then all keys can be redistributed in 5 seconds and be again available. Thus, it is worth adopting redistribution when the throughput is high, the amount of data on each node is small, and the outage of faulty nodes is expected to b long. Dynomite is fault-tolerant with some limitations. In particular, if the coordinator node fails (i.e., the node that first receives a request), there is no retry mechanism that sends the request to another node. Thus, coordinator failures are not tolerated. This is a deliberate design choice, since Dynomite is designed to be on the same host running a Memcached server, thus when the host fails, both Memcached and Dynomite fail. Furthermore, if the rack includes a failed node, the rack still continues to count towards the quorum, while the rack is excluded from the quorum when all its nodes are failed. \subsection{Workload generation} To generate a workload for the caching nodes and for the middleware platform, we need i)to create connections to send data requests, and ii) to collect performance metrics from the clients' perspective. We initially tried several publicly-available tools, but many proved not to be suitable for carrying out our experiments. The first tool was the \emph{CloudSuite Data Caching Benchmark} \cite{cloudsuiterepo}, which is part of CloudSuite, a benchmark suite for cloud services. This tool does not support execution in the presence of failures (which we will deliberately force with fault injection), and stops making requests when a server fails. Then, we tried \emph{Memaslap} \cite{memaslap}, a load generation and benchmark tool for Memcached servers included in \emph{libMemcached}. However, the format of requests generated by this tool are incompatible with Mcrouter. For this reason, we developed our own tool, namely Mcrouter \emph{Mcbench}. It is written in Python, uses the \emph{aiomcache} library to create the connections and makes requests according to the Memcached protocol. Mcbench generates only \texttt{set} (20\%) and \texttt{get} (80\%) requests with random keys and values. The tool can be configured with respect to the distribution of keys and values lengths; the duration of the experiment; the desired throughput; the number of threads, clients and connections per server; the list of servers where to forward requests. The tool collects performance statistics about requests that are successful and failed, latency, and misses, aggregating them every second. To warm up servers, we configure the tool to initially perform only \texttt{set} requests. The random distribution of the keys is based on a real-world Twitter dataset from the CloudSuite Data Caching Benchmark \cite{twitterdataset}. To create random distributions for a more intensive workload for large distributed systems, we scaled-up the Twitter dataset by a factor of ten, while preserving both the popularity and the distribution of object size, with alphanumeric variable-length keys. The original dataset consumes 300MB (267,433 rows) of server memory, while the scaled dataset requires about 3GB (2,674,339 rows). \subsection{Testbed configuration} The experimental testbed was built on top of OpenStack, an open-source Infrastructure-as-a-Service (IaaS) cloud computing platform. The experimental testbed consists of eight host machines SUPERMICRO (high density), equipped with two 8-Core 3.3Ghz Intel XEON CPUs (32 logic cores in total), 128GB RAM, two 500GB SATA HDD, four 1-Gbps Intel Ethernet NICs, and a NetApp Network Storage Array with 32TB of storage space and 4GB of SSD cache. The hosts are connected to three 1-Gbps Ethernet network switches, respectively for management, storage and VM network traffic. The testbed is managed with OpenStack Mitaka and the VMware ESXi 6.0 hypervisor. \begin{table} \centering \protect\caption{Configuration of the experimental testbed} \label{tab:configuration} \begin{tabular}{|p{1.5cm}|p{0.6cm}|p{5cm}|} \hline \textbf{Node Type} & \textbf{\# of nodes} & \textbf{VM configuration}\tabularnewline \hline \hline \textbf{Controller Node} & 1 & 2 vCPU, 16GB RAM, 120 GB HDD\tabularnewline \hline \textbf{Middleware Node} & 7 & 4 vCPU, 4 GB RAM, 20 GB HDD\tabularnewline \hline \textbf{Memcached Node} & 30 & 1 vCPU, 8 GB RAM, 20 GB HDD\tabularnewline \hline \textbf{Workload generator} & 7 & 4 vCPU, 8 GB RAM, 40 GB HDD\tabularnewline \hline \textbf{\emph{Total}} & \emph{45} & \emph{88 vCPU, 340 GB RAM, 1.14 TB HDD}\tabularnewline \hline \end{tabular} \end{table} The system architecture detailed in Table \ref{tab:configuration} consists of: \begin{itemize} \item one controller machine, which orchestrates the test and sends commands to the other machines; \item seven workload generators, which send requests to the middleware platform; \item seven middleware machines, which forward the requests to the Memcached servers; \item thirty Memcached servers. \end{itemize} The connections between the middleware and the Memcached servers vary depending on the specific middleware. In the case of Twemproxy and Mcrouter, each instance of the middleware connects to all servers, as in \figurename{}~\ref{fig:topology1}. In Dynomite, each instance connects only to one node, since there as many Dynomite instances of Dynomite as the number of Memcached servers, as shown in \figurename{}~\ref{fig:topology2}. Therefore, in Dynomite there are fewer connections between the middleware and the Memcached servers, and the instances of the middleware communicate with each other to route the requests \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/topology1.pdf} \caption{Twemproxy and Mcrouter topology} \label{fig:topology1} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/topology2.pdf} \caption{Dynomite topology} \label{fig:topology2} \end{figure} To have a balanced load among the physical hosts, we equally divided the VMs in order to have one workload generator, one middleware and at most five Memcached servers on each physical host. For Twemproxy, the dataset is divided among all thirty nodes; for Mcrouter and Dynomite, which support replication schemes, we have three pools/racks, each composed of ten nodes among which the dataset is divided, thus with a replication factor of three. Thus, a $set$ operation is performed on three different nodes and a get operation in one node out of three. In case of a miss or of an error the operation is retried on the remaining nodes and it is returned the first valid response if any. If the middleware supports the quorum (i.e., in the case of Dynomite) the middleware should reply with an error if the reply does not reach the quorum of two valid responses. We carried out a capacity test to define the maximum throughput that can be reached by the system. The maximum throughput is $18,500$ reqs/sec per workload generator with Twemproxy, and $7,200$ reqs/sec per workload generator with Mcrouter and Dynomite. We then calibrated the workload generator to have a throughput per workload generator of $16,500$ reqs/sec for Twemproxy, and $6,500$ reqs/sec for Mcrouter and Dynomite. The total number of requests served in the experiments are respectively $115,500$ reqs/sec and $45,500$ reqs/sec. \section{Introduction} \label{sec:introduction} \input{tex/introduction.tex} \section{Middleware platforms for distributed caching} \label{sec:fault_tolerance} \input{tex/fault_tolerance.tex} \section{Experimental methodology and setup} \label{sec:experiment} \input{tex/experiment.tex} \section{Experimental results} \label{sec:discussion} \input{tex/discussion.tex} \section{Related work} \label{sec:related} \input{tex/related.tex} \section{Conclusion} \label{sec:conclusion} \input{tex/conclusion.tex} \bibliographystyle{IEEEtran} \section{Introduction} \label{sec:introduction} \input{tex/introduction.tex} \section{Middleware platforms for distributed caching} \label{sec:fault_tolerance} \input{tex/fault_tolerance.tex} \section{Experimental methodology and setup} \label{sec:experiment} \input{tex/experiment.tex} \section{Experimental results} \label{sec:discussion} \input{tex/discussion.tex} \section{Related work} \label{sec:related} \input{tex/related.tex} \section{Conclusion} \label{sec:conclusion} \input{tex/conclusion.tex} \bibliographystyle{IEEEtran} \subsection{Crash of Memcached servers} In these experiments, Memcached is stopped on a subset of the caching server nodes. An experiment has a total duration of 600 seconds. We have an initial phase of 200 seconds (\emph{warm-up}), in which the system and the workload execute without faults; then, we have a second phase of 200 seconds (\emph{fault-injection}), in which the fault is actually injected in the system; and a final phase of 200 seconds (\emph{recovery}), in which the fault is removed from the system. Several experiments were performed by increasing the number of failed servers, to evaluate how this affects the behavior of the system and its fault tolerance mechanisms. When Memcached nodes crash, the three middleware platforms react in different ways. Client requests can experience three possible outcomes, as summarized in \figurename{}~\ref{fig:node_failure_results}: \emph{done} (i.e., the key-value pair is correctly set or retrieved), \emph{misses} (i.e., the key-value pair cannot be retrieved because of the fault, despite it is actually stored by the caching tier); \emph{errors} (i.e., the middleware returns an error signal to the clients). By using Twemproxy, we have cache misses both during the failure and the recovery phase (two values are reported in the cells of the table). Moreover, when the number of failed server is higher than 4, we observe a significant throughput decrease and latency increase, due to the timeouts required to activate the node ejection mechanism. We found that cache misses during the recovery phase are even more than during the fault-injection phase due to a redistribution of the keys in the nodes that are still alive. \figurename~\ref{fig:misses} shows in detail this behaviour: after 200s a subset of memcached nodes are stopped and restarted after 200s. During the fault, the part of the keys are redistributed in the remaining nodes. Those keys are potential future cache misses during the recovery phase due to another change in the topology. This behavior happens because Twemproxy does not provide mechanisms for data replication that could mask data losses during node failures, and does not support online topology changes without redistributing keys among the nodes. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/Node_failure.pdf} \caption{Performance under Memcached crash failures} \label{fig:node_failure_results} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/misses.pdf} \caption{Cache miss rate during experiments with crash of Memcached servers} \label{fig:misses} \end{figure} Mcrouter and Dynomite both support failure detection and data replication. Under the same conditions, Mcrouter is able to mask Memcached failures without significant latency and throughput variation when only 1-out-of-3 servers with the same data are crashed. If two nodes with the same data are crashed, there are timeouts errors, since the only alive server becomes overloaded. The unresponsive nodes are promptly detected and removed from the topology and thus we did not found effects on the latency, which remained stable up to 10 out of 30 node failures. Dynomite is also capable to mask node crashes. However, due to the specific peer-to-peer architecture of Dynomite, when the failed node is in the same rack of the coordinator, and the received responses from other racks are different (such as a cache miss and a cache value), the coordinator always replies with the local rack response \cite{dynomiteConsistency} which is an error . Moreover, in case of two-out-of-three crashed nodes with the same data, all requests to these data experience a failure due to the impossibility to reach the quorum. Thus, differently from Mcrouter, the system does not suffer from an overload of the only available replica, but the clients can experience data unavailability (i.e., service errors). \subsection{Unbalanced overloads of Memcached servers} In this scenario, a subset of the caching servers experiences an overload, which does not simply cause a fail-stop behavior (such as crashes, which are explicitly notified by the OS), but degrades the performance of the servers without explicit failure notifications. In all of the middleware platforms, the data and the requests are distributed among nodes using a stateless and fixed scheme, by computing a deterministic hash function on the keys (\emph{consistent hashing}). This approach selects a node (or a subset of nodes) only on the basis of the key, without considering the workload of the nodes across the datacenter. This can result in an uneven distribution of the workload, such as when most of the users' requests are on a specific resource (\emph{hot-spot}), or when there is physical resource contention on specific nodes. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/Unbalanced_load.png} \caption{Performance under unbalanced overloads of Memcached nodes.} \label{fig:unbalanced_load_results} \end{figure} \figurename~\ref{fig:unbalanced_load_results} shows the percentage of requests done for the three middleware platforms, when injecting overloads on an increasing number of caching servers. In Twemproxy, the presence of unbalanced overloads significantly affects the performance, since these nodes are slowed-down, but are not enough to trigger the ejection mechanism and keys reallocation. It is interesting to note the absence of correlation between the number of failed servers and the number of timeouts errors. This means that having just one or several overloaded nodes has the same impact on performance. We looked at resource utilization metrics of the non-overloaded nodes, and found that these nodes are under-performing much below their normal load, despite they are not directly targeted by fault injection. This behavior occurred because most of the requests in the Twemproxy queue were waiting on the network sockets opened towards the overloaded nodes, and could not be quickly re-sent to another node. Therefore, the effects of one faulty node propagate through the middleware to the whole caching tier. Among the three middleware platforms, Mcrouter is the one most robust against unbalanced overloads, as there is no degradation of the rate of requests done (\figurename{}~\ref{fig:unbalanced_load_results}). The fault does not impact on the throughput and latency of the caching tier. Resource utilization remains stable in non-overloaded nodes, and only saturates on the overloaded ones. This behavior was due to the failover mechanism, which is able to detect the overloaded nodes, mark them as \emph{soft TKO} as shown in the logs in \figurename{}~\ref{fig:logs}, and remove them from the list of routes. Thus, Mcrouter addresses both overloads and crashes of servers in a similar way. Thanks to the exclusion of failed servers, requests are directly sent to another node without any waiting time, thus achieving a stable latency. Regardless of the pool of the overloaded nodes (in the same pool, or in different ones), performance is not affected. \begin{figure*}[ht] \centering \includegraphics[width=0.9\textwidth]{figures/logs.pdf} \caption{Mcrouter logs during unbalancing overloads.} \label{fig:logs} \end{figure*} Instead, when we inject an overload in two nodes with the same data, performance is inevitably degrades. In our experiments, throughput reduces by 85\% and latency grows by two orders of magnitude. The overloaded nodes alternate between states (active vs. \emph{soft TKO}), with one node active and the other unavailable, and vice versa. This behavior increases latency, since \texttt{set} requests cause the middleware to wait for responses from an overloaded node to achieve a majority. In the case of \texttt{get} requests, part of them are sent to an overloaded node. \begin{figure*}[ht] \centering \includegraphics[width=0.9\textwidth]{figures/vcpu_unbalancing.pdf} \caption{Average vCPU usage before (blue) and after (red) unbalanced overload injection.} \label{fig:dynomite_unbalanced_cpu} \end{figure*} Dynomite is not able to properly manage unbalanced overloads. The average throughput decreases proportionally with the increase of overloaded servers (\figurename{}~\ref{fig:unbalanced_load_results}). In this middleware platform, the throughput degrades due to the high latency of requests processed by the overloaded servers. \figurename~\ref{fig:dynomite_unbalanced_cpu} shows the effects of the overload of two out of thirty servers on the cpu usage of the remaining nodes. In particular we observe a significant cpu usage reduction across the whole datastore cluster. Requests for a given key can experience a high or low latency, depending on whether an overloaded node is chosen among the nodes of the quorum. Differently from the Twemproxy case, Dynomite does not propagate the effect of overloaded nodes to the remaining servers. \subsection{Network link bottlenecks} In these experiments, we inject faults in the caching tier by reducing the network bandwidth of a group of servers. In this case, the fault affects a group of Memcached servers that are hosted on the same host, to reproduce a fault (e.g., network congestion) happening at the infrastructure level. Restricting the bandwidth leads to a bottleneck in the network. \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/Network_link_failure.png} \caption{Performance under network link bottlenecks.} \label{fig:link_failure_results} \end{figure} In Twemproxy, bottlenecks in a subset of connections affect the caching tier as a whole system, as the overall throughput and latency degrade, showed in \figurename{}~\ref{fig:link_failure_results}. The standard deviation of latency becomes an order of magnitude higher than the average, which indicates the unbalance of the latency for different requests. Since the latency does not increase for all requests, there are not enough timeouts to trigger the ejection mechanism. The throughput degrades to $20,000$ reqs/sec, which represents a reduction of 82\% when compared to $115,000$ reqs/sec reached under a normal condition. As in the case of unbalanced overloads, in Twemproxy all nodes are impacted by the effects of the fault. Network bottlenecks are the only kind of fault that have an impact on the performance of Mcrouter. We have a sharp increase of latency, as shown in \figurename{}~\ref{fig:link_failure_results}, and a decrease of the throughput, with some requests that experience errors. The throughput decreases from $45,000$ reqs/sec under normal conditions to $8,500$ under faults, and the average latency increases from $2.8$ ms to $142.3$ ms under faults. Dynomite is able to manage the reduction of network bandwidth, as these faults are transparent to the clients. We found that there is no variation in throughput, and we do not have any request with errors. Comparing latency with vs. without faults (\figurename{}~\ref{fig:link_failure_results}), we notice a small increase of latency (from $2.8$ ms to $4.2$ ms under faults) which cannot be considered statistically significant. This behavior is due to the peer-to-peer architecture adopted by Dynomite. Indeed, one of the main advantages of the peer-to-peer architecture is that it increases tolerance to faults related to a specific connection. By creating several connections between nodes in a rack, the bandwidth reduction of few connections does not affect performance, since requests are forwarded to the other connections. Thus, this approach is effective at isolating the problem. The effects of the fault do not propagate across the system, which is why the performance of the caching tier as a whole is not significantly affected. \subsection{Twitter Twemproxy} Twemproxy (aka Nutcracker) is a fast and light-weight proxy for the Memcached protocol. Twemproxy was developed by Twitter to reduce open connections towards cache nodes, by deploying a local proxy on every front-end node. Thanks to protocol pipelining and sharding, Twemproxy improves horizontal scalability of distributed caching. Twemproxy allows to create a pool of cache servers to distribute the data and to reduce the amount of connections. To send a request to any of those servers, the client contacts Twemproxy, which routes the request to a Memcached server. The same Twemproxy instance can manage different pools, by setting different listening ports to each pool. The number of connections between the client and Twemproxy, and between Twemproxy and each server is set through a configuration file. It is interesting to note that the ``read my last write'' constraint does not necessarily hold true when Twemproxy is configured with more than one connection per server. Twemproxy shards data automatically across multiple servers. To decide the destination server for a request, a \emph{request hashing} function is applied to the key of the request to select a shard; then, based on a chosen random distribution, the request is routed to a Memcached server in the shard. Twemproxy provides 12 different hash functions (i.e., \texttt{one\_at\_a\_time}, \texttt{MD5}, \texttt{CRC16}, \texttt{CRC32}, \texttt{FNV1\_64}, etc.) and 3 different distributions (i.e., ketama, modula, random). It allows the application to use only part of the key (\emph{hashtag}) to calculate the hash function. When the hashtag option is enabled, only part of the key is used as input for the hash function. This option allows the application to map different keys to the same server, as long as the part of the key within the tag is the same. When a failure occurs, Twemproxy provides a mechanism to exclude the failed server. It detects the failure after a number of failed requests (set in a configuration file), ejects the failed server from the pool, and redistributes the key among the remaining servers. Client requests are routed to the active servers; at regular intervals, some requests are sent to the failed server to check its status. When the failed server returns active, it is added back to the pool and the key is distributed again. Twemproxy increases observability using logs and stats. Stats can be at the granularity of server pool or individual servers, through a monitoring port. In the configuration file, it is possible to define the monitoring port and the aggregation interval. Companies that use Twemproxy in production include Pinterest, Snapchat, Flikr and Yahoo!. \subsection{Facebook Mcrouter} Mcrouter is a Memcached protocol router to handle traffic to, from, and between thousands of cache servers across dozens of clusters, distributed at geographical scale. It is a key component of the cache infrastructure at Facebook and Instagram, where Mcrouter handles nearly 5 billion requests per second at peak. It uses the standard ASCII Memcached protocol to provide a transparent layer between clients and servers, and adds advanced features that make it more than a simple proxy. In the Mcrouter terminology, a Memcached server is a \emph{destination}, and a set of destinations is a \emph{pool}. Mcrouter adopts a client/server architecture: every Mcrouter instance communicates with several pools, without any communication between different pools. Several clients can connect to a single Mcrouter instance and share the outgoing connections, reducing the number of open connections. Looking at the Facebook infrastructure at a high level, one or more pools with Mcrouter instances and clients define a \emph{cluster}, and clusters together create a \emph{region}. Mcrouter is configured with a graph of small routing modules, called \emph{route handles}, which share a common interface (route a request, return a reply), and which can be combined. The configuration can be changed online to adapt routing to a transient situation, such as adding and warming up a new node. Since the configuration is checked and loaded by a background thread, there is no extra latency from the client point of view. Mcrouter supports sharding in order to adapt the datastore tier to the growth of data. The data distribution among servers is based on a key hash. In this way, different keys are evenly distributed across different destinations, and requests for the same key are served by the same destination. It is possible to choose between different hash functions (e.g., \texttt{CH3}, weighted \texttt{CH3}, or \texttt{CRC32}). Keys in the same pool compete for the same amount of memory, and are evicted in the same way. Mcrouter also provides a feature, namely \emph{prefix routing}, that allows applications to control data distribution on different pools, by using different key prefixes. This feature is valuable since applications generate and store data of different complexity (e.g., caching the results of complex computations), and they can prevent cache misses on ``expensive'' data by using different prefixes than ``cheap'', so that they do not compete for the same memory space. Mcrouter supports data replication. Read and write requests are managed in a different way: writes are replicated to all hosts in the pool, while reads are routed to a single replica, chosen separately for each client, to achieve a higher read rate. To increase fault tolerance, Mcrouter also provides destination health monitoring and automatic failover. When a destination is marked as unresponsive, the incoming requests will be routed to another destination. At the same time, health check requests will be sent in the background, and as soon as a health check is successful, Mcrouter will send the requests to the original destination again. Mcrouter distinguishes between \emph{soft errors} (e.g., data timeouts), which are tolerated to happen a few times in a row, and \emph{hard errors} (e.g., connection refused), which cause a host to be marked unresponsive immediately. The health monitoring parameters are set up through command line options. It is possible to define the number of data timeouts to declare a \emph{soft TKO} (``technical knockout''), the maximum number of destinations allowed to be in soft TKO state at the same time, and the health check frequency. The health check requests (\emph{TKO probes}) are sent with an exponentially increasing interval, whose initial and maximum length (in ms) is configurable. The actual intervals have an additional random jitter of up to 50\% to avoid overloading a single failed host with TKO probes from different Mcrouters. Mcrouter provides mechanisms to check the current configuration. Through an admin request, it is possible to verify what is the route of a specifc request. Given the operation and the key, the response from Mcrouter will be the server that owns the data. It is possible to get the route handle graph that a given request would traverse. These requests allow administrators to get insights on the actual state of the system, e.g., to show how the routing changes when a failure occurs. \subsection{Netflix Dynomite} Dynomite is a middleware solution implemented by Netflix. The main purpose of Dynomite is to transform a single server datastore into a peer-to-peer, clustered and linearly scalable system that preserves native client/server protocols of the datastores, such as the Redis and Memcached protocols. A Dynomite cluster consists of multiple \emph{data centers} (DC). A data center is a group of \emph{racks}, and a rack is a group of \emph{nodes}. Each rack consists of the entire dataset, which is partitioned across several nodes in that rack. A client can connect to any node on a Dynomite cluster when sending a request. If the node that receives the request owns the data, it gives the response; otherwise, the node forwards the request to the node that owns the data in the same rack. Dynomite is designed to be a sharding and replication layer. Sharding is achieved as in distributed hash tables \cite{chi2017hashing,tanenbaum2007distributed}: Request keys are hashed to obtain a \emph{token} (an integer value); the range of all possible token values is partitioned among the nodes, by assigning to each node a unique token value; the keys that fall in the sub-range ending with the node's unique token are assigned to that node. To achieve replication, datasets are replicated among all the racks. When a node receives a \texttt{set} request, it acts as a coordinator, by writing data in the node of its rack which owns the token, and by forwarding the request to the corresponding nodes in other racks and data centers. Every node knows the distribution of the token in the nodes of all data centers through to the configuration file. Using a similar technique for \texttt{get} requests, it is possible to increase data availability and tolerate node failures. The configuration file defines the topology, the number of connections and the token range partitioning among the nodes. Moreover, it is possible to configure one of three confidence levels writes and reads: \begin{itemize} \item \textbf{DC\_ONE}: requests are propagated synchronously only in the local rack, and asynchronously replicated to other racks and regions; \item \textbf{DC\_QUORUM}: requests are sent synchronously to a quorum of servers in the local data center, and asynchronously to the rest. This configuration writes to a set of nodes that forms a quorum. If responses are different, the first response that the coordinator received is returned; \item \textbf{DC\_SAFE\_QUORUM}: similar to DC\_QUORUM, but data checksums have to match. \end{itemize} Dynomite makes the caching system tolerant to failures of one or few servers (i.e., less than the size of the quorum) through replication, but it does not provide any failover detection or online reconfiguration. This makes the system less dynamic. For example, to add a new node you have to recompute all tokens, update the configuration file, and restart all processes. Failover detection, token reconfiguration, and other features are provided from other components in the Dyno ecosystem, like Dynomite-manager or Dyno client. Dynomite provides REST APIs for checking the state of some parameters (e.g., the confidence level), but this does not include routing (i.e., where a key is stored or read from). \subsection{Qualitative comparison of fault-tolerance mechanisms} Both Mcrouter and Dynomite adopt replication as strategy to achieve transparent fault tolerance. Of course, this strategy has a major impact on performance, since a single request turns in multiple operations on several machines. Given the same settings (number of clients, connections, threads, etc.), the throughput of the caching system can significantly degrade when enabling replication: for example, if throughput without replication reaches $20,000$ reqs/sec, it can settle to $5,500$ reqs/sec when using a replication factor of three. The same is not necessarily true for latency, which is of the same order of magnitude in all cases. Being able to use replication without affecting latency is the reason why major service providers are using this strategy despite lower throughput, since latency is the key performance indicator that mostly influences the Quality of Experience. Mcrouter has a more complete failure management, as compared to the previous ones. It consists on monitoring the health state of destinations and detecting failures. By default, it converts all \texttt{get} errors into cache misses, so that the application can still work even if there is no replication and a high amount of errors occur. Similar considerations on misses and errors also apply for Twemproxy. When keys are redistributed among nodes after a failure, Twemproxy turns the timeouts into cache misses. Both Twemproxy and Mcrouter rely on knowledge about the infrastructure and its failures to be configured with appropriate values, e.g., for the frequency of monitoring, the timeouts, and the replication policies. The main factors driving the configuration are: the fault duration, the throughput, and the amount of data on each server. For example, if we have a throughput of 20k \texttt{set} reqs/sec, and 100k keys on each node, then all keys can be redistributed in 5 seconds and be again available. Thus, it is worth adopting redistribution when the throughput is high, the amount of data on each node is small, and the outage of faulty nodes is expected to b long. Dynomite is fault-tolerant with some limitations. In particular, if the coordinator node fails (i.e., the node that first receives a request), there is no retry mechanism that sends the request to another node. Thus, coordinator failures are not tolerated. This is a deliberate design choice, since Dynomite is designed to be on the same host running a Memcached server, thus when the host fails, both Memcached and Dynomite fail. Furthermore, if the rack includes a failed node, the rack still continues to count towards the quorum, while the rack is excluded from the quorum when all its nodes are failed. \subsection{Workload generation} To generate a workload for the caching nodes and for the middleware platform, we need i)to create connections to send data requests, and ii) to collect performance metrics from the clients' perspective. We initially tried several publicly-available tools, but many proved not to be suitable for carrying out our experiments. The first tool was the \emph{CloudSuite Data Caching Benchmark} \cite{cloudsuiterepo}, which is part of CloudSuite, a benchmark suite for cloud services. This tool does not support execution in the presence of failures (which we will deliberately force with fault injection), and stops making requests when a server fails. Then, we tried \emph{Memaslap} \cite{memaslap}, a load generation and benchmark tool for Memcached servers included in \emph{libMemcached}. However, the format of requests generated by this tool are incompatible with Mcrouter. For this reason, we developed our own tool, namely Mcrouter \emph{Mcbench}. It is written in Python, uses the \emph{aiomcache} library to create the connections and makes requests according to the Memcached protocol. Mcbench generates only \texttt{set} (20\%) and \texttt{get} (80\%) requests with random keys and values. The tool can be configured with respect to the distribution of keys and values lengths; the duration of the experiment; the desired throughput; the number of threads, clients and connections per server; the list of servers where to forward requests. The tool collects performance statistics about requests that are successful and failed, latency, and misses, aggregating them every second. To warm up servers, we configure the tool to initially perform only \texttt{set} requests. The random distribution of the keys is based on a real-world Twitter dataset from the CloudSuite Data Caching Benchmark \cite{twitterdataset}. To create random distributions for a more intensive workload for large distributed systems, we scaled-up the Twitter dataset by a factor of ten, while preserving both the popularity and the distribution of object size, with alphanumeric variable-length keys. The original dataset consumes 300MB (267,433 rows) of server memory, while the scaled dataset requires about 3GB (2,674,339 rows). \subsection{Testbed configuration} The experimental testbed was built on top of OpenStack, an open-source Infrastructure-as-a-Service (IaaS) cloud computing platform. The experimental testbed consists of eight host machines SUPERMICRO (high density), equipped with two 8-Core 3.3Ghz Intel XEON CPUs (32 logic cores in total), 128GB RAM, two 500GB SATA HDD, four 1-Gbps Intel Ethernet NICs, and a NetApp Network Storage Array with 32TB of storage space and 4GB of SSD cache. The hosts are connected to three 1-Gbps Ethernet network switches, respectively for management, storage and VM network traffic. The testbed is managed with OpenStack Mitaka and the VMware ESXi 6.0 hypervisor. \begin{table} \centering \protect\caption{Configuration of the experimental testbed} \label{tab:configuration} \begin{tabular}{|p{1.5cm}|p{0.6cm}|p{5cm}|} \hline \textbf{Node Type} & \textbf{\# of nodes} & \textbf{VM configuration}\tabularnewline \hline \hline \textbf{Controller Node} & 1 & 2 vCPU, 16GB RAM, 120 GB HDD\tabularnewline \hline \textbf{Middleware Node} & 7 & 4 vCPU, 4 GB RAM, 20 GB HDD\tabularnewline \hline \textbf{Memcached Node} & 30 & 1 vCPU, 8 GB RAM, 20 GB HDD\tabularnewline \hline \textbf{Workload generator} & 7 & 4 vCPU, 8 GB RAM, 40 GB HDD\tabularnewline \hline \textbf{\emph{Total}} & \emph{45} & \emph{88 vCPU, 340 GB RAM, 1.14 TB HDD}\tabularnewline \hline \end{tabular} \end{table} The system architecture detailed in Table \ref{tab:configuration} consists of: \begin{itemize} \item one controller machine, which orchestrates the test and sends commands to the other machines; \item seven workload generators, which send requests to the middleware platform; \item seven middleware machines, which forward the requests to the Memcached servers; \item thirty Memcached servers. \end{itemize} The connections between the middleware and the Memcached servers vary depending on the specific middleware. In the case of Twemproxy and Mcrouter, each instance of the middleware connects to all servers, as in \figurename{}~\ref{fig:topology1}. In Dynomite, each instance connects only to one node, since there as many Dynomite instances of Dynomite as the number of Memcached servers, as shown in \figurename{}~\ref{fig:topology2}. Therefore, in Dynomite there are fewer connections between the middleware and the Memcached servers, and the instances of the middleware communicate with each other to route the requests \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/topology1.pdf} \caption{Twemproxy and Mcrouter topology} \label{fig:topology1} \end{figure} \begin{figure}[ht] \centering \includegraphics[width=\columnwidth]{figures/topology2.pdf} \caption{Dynomite topology} \label{fig:topology2} \end{figure} To have a balanced load among the physical hosts, we equally divided the VMs in order to have one workload generator, one middleware and at most five Memcached servers on each physical host. For Twemproxy, the dataset is divided among all thirty nodes; for Mcrouter and Dynomite, which support replication schemes, we have three pools/racks, each composed of ten nodes among which the dataset is divided, thus with a replication factor of three. Thus, a $set$ operation is performed on three different nodes and a get operation in one node out of three. In case of a miss or of an error the operation is retried on the remaining nodes and it is returned the first valid response if any. If the middleware supports the quorum (i.e., in the case of Dynomite) the middleware should reply with an error if the reply does not reach the quorum of two valid responses. We carried out a capacity test to define the maximum throughput that can be reached by the system. The maximum throughput is $18,500$ reqs/sec per workload generator with Twemproxy, and $7,200$ reqs/sec per workload generator with Mcrouter and Dynomite. We then calibrated the workload generator to have a throughput per workload generator of $16,500$ reqs/sec for Twemproxy, and $6,500$ reqs/sec for Mcrouter and Dynomite. The total number of requests served in the experiments are respectively $115,500$ reqs/sec and $45,500$ reqs/sec.
{'timestamp': '2020-08-19T02:11:15', 'yymm': '2008', 'arxiv_id': '2008.06943', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06943'}
arxiv
\section{Introduction and Motivation} A liner code $C$ of length $n$ over $\mathbb{F}_q$, the finite field of order $q$, is a vector subspace of $\mathbb{F}_q^n$. The three important parameters of a linear code are: the length ($n$), the dimension ($k$), and the minimum distance ($d$). If a code $C$ over $\mathbb{F}_q$ is of length $n$, dimension $k$, and minimum distance $d$, then we call it an $[n,k,d]_q$ code. One of the most important and challenging problems in coding theory is to determine the optimal parameters of a linear code and to explicitly construct codes that attain them. For example, given the alphabet size $q$, length $n$, and dimension $k$, researchers try to determine the highest value of the minimum distance $d$, and give an explicit construction of such a code. Despite much work on this question, it still has many open cases. There are databases that contain information about best known linear codes (BKLC) and their constructions. Two of the well known databases are the maintained by M. Grassl ( \cite{otable}, codetables.de) and the database contained in the Magma software \cite{magma}. Given $q, n$ and $k$, there are theoretical upper bounds on $d$ that are given in the tables. However, it is not guaranteed and not always possible that they can actually be attained. This is a challenging problem for two main reasons: firstly, computing the minimum distance of a linear code is an NP-hard problem \cite{NPhard} and secondly the number $\displaystyle{\frac{(q^n-1)(q^n-q)\cdots (q^n-q^{k-1})}{(q^k-1)(q^k-q)\cdots (q^k-q^{k-1})}}$ of linear codes over $\mathbb{F}_q$ of length $n$ and dimension $k$ grows fast when $n,k$ and $q$ increase. Therefore, it is impossible to do an exhaustive search except for very small parameters. Hence, researchers focus work on sub-classes of linear codes with special algebraic properties. One very promising class has been the class of quasi-twisted (QT) codes which contains the important classes such as cyclic codes, constacyclic codes, and quasi-cyclic (QC) codes as special cases. Hundreds of BKLCs have been obtained, usually by computer searches, from the class of QT codes. More recently, a generalization of QT codes called multi-twisted (MT) codes was introduced in \cite{mt}. Therefore, MT codes are a generalization of cyclic, negacyclic, consta-cyclic (CC), quasi-cyclic (QC), generalized quasi-cyclic (GQC) and quasi-twisted codes (QT). Compared to QT codes, the search space for MT codes is much larger. While this increases the chances of finding new codes, it also makes the search process computationally more expensive. In this work, we focus on a special type of MT codes whose generator matrix is of the form $G= [I_k \mid A]$ where $I_k$ is the $k \times k$ identity matrix and $A$ is a $k \times n-k$ circulant matrix. The idea of investigating these codes was first introduced in \cite{ICY}. In addition to trying to find new linear codes from this type of MT Codes, we also worked on obtaining codes that are reversible, self-dual, and self-orthogonal. Finally, we also worked on obtaining quantum codes from classical codes, specifically from constacyclic, QC, QT, and MT codes. The idea of quantum codes was first introduced in \cite{Quantumoriginal1} and \cite{Quantumoriginal2}. Later methods of constructing quantum codes from classical codes were introduced in \cite{Quantumoriginal3} (known as CSS construction) and \cite{steane} (Steane construction). Since then, researchers have been working on various ways of obtaining quantum codes from classical codes. More recently, codes over extension rings have attracted a lot of attention. Many quantum codes in the literature have been obtained via the method of considering codes over an extension ring $S$ of a base/ground ring (or field) $R$ and using a map to eventually obtain codes over the ground ring $R$. We show that in many cases, there is no need to obtain these codes in such indirect way. We have obtained many of these best known codes presented in the literature, and even better ones, by using a direct approach. It is preferable to obtain codes in more direct ways with good algebraic structures. \section{Preliminaries} \begin{definition} \cite{mt} For each $i=1,\dots,\ell$, let $m_i$ be a positive integer and $a_i\in \mathbb{F}_q ^{*}=\mathbb{F}_q\setminus \{0\}$. A multi-twisted (MT) module $V$ is an $\mathbb{F}_q[x]$-module of the form \[V = {\displaystyle\prod_{i=1}^\ell \mathbb{F}_q[x] / \langle x^{m_i} - a_i \rangle},\] An MT code is an $\mathbb{F}_q[x]$-submodule of an MT module $V$. \end{definition} Equivalently, we can define an MT code in terms of the shift of a codeword. Namely, a linear code $C$ is MT if for any codeword $$\vec{c}=(c_{1,0},\dots, c_{1,{m_1-1}}; c_{2,0},\dots, c_{2,{m_2-1}};\dots;c_{\ell,0},\dots, c_{\ell,{m_{\ell}-1}})\in C,$$ \noindent its multi-twisted shift $$(a_1c_{1,m_1-1},c_{1,0},\dots, c_{1,{m_1-2}}; a_2c_{2,m_2-1},c_{2,0},\dots, c_{2,{m_2-2}};\dots; a_{\ell}c_{\ell,m_{\ell}-1},\dots, c_{\ell,{m_{\ell}-2}})$$ \noindent is also a codeword. If we identify a vector $\vec{c}$ with $C(x)=(c_1(x),c_2(x),\dots,c_{\ell}(x))$ where $c_i(x)=c_{i,0}+c_{i,1}x+\cdots+c_{i,m_i-1}x^{m_i-1}$, then the MT shift corresponds to $xC(x)=(xc_1(x) \mod x^{m_1}-a_1, \dots, xc_{\ell}(x) \mod x^{m_{\ell}}-a_{\ell})$. The following are some of the most important special cases of MT codes: \begin{itemize} \item $a_1=a_2=\dots=a_{\ell}$ gives QT codes \item $a_1=a_2=\dots=a_{\ell}=1$ gives QC codes \item $\ell=1, a_1=1$ gives cyclic codes \item $\ell=1, a_1=-1 $ gives negacyclic codes \item $\ell=1$ gives constacyclic codes \end{itemize} There has been much research on QT codes, a special case of MT codes. Hundreds of new codes have been obtained from QT codes by computer searches. An algorithm called ASR has been particularly effective in this regard.The ASR algorithm is based on the following theorem. \begin{theorem}\label{theorem:ASR} \cite{qtmain} Let C be a 1-generator QT code of length $n = m\ell$ over $\mathbb{F}_q$ with a generator of the form $$(g(x)f_1(x), g(x)f_2(x), . . . , g(x)f_{\ell}(x))$$ where $x^m - a = g(x)h(x)$ and $\gcd(h(x),f_i(x)) = 1$ for all $i = 1,...,\ell$. Then $dim(C) = m -deg(g(x))$, and $d(C) \geq \ell\cdot d$ where $d$ is the minimum distance of the constacyclic code $C_g$ generated by $g(x)$. \end{theorem} This algorithm has been refined and automatized in more recent works such as (\cite{gf2}, \cite{gf7}, \cite{gf3}, \cite{nonprime}, \cite{oliverequiv}) and dozens of record breaking codes have been obtained over every finite field $\mathbb{F}_q$, for $q=2,3,4,5,7,8,9$ through its implementation. Moreover, it has been further generalized in \cite{ICY} and more new codes were discovered that would have been missed by its earlier versions. We can consider MT analogues of the QT codes given in the previous theorem. The following theorem gives a fact about duals of such codes. \begin{theorem} Let an $C=\langle g_1(x),g_2(x),g_3(x),...,g_{\ell}(x) \rangle$ be an MT code such that the constacyclic codes generated by $g_i(x)$ have the same length $n$ and the same dimension $k$ for $i=1,2,...,\ell$. Let $D_i$ be the dual of $\langle g_i(x) \rangle$. Let $PD=D_1\times D_2\times \dots \times D_{\ell}$. Then $PD$ is contained in $C^{\perp}$. \end{theorem} \begin{proof} Let $G_i$ be a generator matrix of $C_i=\langle g_i(x)\rangle$, so a generator matrix $G$ of $C$ is given by \begin{align*} G= \begin{pmatrix} G_1&G_2&G_3&...&G_l \end{pmatrix}_{k\times \sum_{i=1}^{l} n_i}. \end{align*} Let $H_i$ be a generator matrix of $D_i=C_i^{\perp}$. Then a generator matrix $GPD$ of $PD$ is given by \begin{align*} GPD= \begin{pmatrix} H_1&0&0&...&0\\ 0&H_2&0&...&0\\ 0&0&H_3&...&0\\ \ddots&\ddots&\ddots&\ddots&\ddots\\ 0&0&0&...&H_l \end{pmatrix}_{(n-k)l \times \sum_{i=1}^{\ell} n_i}. \end{align*} It is readily verified that $G\cdot GPD=0$. Note that the dimension of $C^{\perp}$ is $\sum_{i=1}^{\ell} n_i-k$ and the dimension of $PD$ is $\sum_{i=1}^{\ell}(n_i-k)$, so the dimension of $PD$ is $\leq$ the dimension of $C^{\perp}$. Hence, $PD\subseteq C^{\perp}$. \end{proof} \section{A Special Type of MT Codes} We first introduced a special type of MT codes that we called ICY codes in \cite{ICY}. The basic idea for this construction is inspired by the well known fact that any linear code is equivalent to a linear code whose generator matrix is of the form $G= [I_k \mid A]$ where $I_k$ is the $k \times k$ identity matrix and $A$ is a $k \times n-k$ matrix. A code with a generator matrix in this form is called a systematic code. In this search method, we begin with a $k \times k$ identity matrix on the left and append it with $k \times n-k$ circulant matrices on the right. The circulant matrix is constructed using a generator polynomial $g(x) | x^{n-k} - a$ of a constacyclic code (obtained using the partition program from \cite{oliverequiv}). For each polynomial $g(x)$, we consider a number of circulant matrices obtained from polynomials $g(x) \cdot f(x)$ where $\gcd(f(x), h(x)) = 1$, with the goal of finding a code with minimum distance equal to or greater than the BKLCs for parameters $[n, k]_q$. In \cite{ICY} we were able to find many good codes over $GF(2)$ and $GF(5)$. In this paper we present a number of optimal codes over $GF(2)$ with parameters $[2\cdot k, k]$ obtained from an implementation of this method. A number of these codes we found are also self-dual, which makes these codes even more useful. \begin{lemma} \label{theorem:ICY 2kk GF(2)} If f(x) is a monomial and the block length of $\langle f(x)\rangle$ is the same as the block length of the identituy matrix, then the MT code $C$ over GF(2) generated by $\langle 1,f(x)\rangle$ is always self-dual, reversible and of minimum distance 2. In particular, if the monomial is a constant, then $C$ is a cyclic code. \end{lemma} \begin{proof} Let $f(x)=x^i$ be a monomial and the block length of $\langle f(x)\rangle$ be the same as $k\times k$ identity matrix. Then the generator matrix of the MT code $C$ over $GF(2)$ generated by $\langle 1,f(x)\rangle$ is given by: \begin{align*} G= \begin{pmatrix} 1&0&...&0&\aug&0&...&1&0&...\\ 0&1&...&0&\aug&0&...&0&1&...\\ \ddots&\ddots&\ddots&\ddots&\aug&\ddots&\ddots&\ddots&\ddots&\ddots\\ 0&0&...&1&\aug&...&1&0&0&...\\ \end{pmatrix}_{k \times 2k}. \end{align*} It is easy to verify that the reverse of the $j^th$ row is the $(k-i+1-j)^th$ row, so it follows that $C$ is reversible. Also note that each row of $G$ is orthogonal to itself and also orthogonal to every other row, so given $k=2k/2$ we know $C$ is also self-dual. Moreover, since each row is of weight 2, and both matrices are circulant, it follows that $C$ is of minimum distance 2. Specifically, if $f(x)=1$, then the generator matrix $G$ is given by \begin{align*} G= \begin{pmatrix} 1&0&...&0&\aug&1&...&0&...\\ 0&1&...&0&\aug&0&1&0&...\\ \ddots&\ddots&\ddots&\ddots&\aug&\ddots&\ddots&\ddots&\ddots\\ 0&0&...&1&\aug&...&0&...&1\\ \end{pmatrix}_{k \times 2k}. \end{align*} Hence, the code is a cyclic code of length $2k$ generated by $f(x)=x^k-1|x^{2k}-1$. \end{proof} The following codes in Table 1 are obtained by ICY method where we chose $n=2k$, so each one of these codes has parameters $[2k,k,d]$. All of these codes are optimal with additional properties of being reversible and/or self orthogonal. For the circulant matrix on the right, we used a random $m \times m$ circulant matrix by choosing a random vector and taking its cyclic shifts. This polynomial is given in the table. We also checked condition for reversibility and self-duality. Note that self-orthogonality is the same as self-duality since we set $n=2k$. In this search, the binary field fields turned out to be most promising. In this and every subsequent table presented in this paper the terms of the generator polynomials are listed in ascending order from left to right. For instance, the first generator polynomial $[111]$ in this table is the vector representation of $g(x) = 1 + x + x^2$. \begin{small} \begin{singlespacing} \label{tab:Table1} \begin{longtable}{ p{2cm}p{4.6cm} } \caption*{Table 1: Optimal codes from ICY method with several properties. Here, $^*$ delineates a reversible code, and $^\circ$ delineates a self-dual code.} \\ \hline\noalign{\smallskip} $[n,k,d]_{q}$ & Polynomials \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[8, 4, 4]_2$ $^{* \circ}$ & $g=[111]$\\ $[10, 5, 4]_2$&$g=[10101]$\\ $[12,6,4]_{2}$ $^{* \circ}$ &$g=[110111]$\\ $[14,7,4]_{2}$ &$g= [111101]$ \\ $[20,10,6]_{2}$ &$g= [11111011]$ \\ $[24, 12, 8]_2$ $^{* \circ}$ & $g=[101111011]$\\ $[28,14,8]_{2}$ &$g= [11101111001001]$ \\ $[32, 16, 8]_2$ $^{* \circ}$ & $g=[1100100001100011]$\\ $[36, 18, 8]_2$ $^{* \circ}$ & $g=[111010010111001]$\\ $[42,21,10]_{2}$ &$g= [11110011011011101001]$ \\ $[48, 24, 12]_{2}$ $^{* \circ}$ &$g= [10111101001011110011101]$ \\ $[16,8,6]_{3}$ $^*$ &$g= [212222]$ \\ $[18,9,6]_{3}$ $^*$ &$g= [201002222]$ \\ $[20,10,7]_{3}$ $^*$ &$g= [112012102]$ \\ $[30,15,9]_{3}$ $^*$ &$g= [201212222200121]$ \\ $[14,7,6]_{4}$ $^{* \circ}$ &$g= [\alpha\alpha\alpha^2\alpha\alpha^2\alpha^2]$ \\ $[20,10,8]_{4}$ $^{* \circ}$ &$g=[\alpha\alpha1\alpha00\alpha^2 1\alpha^2\alpha^2]$ \\ $[24,12,9]_{4}$ &$g=[10\alpha\alpha^2\alpha\alpha^2 \alpha10\alpha1]$ \\ $[14,7,6]_{5}$ &$g= [3343442]$ \\ $[16,8,7]_{5}$ &$g= [34404411]$ \\ $[12,6,6]_{7}$ &$g= [551641]$ \\ $[14,7,7]_{7}$ &$g= [5226211]$ \\ $[16,8,7]_{7}$ &$g= [42325344]$ \\ $[18,9,8]_{7}$ &$g= [524635101]$ \\ [.5ex] \noalign{\smallskip}\hline \end{longtable} \end{singlespacing} \end{small} The next table presents a list of optimal self-dual codes together with their weight enumerators obtained by this method. For codes over $GF(4)=\{0,1,\alpha,\alpha+1 \}$, $\alpha$ is a root of $x^2+x+1$ over the binary field. Again, $^*$ delineates a reversible code. \begin{singlespacing} \begin{footnotesize} \label{tab:2} \begin{longtable}{ p{1.8cm}p{1.3cm}p{4.5cm}p{4.48cm} } \caption*{Table 2: Optimal self-dual code from ICY method. } \\ \hline\noalign{\smallskip} $[n,k,d]_{q}$ &Type& weight enumerator & Polynomials \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[8, 4, 4]_2$ $^{*}$ &II&\scriptsize $A^8 + 14A^4 + 1$ & $g=[111]$\\ $[12,6,4]_{2}$ & $I$&\scriptsize $A^{12} + 15A^8 + 32A^6 + 15A^4 + 1$ &$g=[110111]$\\ [.5ex] $[16,8,4]_{2}$ $^*$ &$II$&\scriptsize $A^{16} + 28A^{12} + 198A^8 + 28A^4 + 1$ &$g=[110111]$\\ [.5ex] $[16,8,4]_{2}$ $^*$ &$I$&\scriptsize $A^{16} + 12A^{12} + 64A^{10} + 102A^8 + 64A^6 + 12A^4 + 1$ &$g=[1010111]$\\ [.5ex] $[18, 9, 4]_2$ $^*$ &$I$& $\scriptsize A^{18} + 9A^{14} + 75A^{12} + 171A^{10} + 171A^8 + 75A^6 + 9A^4 + 1$ & $g=[11011001]$\\ $[20,10,4]_{2}$ $^*$ &$I$&\scriptsize $A^{20} + 45A^{16} + 210A^{12} + 512A^{10} + 210A^8 + 45A^4 + 1$ &$g=[1011111111]$\\ [.5ex] $[22,11,6]_{2}$ $^*$ &$I$&\scriptsize $ A^{22} + 77A^{16} + 330A^{14} + 616A^{12} + 616A^{10} + 330A^8 + 77A^6+ 1$ &$g=[1001011]$\\ [.5ex] $[26,13,6]_{2}$ &$I$& \scriptsize$A^{26} + 52A^{20} + 390A^{18} + 1313A^{16} + 2340A^{14} + 2340A^{12} + 1313A^{10} + 390A^8 + 52A^6 + 1$ &$g=[10111110111]$\\ [.5ex] $[52,26,10]_{2}$ &$I$& \scriptsize$A^{52} + 442A^{42} + 6188A^{40} + 53040A^{38} + 308958A^{36} + 1270360A^{34} + 3754569A^{32} + 8065616A^{30} + 12707500A^{28} + 14775516A^{26} +12707500A^{24} + 8065616A^{22} + 3754569A^{20} + 1270360A^{18} + 308958A^{16} + 53040A^{14} + 6188A^{12} + 442A^{10} + 1$ &$g=[1001111100101010100100101]$\\ $[14,7,6]_{4}$ $^*$ & $Euclidean$ &\scriptsize $318A^{14} + 1302A^{13} + 2940A^{12} + 3990A^{11} + 3738A^{10} + 2226A^{9}+ 1155A^8 + 546A^7 + 168A^6 + 1$ &$g=[\alpha1\alpha\alpha^2\alpha\alpha\alpha^2]$\\ [.5ex] $[16,8,6]_{4}$ $^*$ &$Euclidean$ &\scriptsize $681A^{16} + 3696A^{15} + 7896A^{14} + 14112A^{13} + 16464A^{12} + 9408A^{11} + 7392A^{10} + 4704A^9 + 678A^8 + 336A^7 + 168A^6 + 1$ &$g=[\alpha\alpha1\alpha^2\alpha\alpha^2]$\\ [.5ex] $[20,10,8]_{4}$ $^*$ &$Euclidean$ &\scriptsize $171A^{12} + 432A^{11} + 864A^{10} + 1440A^9 + 459A^8 + 432A^7 + 288A^6 + 9A^4 + 1$ &$g=[\alpha\alpha1\alpha00\alpha^2\alpha^2\alpha^2]$\\ $[22,11,8]_{4}$ $^*$ &$Euclidean$ &\scriptsize $171A^{12} + 432A^{11} + 864A^{10} + 1440A^9 + 459A^8 + 432A^7 + 288A^6 + 9A^4 + 1$ &$g=[\alpha^2\alpha\alpha\alpha^2010\alpha \alpha^2\alpha^2\alpha]$\\ [.5ex] \noalign{\smallskip}\hline \end{longtable} \end{footnotesize} \end{singlespacing} \section{Reversible Codes} Reversible codes are essential in application of coding theory to DNA computing \cite{dna2}. Each single DNA strand is composed of a sequence of four bases nucleotides (adenine (A), guanine (G), thymine (T), cytosine (C) ) and it is paired up with a complementary strand to form a double helix\cite{dna}. Finding reversible codes is an essential requirement in order to find codes suitable for DNA computing. Also, reversible codes may be used in certain data storage applications \cite{mas}. For example, one just needs to read the stored data from either end of a block code. In this paper, we present a general method to construct reversible $\ell$-block MT, QT and QC codes, and a number of good reversible QC codes over $GF(2)$ are obtained using this method. The codes presented in Table 3 are reversible and self orthogonal QC with the same parameters as BKLCs over $GF(2)$. Hence they are more desirable than BKLCs that do not have these properties. In checking the reversibility of these codes, we used the conditions for reversibility of QC codes given in \cite{qcReversible}. Theorem 1 in section IV of \cite{qcReversible} presents three conditions for reversibility of QC codes with generator matrices of the form $[g(x), g(x) \cdot f(x)]$, where $g(x) | x^m-1$ and $\gcd(f(x), h(x))) = 1$. After finding all nonequivalent generators $g(x)$ for a given block length $m$, we check the first two conditions on $g(x)$ and $h(x)$ before proceeding. If these two checks pass, then we generate random polynomials $f(x)$ that satisfy the third condition in the theorem, resulting in a reversible QC code. Additionally, since these QC codes are constructed over $GF(2)$ they have the added property of being self-orthogonal. Theorem 1 also provides conditions for self-orthogonality of QC codes with such generator matrices and in the binary case these conditions are the same as those for reversibility. For a polynomial $f(x)$, it is customary to denote its reciprocal by $f(x)^{*}$. \begin{theorem} Let $g_i|x^{n_i}-a_i$ and $\gcd(h_i,f_i)=1$ for $i=1,2,...,\ell$, where $h_i=\frac{x^{n_i}-a_i}{g_i}$. If $\deg(g_if_i)=\deg(g_{\ell+1-i}f_{\ell+1-i})$, $n_i=n_{\ell+1-i}$ and $g_if_i=(g_{\ell+1-i}f_{\ell+1-i})^*$ for $i=1,2,..,\ell$, then the MT code $C$ generated by $(g_1f_1,\dots,g_{\ell}f_{\ell})$ is reversible. \end{theorem} \begin{proof} Let $g_if_i=a_{i,0}+a_{i,1}x +\cdots +a_{i,k_i}x^{k_i}$, so the generator matrix of this MT code with $\ell$ blocks is given by \begin{align*} G=\begin{pmatrix} G_1&G_2&...&G_{l-1}&G_l \end{pmatrix}, \end{align*} where $G_i$ is \begin{align*} G_i= \begin{pmatrix} a_{i,0} &a_{i,1} &a_{i,2}&...&a_{i,k_i}&0&0&...\\ 0 &a_{i,0} &a_{i,1}&...&a_{i,k-1}&a_{i,k_i}&0&...\\ \vdots &\ddots & \ddots & \ddots &\ddots&\ddots&\ddots &\ddots\\ 0 & 0&... &a_{i,0}&a_{i,1}&a_{i,2}&...&a_{i,k_i}\\ \end{pmatrix}_{(n_i-k_i) \times n_i}. \end{align*} Hence, the reversed first row of $G$ is given by \begin{align*} (&0,...,0,a_{\ell,k_\ell},a_{\ell,k_\ell-1},...,a_{\ell,1},a_{\ell,0};\\&0,...,0,a_{\ell-1,k_{\ell-1}},a_{\ell-1,k_{\ell-1}-1},...,a_{\ell-1,1},a_{\ell-1,0};\\&\vdots\\&0,...,0,a_{1,k_1},a_{1,k_1-1},...,a_{1,1},a_{1,0}). \end{align*} Note that $g_if_i=(g_{\ell+1-i}f_{\ell+1-i})^*$ for $i=1,2,..,\ell$, so $a_{i,j}=a_{\ell+1-i,k-j+1}$ for $i=1,2,..,\ell$ and $j=1,2,...,k$. Also, since the degree of all $\deg(g_if_i)=\deg(g_{\ell+1-i}f_{\ell+1-i})$, it is not hard to see that the reversed first row is the $(n-k)^{th}$ row, and in general the reversed $j^{th}$ row is the same as $(n-k+1-j)^{th}$ row. Therefore, the reverse of each row in $G$ is in $G$, so $C$ is reversible. \end{proof} As mentioned previously all of these codes were constructed using the conditions for a $2-$QC code to be reversible found in \cite{qcReversible}. This paper gives conditions on the generator polynomials $g(x)$ and $f(x) \cdot g(x) \mod(x^m-1)$ with $\gcd(h(x), f(x)) = 1$ so the first polynomial presented in this table is $g(x)$, and the second one is $f(x) \cdot g(x) \mod(x^m-1)$. \begin{small} \begin{singlespacing} \label{tab:3} \begin{longtable}{p{2cm} p{8cm}} \caption*{Table 3: Reversible and Self-Orthogonal Binary QC Codes with best-known parameters} \\ \hline\noalign{\smallskip} $[n,k,d]$ & Polynomials \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[60,28,12]$ & [00101100111001101100101001101], [111] \\ $[60,29,12]$ & [000111000101011000100100011111], [11] \\ $[72,29,16]$ & [011111101110101111101101100111101011], [10111101] \\ $[72,30,16]$ & [0110111100000111111100010010111001], [1101011] \\ $[80,37,16]$ & [1010011110001011110000000111110001110001], [1111] \\ $[80,38,16]$ & [0011111110101010100100101101110101011], [101] \\ $[84,24,24]$ & [111100010111100111000111101110000000100101], [1010100000000010101] \\ $[84,25,24]$ & [001111100001011100110011110100001101000111], [110011111111110011] \\ $[84,26,24]$ & [001101010011000011101100000100001110001101], [11100000000000111] \\ $[84,27,24]$ & [001001101000110101101001110110000011000001], [1011111111111101] \\ $[90,28,24]$ & [011111010111100100001011100011000011110000001], [110111011110111011] \\ $[90,34,20]$ & [00010111011111110110000000011010111111101101], [110001100011] \\ $[96,36,20]$ & [10010100100000001100000001110111001001100111001], [1010001000101] \\ $[96,37,20]$ & [01100110011010101011011110010011101110010010011], [100110011001] \\ $[96, 38, 20]$ & [110011110011101110010010111100100111011010101], [11101110111] \\ $[100,41,20]$ & [00110100011011100110001010100100101010000111001001], [1111111111] \\ $[102,34,24]$ & [10011111000011100010010001100001100001101110101], [101110111111011101] \\ $[102,42,20]$ & [1010110010011100000100111101101100110001000000101], [1001111001] \\ $[104,36,24]$ & [1010111000101110001001010010110111001001101110110101], [11110000000001111] \\ $[108,46,20]$ & [110000001010000001101111000101010010011011101000001], [111111111] \\ $[110,40,24]$ & [110111111111101000011111110110011000010001011111000111], [1111100000011111] \end{longtable} \end{singlespacing} \end{small} \section{Quantum Codes} In comparison to classical information theory, the field of quantum information theory is relatively young and there is still a lot of room for further study. The idea of quantum error correcting codes was first introduced in \cite{Quantumoriginal1} and \cite{Quantumoriginal2}. A method of constructing quantum error correcting codes (QECC) was given in \cite{Quantumoriginal3}. Since then researchers have investigated various methods of using classical error correcting codes to construct new QECCs. The majority of the methods have been based on the CSS construction given in \cite{Quantumoriginal3}. In this method, self-dual, self-orthogonal and dual-containing linear codes are used to construct quantum codes. The CSS construction requires two linear codes $C_1$ and $C_2$ such that $C_2^{\perp}\subseteq C_1$. Hence, if $C_1$ is a self-dual code, then we can construct a CSS quantum code using $C_1$ alone since $C_1^{\perp}\subseteq C_1$. If $C_1$ is self-orthogonal, then we can construct a CSS quantum code with $C_1^{\perp}$ and $C_1$ since $C_1^{\perp}\supseteq C_1$. Similarly in the case $C_1$ is a dual-containing code. The last few tables in this section give some good QECCs obtained from both the CSS method and the method of additive codes. A number of these codes have the same parameters as those found in the literature but we obtained them using more direct and simpler constructions. Additionally, we have found other codes whose parameters do not appear in the literature. The following codes are constructed using the method of quantum codes constructed from additive codes \cite{Quantumoriginal3}. After generating all divisors $g(x)$ of $x^m - a$ that generate non equivalent constacyclic codes and finding a generator matrix of the form $[C_{g(x) \cdot f_{1}(x)}, C_{g(x) \cdot f_{2}(x)}]$ where $\gcd(f_{i}(x), h(x))) = 1$ and $C_g(x)$ represents the circulant matrix from $g(x)$, we construct an additive code from this generator matrix and check it for symplectic self orthogonality. If this check passes, then we construct a quantum code from this additive code and compute its minimum distance. Then we can compare the minimum distance of these codes against the comparable best known QECCs given in the database codetables.de. \vspace{2mm} In Table 4, all of the codes are optimal quantum QT codes constructed over $GF(2^2)$. Note that $\alpha$ is a root of the irreducible polynomial $x^2 + x + 1$ over $GF(2)$. \begin{small} \begin{singlespacing} \label{tab:4} \begin{longtable}{ p{1.8cm} p{9.8cm}} \caption*{Table 4 : Optimal quantum codes over GF($2^2$) from QT Codes} \\ \hline\noalign{\smallskip} $[n,k,d]$ & Polynomials \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[[54,47,2]]$ & $[00\alpha^21110\alpha000\alpha^21110\alpha000\alpha^21110\alpha]$, \\ & $[\alpha^2\alpha\alpha^201\alpha^2\alpha0\alpha\alpha^2\alpha\alpha^201\alpha^2\alpha0\alpha\alpha^2\alpha\alpha^201\alpha^2\alpha0\alpha]$ \\ $[[56,50,2]]$ & $[10000\alpha^2\alpha\alpha1\alpha^21\alpha^2\alpha1\alpha^2\alpha\alpha\alpha\alpha100\alpha^21\alpha^210\alpha^2]$, \\ & $[\alpha^210011\alpha\alpha\alpha^21\alpha0\alpha^2\alpha^20\alpha\alpha^2\alpha^2\alpha\alpha110\alpha1\alpha^2]$ \\ $[[70,64,2]]$ & $[10\alpha^2\alpha010\alpha0\alpha\alpha1\alpha\alpha\alpha001\alpha\alpha\alpha^210\alpha0\alpha1\alpha^200\alpha^2110\alpha]$, \\ & $[\alpha^201\alpha^2\alpha\alpha\alpha^2\alpha\alpha^2101\alpha^2\alpha^201\alpha^2\alpha^20\alpha^2\alpha\alpha1011\alpha0\alpha^2\alpha^2\alpha^21\alpha0\alpha]$ \\ $[[88,80,2]]$ & $[100\alpha^21\alpha\alpha101\alpha^2\alpha\alpha\alpha^21\alpha01\alpha^2\alpha^2\alpha^20011\alpha0\alpha^2\alpha^2010\alpha\alpha^2\alpha^2\alpha0\alpha^210\alpha\alpha\alpha1]$, \\ & $[0\alpha^211\alpha00\alpha^2000100\alpha\alpha^2\alpha^2101\alpha^21\alpha1\alpha^2\alpha^20\alpha\alpha1\alpha\alpha\alpha\alpha^2\alpha\alpha011\alpha^2\alpha\alpha^21\alpha^2]$ \\ $[[98,91,2]]$ & $[11\alpha^2101011\alpha^2101011\alpha^2101011\alpha^2101011\alpha^2101011\alpha^2101011\alpha^2101]$, \\ & $[\alpha\alpha000\alpha^20\alpha\alpha000\alpha^20\alpha\alpha000\alpha^20\alpha\alpha000\alpha^20\alpha\alpha000\alpha^20\alpha\alpha000\alpha^20\alpha\alpha000\alpha^2]$ \\ \noalign{\smallskip}\hline \end{longtable} \end{singlespacing} \end{small} We also found some QECCs whose parameters do not appear in the literature. Hence, we consider them new quantum codes. The inspiration for this idea came from \cite{preprint}. These codes are obtained using direct sums of two cyclic codes, with generators $g_1(x), g_2(x)$ that are divisors of $x^m - 1$. Each $g_{i}(x)$ generates a dual containing cyclic code $C_i=\langle g_i(x)\rangle$ which implies that their direct sum $C_1\times C_2$ is also dual containing. So, the CSS method can be used with the direct sum code and its dual. The resultant QECC will have parameters $[[2 \cdot m, 2\cdot k - 2 \cdot m, d]]_q$. Here, $k$ is defined to be the dimension of the direct sum code which is equal to $k_1 + k_2$, the sum of the dimensions of the individual cyclic codes, and $d$ is the minimum of the minimum distances of the cyclic codes generated by $g_1(x)$ and $g_2(x)$. Table 5 contains these new codes. \label{tab:5} \begin{longtable}{p{2cm} p{2cm} } \caption*{Table 5 : New QECCs} \\ \hline\noalign{\smallskip} $[[n,k,d]]_q$ & Polynomials \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[[60,54,2]]_3$ & $[21], [201] $ \\ $[[72,68,2]]_3$ & $[21], [21] $ \\ $[[84,80,2]]_3$ & $[21], [21] $ \\ $[[100,96,2]]_5$ & $[41], [41] $ \\ \noalign{\smallskip}\hline \end{longtable} Next, we have a number of codes that have the same parameters as the best known QECCs presented in the literature. Our codes have the advantage that they are obtained in a more direct and simple construction. They were all obtained using the same method as the codes in the previous table. Codes with the same parameters listed in Table 6 were found using more complex and indirect methods detailed in \cite{QuantumTables1}, \cite{QuantumTables2}, \cite{QuantumTables3} , \cite{QuantumTables4}, \cite{QuantumTables5}, \cite{QuantumTables6}. These constructions usually involve considering an extension ring $S$ of a ground ring or field $R$, constructing a code over the extension ring, then coming back to $R$ using some sort of Gray map. We argue that it is more desirable to construct codes with the same parameters using a more direct approach. \label{tab:6} \begin{longtable}{p{2cm} p{2cm} p{1cm}} \caption*{Table 6 : QECC ties} \\ \hline\noalign{\smallskip} $[[n,k,d]]_q$ & Polynomials & Source \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[[72,66,2]]_3$ & $[21], [111]$ & \cite{QuantumTables3}\\ $[[84,78,2]]_3$ & $[21], [201]$ & \cite{QuantumTables1} \\ $[[40,36,2]_5$ & $[41], [41] $ & \cite{QuantumTables5} \\ $[[40,34,2]]_5$ & $[41], [131] $ & \cite{QuantumTables1} \\ $[[40,28,3]]_5$ & $[3011], [3011] $ & \cite{QuantumTables5} \\ $[[60,54,2]]_5$ & $[41], [131] $ & \cite{QuantumTables3} \\ $[[90,84,2]]_5$ & $[41], [131] $ & \cite{QuantumTables4}\\ $[[100,94,2]]_5$ & $[41], [401] $ & \cite{QuantumTables1} \\ $[[140,134,2]]_5$ & $[41], [401] $ & \cite{QuantumTables6} \\ \noalign{\smallskip}\hline \end{longtable} \subsection{New Quantum Codes from Constacyclic Codes and a Result About Binomials} In this section, we obtain new QECCs that are constructed by the method of CSS construction from constacyclic codes over finite fields. These codes are new in the sense that either there do not exist codes with these parameters in the literature (to the best of our knowledge) or the minimum distances of our codes are higher than the codes that are presented in the literature. Our work on this also led to a couple of theoretical results about the binomials of the form $x^n-a$ over $\mathbb{F}_q$. The first one (Theorem 5.3 below) is similar to Theorem 4.1 in \cite{mt}. We start with the results on binomials. \begin{lemma} Let $\alpha,\beta\in \mathbb{F}_q$ and $\alpha\not=\beta$, where $q$ is a power of a prime $p$. Then for all $m\in\mathbb{Z}^{+}$, $\alpha^{p^m}\not=\beta^{p^m}$. \end{lemma} \begin{proof} Since $\alpha\not=\beta$, it follows that \begin{align*} (\alpha-\beta)^{p^m}&\not=0\\ \alpha^{p^m}-\beta^{p^m}&\not=0\\ \alpha^{p^m}&\not=\beta^{p^m} \end{align*} \end{proof} \begin{theorem} Let $q$ be a power of a prime $p$ and let $\alpha\in \mathbb{F}_q$. Then for any $m\in \mathbb{Z}^{+}$, there exists a unique $\beta\in \mathbb{F}_q$ such that $\alpha=\beta^{p^m}$. \end{theorem} \begin{proof} Let $\mathbb{F}_q=\{a_1,a_2,...,a_q\}$. Given previous lemma, for any $\alpha,\beta\in \mathbb{F}_q$, where $\alpha\not=\beta$, we have $\alpha^{p^m}\not=\beta^{p^m}$. Hence, $\mathbb{F}_q=\{a_1,a_2,...,a_q\}=\{a_1^{p^m},a_2^{p^m},...,a_q^{p^m}\}$. Since $\alpha\in \mathbb{F}_q$, it follows that $\alpha\in\{a_1^{p^m},a_2^{p^m},...,a_q^{p^m}\}$. Therefore, there must be a unique $\beta\in \mathbb{F}_q$ such that $\alpha=\beta^{p^m}$. \end{proof} \begin{theorem} Let $n\in \mathbb{Z}^{+}$, $q$ be a prime power and $a,b\in \mathbb{F}_q$ such that $a\not=b$. Then $\gcd(x^n-a,x^n-b)=1$ . \end{theorem} \begin{proof} Let $\delta$ be a root of $x^m-a$. Then for any $k\in \mathbb{Z}^{+}$, it follows that \begin{align*} (\delta^k)^{m}-b=(\delta^m)^k-b=a-b\not=0 \end{align*} Hence, the polynomials $x^m-a$ and $x^m-b$ share no common roots. Therefore, $\gcd(x^n-a,x^n-b)=1$. \end{proof} \begin{theorem} Let $q$ be a power of prime $p$, and let $g(x)=x^n-a\in \mathbb{F}_q[x]$. Then all irreducible factors of $x^n-a$ have the same multiplicity $p^z||n$, where $z$ is the largest positive integer such that $p^z$ divides $n$. \end{theorem} \begin{proof} Let $n=p^z\cdot b$, where $\gcd(b,p)=1$. Given Theorem 5.2, $x^n-a$ can be written as \begin{align*} x^n-a&=x^{p^z\cdot b}-a\\ &=(x^{b}-a')^{p^z}, \end{align*} where $a'\in \mathbb{F}_q$. Let's call $f(x)=x^{b}-a'$, and then consider $\gcd(f(x),f'(x))$. Note that $b\not =0$ and $x^{b}-a'$ is not a multiple of $x$, so it follows that $\gcd(f(x),f'(x))=\gcd(x^{b}-a',bx^{b-1})=1$. Hence, all irreducible factors of $f(x)=x^b-a'$ have the same multiplicity 1. Therefore, all irreducible factors of $g(x)=x^n-a=f^{p^z}(x)$ have the same multiplicity $p^z$. \end{proof} By the definition of CSS construction, we need two codes such that one is contained in the dual of the other one. By ideals inclusion we know that \begin{align*} \langle g(x)f(x) \rangle \subseteq \langle g(x) \rangle \end{align*} and we consider $C_2^{\perp}=\langle g(x)f(x)\rangle \subseteq \langle g(x) \rangle =C_1 $. Here $g(x)$ is a divisor of a binomial $x^n-a$ and it generates a constacyclic code. Since for a given $n\in\mathbb{Z}^{+}$ and distinct elements $\alpha,\beta\in \mathbb{F}_q$, $\gcd(x^n-\alpha,x^n-\beta)=1$, it follows that for any divisor $g(x)|x^n-\alpha$, we have $g(x)f(x)\not | x^n-\beta$ for any $f(x)\in \mathbb{F}_q[x]$. In other words, for a given $C_1=\langle g \rangle$, where $g|x^n-\alpha$, all possible constacyclic codes of the same length $C_2^{\perp}$ such that $C_2^{\perp}\subseteq C_1$ have the form $C_2^{\perp}=\langle gf\rangle$, where $gf|x^n-\alpha$. Hence, for given $\alpha\in \mathbb{F}_q$ and $n$, we only need to consider $g_i|x^n-\alpha$ and $g_if_i|x^n-\alpha$. By Theorem 5.3, any generator of $C_2^{\perp}$ will be a divisor of $x^n-\alpha$, and not $x^n-\beta$ for $\beta\not = \alpha$. Also, based on the multiplicity of all irreducible factors of $x^n-\alpha$, for any $g(x)$, we can determine all $g(x)f(x)$ by enumerating all possible combinations of multiplicities of irreducible factors. Therefore, our algorithm goes through every possible pair of $g(x)$ and $g(x)f(x)$, and we view each $\langle g(x)\rangle$ as $C_1$ and each $\langle g(x)f(x) \rangle$ as $C_2^{\perp}$ in the CSS construction. This way, we obtained many new QECCs. The new codes we obtained are of two types: i) those that have higher minimum distances than the codes given in the literature, ii) those whose parameters do not appear in the literature. We present them in the following two tables. \begin{small} \begin{singlespacing} \label{tab:7} \begin{longtable}{p{2.7cm}p{2.7cm} p{7.5cm} } \caption*{Table 7 : New QECCs that have higher minimum distances than the codes given in the literature} \\ \hline\noalign{\smallskip} Known QECC &New $[[n,k,d]]_q$ & $g(x)$ \& $g(x)f(x)$ \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[[11,1,4]]_5$ \cite{QuantumTables11}&$[[11,1,5]]_5$ & $[124114], [1122031] $ \\ $[[30,20,3]]_5$ \cite{QuantumTables10}& $[[30,20,4]]_5$& $[142241], [14401243413033031434210441] $ \\ $[[40, 32, 2]]_5$ \cite{QuantumTables2}&$[[40, 32, 3]]_5$ & $[12342], [1203022234202444014241112314133340313] $ \\ $[[93, 75,2]]_5$ \cite{QuantumTables12}&$[[93, 75, 4]]_5$ &$[1032243334]$,$[121431401222402220013421431143342442$\\ &&$3124230120124143123112101233022341423121100111211] $ \\ $[[60, 52,2]]_5$ \cite{QuantumTables3}&$[[60, 52, 3]]_5$ &$[10434]$,$[101321202243220133133431344440014124413202$ \\ &&$440312032014321] $ \\ $[[78,60,3]]_3$ \cite{QuantumTables12}&$[[78,60,4]]_5$ &$[1120201112]$,$[120220102221110112120120121022021112$ \\ &&$0012212110210210000100012101020022] $ \\ $[[18,2,3]]_7$ \cite{QuantumTables9}&$[[18,2,6]]_7$ & $[143561634], [14631236125] $ \\ $[[12, 4, 3]]_{13}$ \cite{QuantumTables7}&$[[12, 4, 5]]_{13}$ & $[18554], [184835595] $ \\ $[[24,18,2]]_{17}$ \cite{QuantumTables7}&$[[24,18,3]]_{17}$ & $[1332], [9511521119410532108411631] $ \\ $[[21, 7, 2]]_{19}$ \cite{QuantumTables8}&$[[21, 7, 3]]_{19}$ & $[19999998], [11313131313131319999991] $ \\ \noalign{\smallskip}\hline \end{longtable} \end{singlespacing} \end{small} The final table shows the set of codes we have found whose parameters do not appear in the literature. \begin{small} \begin{singlespacing} \label{tab:8} \begin{longtable}{p{2cm} p{10.8cm} } \caption*{Table 8 : New QECCs} \\ \hline\noalign{\smallskip} $[[n,k,d]]_q$ & Polynomials \\ \noalign{\smallskip}\hline\noalign{\smallskip} $[[61, 41, 5]]_3$ & $[10011111001], [1100101022020121010222110210221110202120101102020022] $ \\ $[[52, 7, 6]]_3$ & $[12211120111], [100000202100102111] $ \\ $[[52, 35, 4]]_3$ & $[110000012], [11020221221200111012111020100112002220020221] $ \\ $[[52, 15, 5]]_3$ & $[12010202], [12200202101110221121201] $ \\ $[[40, 11, 6]]_3$ & $[112100201012], [11112000221100111020001] $ \\ $[[40, 22, 5]]_3$ & $[1222100011], [12220111102211221220021121211111] $ \\ $[[30, 2, 8]]_3$ & $[101101000202101], [10211201020112201] $ \\ $[[32, 2, 7]]_3$ & $[1211021211201002], [122010112001001202] $ \\ $[[30, 10, 4]]_3$ & $[120212022101], [1211111102001211202201] $ \\ $[[30, 16, 4]]_3$ & $[11122111], [110112012020020210211011] $ \\ $[[33, 1, 10]]_3$ & $[12000021012021021], [111000222111222222] $ \\ $[[35, 4, 6]]_3$ & $[12122221121022], [101020002212012112] $ \\ $[[36, 1, 8]]_3$ & $[11120020102002111], [100110211221022002] $ \\ $[[36, 2, 8]]_3$ & $[12212100100121221], [1200122110112210021] $ \\ $[[36, 18, 4]]_3$ & $[1110220111], [1102010202122112212020102011] $ \\ $[[20 , 4, 5]]_3$ & $[112212211], [1122201022211] $ \\ $[[23, 1, 8]]_3$ & $[100202011222], [1202121101001] $ \\ $[[26, 9, 6]]_3$ & $[111122121], [112200100222020102] $ \\ $[[28, 0, 9]]_3$ & $[122221000112122], [122221000112122] $ \\ $[[28, 12, 6]]_3$ & $[111000121], [121100111020121002111] $ \\ $[[14, 2,5]]_3$ & $[1101011], [111202111] $ \\ $[[11, 1, 5]]_5$ & $[124114], [1122031] $ \\ $[[12, 4, 4]]_5$ & $[14102], [140124402] $ \\ $[[16, 1, 6]]_5$ & $[1320214], [11112222] $ \\ $[[20, 4, 6]]_5$ & $[121201212], [1231323013112] $ \\ $[[30, 20, 4]]_5$ & $[142241], [14401243413033031434210441] $ \\ $[[10,2,4]]_7$ & $[12134], [1230661] $ \\ $[[14, 6, 4]]_7$ & $[12056], [12462526421] $ \\ $[[40, 28, 4]]_7$ & $[1455541], [11152236066630031463035562341504546] $ \\ $[[12, 2, 5]]_{13}$ & $[154816], [1582412411] $ \\ \noalign{\smallskip}\hline \end{longtable} \end{singlespacing} \end{small}
{'timestamp': '2020-08-18T02:21:33', 'yymm': '2008', 'arxiv_id': '2008.07037', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07037'}
arxiv
\section{Introduction} \label{sec:intro} This paper presents a new deep architecture for unsupervised few-shot object recognition. In training, we are given a set of unlabeled images. In testing, we are given a small number $K$ of {\em support images} with labels sampled from $N$ object classes that do not appear in the training set (also referred to as unseen classes). Our goal in testing is to predict the label of a \textit{query image} as one of these $N$ previously unseen classes. A common approach to this $N$-way $K$-shot recognition problem is to take the label of the closest support to the query. Thus, our key challenge is to learn a deep image representation on unlabeled data such that it would in testing generalize well to unseen classes, so as to enable accurate distance estimation between the query and support images. This problem is important as it appears in a wide range of applications. For example, we expect that leveraging unlabeled data could help few-shot image classification in domains with very few labeled images per class (e.g., medical images). Another example is online tracking of a previously unseen object in a video, initialized with a single bounding box. Unsupervised few-shot object recognition is different from the standard few-shot learning \cite{snell2017prototypical,finn2017model} that has access to a significantly larger set of labeled images, allowing for episodic training \cite{vinyals2016matching}. Episodic training cannot be used in our setting with a few annotations. \begin{figure*}[t!] \centering \begin{minipage}[t]{0.77\textwidth} \centering \includegraphics[scale=0.36]{images/figures_overview.pdf} \caption{We extend the vanilla GAN to learn an image encoding $z$ on unlabeled data that will be suitable for subsequent few-shot image classification and image retrieval in new domains with very few annotations. Our extension integrates self-supervised and adversarial learning by the means of: (a) Reconstruction loss so the encoding $\hat{z'}$ of a ``fake'' image is similar to the corresponding randomly sampled code $z'$; and (b) Deep metric learning so the image encodings $z$ are closer for similar ``real'' images than for dissimilar ones.} \label{fig:overview} \end{minipage}\hfill% \begin{minipage}[t]{0.2\textwidth} \centering \includegraphics[scale=0.3]{images/discriminator.pdf} \caption{Details of the discriminator from Fig.~\ref{fig:overview} with discriminating head and encoding head.} \label{fig:discriminator} \end{minipage} \end{figure*} There is scant work on unsupervised few-shot classification. Recent work \cite{hsu2018unsupervised,antoniou2019assume,khodadadeh2018unsupervised} first identifies pseudo labels of unlabeled training images, and then uses the standard episodic training \cite{vinyals2016matching} on these pseudo labels. However, performance of these methods is significantly below that of counterpart approaches to supervised few-shot learning. Motivated by the success of Generative Adversarial Networks (GANs) \cite{goodfellow2014generative, donahue2016adversarial, miyato2018spectral} to generalize well to new domains, we adopt and extend this framework with two new strategies for self-supervision \cite{SelfSupervision_Survey}. A GAN is appropriate for our problem since it is a generative model aimed at learning the underlying image prior in an unsupervised manner, rather than discriminative image features which would later be difficult to ``transfer'' to new domains. As shown in Fig.~\ref{fig:overview}, a GAN consists of a generator and discriminator that are adversarially trained such that the discriminator distinguishes between ``real'' and ``fake'' images, where the latter are produced by the generator from randomly sampled latent codes. We extend this framework by allowing the discriminator not only to predict the ``real'' or ``fake'' origins of the input image but also to output a deep image feature, which we will use later for unsupervised few-shot classification task. This allows us to augment the standard adversarial learning of the extended GAN with additional self-supervised learning via two loss functions -- reconstruction loss and distance-metric triplet loss. {\bf Our first contribution:} By minimizing a reconstruction loss between the randomly sampled code and the discriminator's encoding of the ``fake'' image, we enforce the discriminator to explicitly capture the most relevant characteristics of the random codes that have been used to generate the corresponding ``fake'' images. In this way, the discriminator seeks to extract relevant features from images which happen to be ``fake'' but are guaranteed by the adversarial learning to be good enough to fool the discriminator of their origin. Thus, we use the randomly sampled codes not only for the adversarial learning but also as a ``free'' ground-truth for self-supervised learning \cite{SelfSupervision_Survey}. From our experiments, the added reconstruction loss gives a significant performance improvement over the vanilla GAN. \begin{figure}[b] \centering \includegraphics[scale=0.35]{images/stage2.pdf} \caption{Self-supervised learning of our extended GAN by minimizing the triplet loss of $\langle$anchor, positive, negative$\rangle$ images, where the positives and negatives are generated via appropriately masking the anchor. D is the discriminator show in Fig.~\ref{fig:discriminator}} \label{fig:stage2} \end{figure} {\bf Our second contribution:} As shown in Fig.~\ref{fig:overview}, we specify another type of self-supervised learning for our extended GAN so image encodings at the discriminator's output respect similarity of input images. While in general this additional self-supervision along with adversarial learning is expected to produce a better GAN model, it is particularly suitable for our subsequent distance-based image retrieval and few-shot image classification. In the lack of labeled data, for distance-metric learning, we resort to data augmentation. We take ``real'' training images and mask them with a patch whose placement controls similarity between the masked and original image, as shown in Fig.~\ref{fig:stage2}. Following the long track of research on object center-bias \cite{borji2015reconciling, henderson1993eye, nuthmann2010object, elazary2008interesting} arguing that human attention usually focuses on an object in the image center, we declare the masked images more similar to the original if their masking patches fall in the image corners rather than on the image center, as the latter case is more likely to partially occlude the target object. We use the above masking procedure to compile a set of image triplets that encode similarity relationships between the images. In a triplet, the anchor is a ``real'' image selected from the training dataset, the positive is a masked version of the anchor with the masking patch in one of the image corners, and the negative is another masked anchor but with the masking patch falling close to the image center. Thus, by construction, we constrain the triplet's similarity relationships relative to the anchor, as our training images are unlabeled. Given the set of triplets, we estimate the standard triplet loss for our GAN training. As our results show, the added distance-metric learning further improves the subsequent few-shot classification. Our two contributions lead to significant performance gains in unsupervised few-shot image classification relative to recent unsupervised approaches on the Mini-Imagenet \cite{vinyals2016matching,ravi2016optimization} and Tiered-Imagenet \cite{ren2018meta} datasets. In the rest of this paper: Sec.~\ref{sec:related_work} reviews prior work, Sec.~\ref{sec:proposed_model} specifies our approach, and Sec.~\ref{sec:experiments} presents our implementation details and experimental results. \section{Related Work} \label{sec:related_work} This section reviews closely related work. Methods for \textbf{deep unsupervised learning} can be broadly divided into: deep clustering, self-supervised learning and generative models. Deep clustering iteratively trains a CNN \cite{caron2018deep,xie2016unsupervised,wu2018unsupervised}. In each iteration, deep feature extracted by the current CNN are clustered to produce pseudo-labels of training images. The pseudo-labels are then used for the standard supervised learning of the next CNN. Self-supervised methods seek to solve an auxiliary task, for which ground-truth can be easily specified \cite{doersch2015unsupervised,zhang2016colorful,noroozi2016unsupervised,noroozi2017representation,zhang2017split}. Generative models seek to generate new images that look similar to images sampled from the underlying distribution. Recent generative models include (variational) auto-encoders \cite{kingma2013auto,vincent2010stacked}, and GANs \cite{goodfellow2014generative,donahue2016adversarial}. Our extended GAN belongs to the group of generative models enhanced with self-supervised learning. For \textbf{unsupervised few-shot classification}, recent work uses unlabeled training data and very few labeled test data that do not share the same classes. These methods first assign pseudo labels to the training data by either image clustering \cite{hsu2018unsupervised} or treating each training example as having a unique class \cite{antoniou2019assume, khodadadeh2018unsupervised}. Then, they apply the standard fully-supervised few-shot learning (e.g., \cite{finn2017model, snell2017prototypical}) on the pseudo-labeled training data. We differ from these approaches in two ways. First, we do not estimate pseudo-labels, and do not use the common episodic training for fully-supervised few-shot learning, but seek to directly learn the underlying image prior distribution by integrating adversarial and self-supervised learning. Second, we ensure that our image representation respects similarity relationships of images. Our problem is related to semi-supervised few-shot learning \cite{ren2018meta, sun2019learning}. These approaches first augment their labeled training set with unlabeled images, then, apply label propagation for knowledge transfer from the labeled to unlabeled set, and finally conduct fully-supervised few-shot learning on all training data. We cannot use this framework, as our labeled images have different classes from unlabeled ones, and even if they shared the same classes label, propagation from just one labeled example per class would be very difficult. Adversarial learning and self-supervised learning has been integrated for fully supervised few-shot learning \cite{zhang2018metagan, gidaris2019boosting}, but cannot be easily extended to our unsupervised setting. Compared with very closely-related work \cite{chen2019self,tran2019self,doersch2017multi}, our approach significantly differs. \cite{chen2018self,tran2019self} use the same GAN but with a rotation-based self-supervision loss which we do not use. \cite{doersch2017multi} uses a completely different triplet loss from ours. To form a triplet, we use the anchor, positive and negative from the very {\bf same image}, whereas \cite{doersch2017multi} uses the anchor and positive from the same image and the negative from a different image. \section{Our Approach} \label{sec:proposed_model} This section first specifies our extended GAN and its adversarial learning, Sec.~\ref{sec:reconstruction} defines the reconstruction loss, Sec.~\ref{sec:distance} presents our masking procedure and triplet loss, and Sec.~\ref{subsec:training} describes our unsupervised training. As shown in Figures~\ref{fig:overview} and \ref{fig:discriminator}, our extended GAN consists of the standard generator network $G$ and a discriminator network $D$ which is equipped with image encoding head $D_z$ and the standard discriminating head $D_{\text{r/f}}$. For adversarial training, we probabilistically sample latent codes $z'$ from a prior distribution, $z' \sim p(z')$, and generate corresponding ``fake'' images $x' = G(z')$. Both ``real'' training images $x$ and ``fake'' images $x'$ are passed to the discriminator for $D_{\text{r/f}}$ to predict their ``real'' or ``fake'' nature, $D_{\text{r/f}}(x)\in\mathbb{R}$. For training $D$ and $G$, we use the standard adversarial loss, specified as% \begin{eqnarray} L_{D}^{\text{adv}} &=&\underset{x \sim p_{\text{data}}(x)}{\mathrm{E}}[\max (0,1-D_{\text{r/f}}(x))] \notag \\ && + \underset{z' \sim p(z')}{\mathrm{E}}[\max (0,1+D_{\text{r/f}}(G(z')))], \label{eq:hinge_discriminator}\\ L_{G}^{\text{adv}} &=&-\underset{z' \sim p(z')}{\mathrm{E}}[D_{\text{r/f}}(G(z'))], \label{eq:hinge_generator} \end{eqnarray} where $E$ denotes the expected value and $p_{\text{data}}(x)$ is a prior distribution of unlabeled ``real'' training images $x$. As shown in \cite{lim2017geometric}, optimizing \eqref{eq:hinge_discriminator} and \eqref{eq:hinge_generator} is equivalent to minimizing the reverse KL divergence. For sampling latent codes, $z' \sim p(z')$, as in related work \cite{goodfellow2014generative, donahue2016adversarial, miyato2018spectral}, we assume that all elements of $z'$ are i.i.d.. For the $d$-dimensional latent code $z'$, we have studied several definitions of the prior $p(z')$, including the continuous uniform distribution $p(z')=U[-1, 1]^d$, the corresponding discrete Bernoulli distribution with the equal probability of 0.5 for the binary outcomes ``1'' and ``-1'' of elements of $z'$, and the Gaussian distribution with the mean zero and variance 1, $p(z')=\mathcal{N}(0,1)^d$. All these definitions of $p(z')$ give similar performance in our experiments. Sampling from the uniform distribution is justified, because many object classes appearing in training images are likely to share the same latent features, so the presence of these features encoded in $z$ and $z'$ is likely to follow the uniform distribution. \subsection{Reconstruction Loss} \label{sec:reconstruction} We extend the above specified adversarial learning of our GAN by enforcing the discriminator's encoding head $D_z$ to reconstruct randomly sampled latent codes $z'\sim p(z')$ from the corresponding ``fake'' images, $\hat{z'}=D_z(G(z'))\in\mathbb{R}^d$, as illustrated in Fig.~\ref{fig:overview}. Thus, we use $z'$ as a ``free'' label for the additional self-supervised training of $D$ and $G$ along with the adversarial learning. Minimizing a reconstruction loss between $z'$ and $\hat{z'}$ enforces $D_z$ to be trained on ``free'' labels of the corresponding ``fake'' images -- the knowledge that will be later transferred for encoding ``real'' images by $D_z$ when ``fake'' images become good enough to ``fool'' $D_{\text{r/f}}$. A difference between $z'$ and its reconstruction $\hat{z'}=D_z(G(z'))$ is penalized with the mean-squared error (MSE) reconstruction loss: \begin{align} L_{D}^{\text{mse}} = L_{G}^{\text{mse}} = \|\hat{z}' - z'\|^2_2, \label{eq:mse_discriminator} \end{align} when elements of $z'$ are sampled from the uniform or Gaussian distribution, $p(z')=U[-1, 1]^d$ or $p(z')=\mathcal{N}(0,1)^d$, or with the binary cross-entropy (BCE) reconstruction loss: \begin{align} L_{D}^{\text{bce}} = L_{G}^{\text{bce}} =& -\frac{1}{d}\sum_{m=1}^d[\frac{1+z_m'}{2} \cdot \log{\sigma(\hat{z'}_m)} \notag \\ & +(1-\frac{1+z_m'}{2})\cdot\log(1 - \sigma(\hat{z'}_m))], \label{eq:bce_discriminator} \end{align} when elements of $z'$, $z_m'\in\{-1,1\}$, are sampled from the discrete Bernoulli distribution, $p(z_m'=\pm 1)=0.5$; $\sigma(\cdot)$ denotes the sigmoid function. \subsection{Image Masking and Triplet Loss} \label{sec:distance} We additionally train the discriminator to output image representations that respect image similarity relationships, such that $z_i=D_z(x_i)$ and $z_j=D_z(x_j)$ are closer than $z_i$ and $z_k=D_z(x_k)$ when images $x_i$ and $x_j$ are more similar than $x_i$ and $x_k$. As ground-truth similarity relationships are not provided for our training images, we resort to data augmentation using the following masking procedure. Each training image generates a set of its masked versions by exhaustively placing a masking patch on a regular grid covering the image. The masking patch brightness is uniform and equal to the pixel average of the original image. We have experimented with various patch sizes and shapes, and various grids. A good trade-off between complexity and performance for $64\times 64$ training images that we use is obtained for the $16 \times 16$ square patch and $4 \times 4$ regular grid. Given the training dataset and its masked images, we compile a set of image triplets $\langle$anchor, positive, negative$\rangle$. The anchor $z=D_z(x)$ is an image from the training set. The positive is one of four masked versions of the anchor image $\{z^+_i=D_z(x^+_i):i=1,\dots,4\}$ whose masking patch falls in the image corner -- namely, the top-left, top-right, bottom-left, and bottom-right corner. The negative is one of the remaining masked versions of the anchor image $\{z^-_j=D_z(x^-_j):j=1,2,\dots\}$ whose masking patch falls on central locations on the grid. In the positives, the relatively small masking patch masks very little to no foreground of the anchor image. On the other hand, in the negatives, the masking patch is very likely to partially occlude foreground of the anchor image. Therefore, by construction, we constrain image similarity relationships to pertain to the image's foreground, such that the positives should be closer to the anchor than the negatives. We use the set of triplets $\{\langle z, z_i^+, z_j^- \rangle\}$ to estimate the following triplet loss for the additional distance-metric learning of our GAN:% \begin{align} \begin{split} L_{D}^{\text{triplet}} = \max[0, \max_i \Delta(z, z^+_i) - \min_j \Delta(z, z^-_j) + \rho]. \end{split} \label{eq:triplet} \end{align} where $\rho\ge 0$ is a distance margin, and $\Delta$ is a distance function. In this paper, we use the common cosine distance:% \begin{equation} \Delta(z, z') = 1 - \frac{z ^\top z'}{\|z\|_2 \cdot \|z'\|_2}. \label{eq:distance} \end{equation} \begin{algorithm}[ht] {\footnotesize \caption{Our Unsupervised Training} \label{algo:1} \begin{algorithmic} \STATE {\bf Input} = $\{T_1, T_2, \mathcal{T}, \beta, \gamma, \lambda\}$= numbers of training iterations, and 3 non-negative hyper parameters. \STATE \COMMENT {First stage $(1)$\quad} \FOR {$t_1=1,\dots,T_1$ } \STATE Sample $z' \sim p(z')$ and reconstruct $\hat{z'} = D_z(G(z'))$; \STATE Compute: $L_G^{\text{adv}}$ as in \eqref{eq:hinge_generator}, and $L_G^{\text{mse}}$ as in \eqref{eq:mse_discriminator} or $L_G^{\text{bce}}$ as in \eqref{eq:bce_discriminator}; \STATE Update $G$ by back-propagating the total loss: \\ \quad $L_G^{(1)} = L_G^{\text{adv}} + \beta L_G^{\text{bce}}$ or $L_G^{(1)} = L_G^{\text{adv}} + \beta L_G^{\text{mse}}$. \FOR {$\tau=1,\dots,\mathcal{T}$} \STATE Sample $z' \sim p(z')$ and reconstruct $\hat{z'} = D_z(G(z'))$; \STATE Sample a real image $x \sim p_{\text{data}}(x)$; \STATE Compute: $L_D^{\text{adv}}$ as in \eqref{eq:hinge_discriminator}; \STATE Compute: $L_G^{\text{mse}}$ as in \eqref{eq:mse_discriminator} or $L_D^{\text{bce}}$ as in \eqref{eq:bce_discriminator}; \STATE Update $D^{(1)}$ by back-propagating the total loss:\\ \quad $L_D^{(1)} = L_D^{\text{adv}} + \gamma L_D^{\text{bce}}$ or $L_D^{(1)} = L_D^{\text{adv}} + \gamma L_D^{\text{mse}}$. \ENDFOR \ENDFOR \STATE \COMMENT {Second stage $(2)$\quad} \FOR {$t_2=1,\dots,T_2$} \STATE Sample a real image $x \sim p_{\text{data}}(x)$ and take it as the anchor; \STATE Generate the masked positives and negatives of the anchor; \STATE Form the set of triplets for the anchor; \STATE Compute $L_D^{\text{triplet}}$ as in \eqref{eq:triplet}; \STATE Update $D^{(2)}$ by back-propagating the total loss:\\ \quad $L_D^{(2)} = L_D^{\text{triplet}} + \lambda \|D_z^{(1)}(x) - D_z^{(2)}(x)\|_2^2$. \ENDFOR \STATE Take $D^{(2)}$ as the learned discriminator $D$. \end{algorithmic} } \end{algorithm} \subsection{Our Unsupervised Training} \label{subsec:training} Alg.~\ref{algo:1} summarizes our unsupervised training that integrates adversarial learning with distance-metric learning and latent-code reconstruction. For easier training of $D$ and $G$, we divide learning in two stages. First, we perform adversarial learning constrained with the latent-code reconstruction regularization over $t_1=1,\dots,T_1$ iterations. In every iteration, $G$ is optimized once and $D$ is optimized multiple times over $\tau=1,\dots,\mathcal{T}$ iterations ($\mathcal{T}=3$). After convergence of the first stage ($T_1=50,000$), the resulting discriminator is saved as $D^{(1)}$. In the second training stage, we continue with distance-metric learning in $t_2=1,\dots,T_2$ iterations ($T_2=20,000$), while simultaneously regularizing that the discriminator updates do not significantly deviate from the previously learned $D^{(1)}$. \section{Experiments} \label{sec:experiments} \textbf{Datasets:} For evaluation on unsupervised few-shot classification, we follow \cite{hsu2018unsupervised, antoniou2019assume, khodadadeh2018unsupervised}, and evaluate on two benchmark datasets: Mini-Imagenet \cite{vinyals2016matching} and Tiered-Imagenet \cite{ren2018meta}. Our training is unsupervised, starts from scratch, and does not use other datasets for pre-training. Mini-Imagenet consists of 100 randomly chosen classes from ILSVRC-2012 \cite{russakovsky2015imagenet}. As in \cite{donahue2016adversarial, antoniou2019assume,hsu2018unsupervised}, these classes are randomly split into 64, 16, and 20 classes for training, validation, and testing, respectively. Each class has 600 images of size $84\times 84$. Tiered-Imagenet consists of 608 classes of $84 \times 84$ images from ILSVRC-2012 \cite{russakovsky2015imagenet}, grouped into 34 high-level categories. These are divided into 20, 6 and 8 categories for meta-training, meta-validation, and meta-testing. This corresponds to 351, 97 and 160 classes for meta-training, meta-validation, and meta-testing respectively. Tiered-Imagenet minimizes the semantic similarity between the splits compared to Mini-Imagenet. \textbf{Evaluation metrics:} For few-shot classification, we first randomly sample $N$ classes from the test classes and $K$ examples for each sampled class, and then classify query images into these $N$ classes. We report the average accuracy over 1000 episodes with $95\%$ confidence intervals of the $N$-way $K$-shot classification. Specifically, we are given support images $x_s$ with labels $y_s \in L_{\text{test}}$ sampled from $N=|L_{\text{test}}|$ classes which have not been seen in training. Each class has $K$ examples, $K\le 5$. Given a query image, $x_q$, we predict a label $\hat{y}_q \in L_{\text{test}}$ of the query as follows. After computing deep representations $z_q=D_z(x_q)$ and $z_s=D_z(x_s)$ of the query and support images, for every class $n=1,\dots,N$, we estimate its mean prototype vector $c_n$ as $ c_n = \frac{1}{K} \sum_{s, y_s=n} z_s$, and take the label of the closest $c_n$ to $z_q$ as our solution: \begin{equation} \hat{y}_q = \hat{n}=\argmin_n \Delta(z_q,c_n), \label{eq:recognition} \end{equation} where $\Delta$ is a distance function (e.g., \eqref{eq:distance}). The same formulation of few-shot recognition is used in \cite{snell2017prototypical}. \textbf{Implementation details:} Our implementation is in Pytorch \cite{paszke2017automatic}. Our backbone GAN is the Spectral Norm GAN (SN-GAN) \cite{miyato2018spectral} combined with the self-modulated batch normalization \cite{chen2018self}. All images are resized to $64 \times 64$ pixels, since the SN-GAN cannot reliably generate higher resolution images beyond $64 \times 64$. There are 4 blocks of layers in both $G$ and $D$. The latent code $z'$ and image representation $z$ have length $d=128$. We use an ADAM optimizer \cite{kingma2014adam} with the learning rate of $5e^{-4}$. We empirically observe convergence of the first and second training stages after $T_1=50000$ and $T_2=10000$ iterations, respectively. $D$ is updated in $\mathcal{T}=3$ iterations for every update of $G$. In all experiments, we set $\gamma = 1, \beta = 1, \lambda = 0.2, \rho=0.5$ as they are empirically found to give the best performance. In the first and the second training stages, the mini-batch size is 128 and 32, respectively. Our image masking places a $16 \times 16$ patch at $4 \times 4$ locations of the regular grid in the original image, where the patch brightness is equal to the average of image pixels. It is worth noting that we do not employ other popular data-augmentation techniques in training (e.g., image jittering, random crop, etc.). \textbf{Ablation study:} The following variants test how individual components of our approach affect performance: \begin{itemize}[itemsep=-1pt,topsep=2pt, partopsep=1pt] \item T: An architecture that is not a GAN, but consists of only the discriminator network from the SN-GAN \cite{miyato2018spectral}, and the discriminator's encoding head $D_z$ is trained on the triplet loss only. This variant tests how distance-metric learning affects performance without adversarial learning. \item Gc and Gd: SN-GAN \cite{miyato2018spectral} with continuous uniformly distributed and discrete Bernoulli-distributed elements of the latent code $z'$, respectively. \item GcM and GdB: Gc and Gd are extended with the MSE and BCE reconstruction loss, respectively. \item GcT1 and GcT2 = Gc + T: Gc is extended with the triplet loss, and the discriminator is trained in a single stage with total loss $L_D = L_D^{\text{adv}}+ \gamma L_D^{\text{triplet}}$ and in two stages as specified in Alg.~\ref{algo:1}, respectively. These two variants compare performance of single-stage and two-stage training. \item GdT1 and GdT2 = Gd + T: Gd is extended similarly as Gc for GcT1 and GcT2. \item GcMT1 and GcMT2 = Gc + MSE + T: Gc is extended with the MSE reconstruction loss and the triplet loss, and the discriminator is trained in a single stage with total loss $L_D = L_D^{\text{adv}}+ \gamma L_D^{\text{mse}}+ \gamma L_D^{\text{triplet}}$ and in two stages as specified in Alg.~\ref{algo:1}, respectively. \item GdBT1 and GdBT2 = Gd + BCE + T: Gd is extended the BCE reconstruction loss and the triplet loss, and the discriminator is trained in a single stage with total loss $L_D = L_D^{\text{adv}}+ \gamma L_D^{\text{bce}}+ \gamma L_D^{\text{triplet}}$ and in two stages as specified in Alg.~\ref{algo:1}, respectively. \end{itemize} \begin{table}[b] \caption{Average accuracy of few-shot image classification on test classes in Mini-Imagenet. GdBT2 with the $16\times16$ masking patch gives the best results.} \label{table:ablation_study} {\normalsize \begin{center} \begin{tabular}{|l|c|c|} \hline \textbf{Ablations} & 1-shot & 5-shot \\ \hline T & 31.23 $\pm$ 0.46 & 41.91 $\pm$ 0.53 \\ Gc & 34.52 $\pm$ 0.57 & 44.24 $\pm$ 0.72 \\ Gd & 34.84 $\pm$ 0.68 & 44.73 $\pm$ 0.67 \\ GcM & 43.49 $\pm$ 0.76 & 57.62 $\pm$ 0.73 \\ GdB & 43.51 $\pm$ 0.77 & 57.94 $\pm$ 0.76 \\ \hline GcT1 & 41.95 $\pm$ 0.47 & 50.62 $\pm$ 0.54 \\ GdT1 & 42.13 $\pm$ 0.52 & 51.39 $\pm$ 0.63 \\ GcMT1 & 45.13 $\pm$ 0.63 & 58.87 $\pm$ 0.69 \\ GcBT1 & 45.43 $\pm$ 0.78 & 58.96 $\pm$ 0.72 \\ \hline GcT2 & 42.36 $\pm$ 0.45 & 52.76 $\pm$ 0.52 \\ GdT2 & 43.13 $\pm$ 0.53 & 53.39 $\pm$ 0.78 \\ GcMT2 & 46.72 $\pm$ 0.73 & 60.92 $\pm$ 0.74 \\ {\bf GdBT2} & \textbf{48.28 $\pm$ 0.77} & \textbf{66.06 $\pm$ 0.70} \\ \hline GdBT2 $8\times8$ & 46.23 $\pm$ 0.77 & 60.46 $\pm$ 0.64 \\ {\bf GdBT2 $\bm{16\times16}$} & \textbf{48.28 $\pm$ 0.77} & \textbf{66.06 $\pm$ 0.70} \\ GdBT2 $32\times32$ & 44.40 $\pm$ 0.64 & 57.93 $\pm$ 0.49 \\ \hline \end{tabular} \end{center} } \end{table} \begin{table*} \caption{Unsupervised few-shot classification on Mini-Imagenet and Tiered-Imagenet. At the bottom, we show results of recent fully-supervised approaches to few-shot classification as our upper bound.} \label{table:compare-mini-imagenet} \centering {\normalsize \begin{tabular}{|l|c|c|c|c|} \hline & \multicolumn{2}{|c|}{\textbf{Mini-Imagenet, 5-way}} & \multicolumn{2}{|c|}{\textbf{Tiered-Imagenet, 5-way}} \\ \hline \textbf{Unsupervised Methods} & 1-shot & 5-shot & 1-shot & 5-shot \\ \hline SN-GAN \cite{miyato2018spectral} & 34.84 $\pm$ 0.68 & 44.73 $\pm$ 0.67 & 35.57 $\pm$ 0.69 & 49.16 $\pm$ 0.70 \\ AutoEncoder \cite{vincent2010stacked} & 28.69 $\pm$ 0.38 & 34.73 $\pm$ 0.63 & 29.57 $\pm$ 0.52 & 38.23 $\pm$ 0.72 \\ Rotation \cite{gidaris2018unsupervised} & 35.54 $\pm$ 0.47 & 45.93 $\pm$ 0.62 & 36.90 $\pm$ 0.54 & 51.23 $\pm$ 0.72 \\ \hline BiGAN kNN \cite{donahue2016adversarial} & 25.56 $\pm$ 1.08 & 31.10 $\pm$ 0.63 & - & - \\ AAL-ProtoNets \cite{antoniou2019assume} & 37.67 $\pm$ 0.39 & 40.29 $\pm$ 0.68 & - & - \\ UMTRA + AutoAugment \cite{khodadadeh2018unsupervised} & 39.93 & 50.73 & - & - \\ CACTUs-ProtoNets \cite{hsu2018unsupervised} & 39.18 $\pm$ 0.71 & 53.36 $\pm$ 0.70 & - & -\\ \hline Our GdBT2 & \textbf{48.28 $\pm$ 0.77} & \textbf{66.06 $\pm$ 0.70} & \textbf{47.86 $\pm$ 0.79} & \textbf{67.70 $\pm$ 0.75} \\ \hline \hline {\bf Fully-supervised Methods} &&&&\\ ProtoNets \cite{snell2017prototypical} & 46.56 $\pm$ 0.76 & 62.29 $\pm$ 0.71 & 46.52 $\pm$ 0.72 & 66.15 $\pm$ 0.74 \\ \hline \end{tabular} } \end{table*} Table.~\ref{table:ablation_study} presents our ablation study on the tasks of unsupervised 1-shot and 5-shot image classification on Mini-Imagenet. As can be seen, the variants with discrete Bernoulli-distributed elements of $z'$, on average, achieve better performance by $0.5\%$ than their counterparts with continuously distributed latent codes $z'$. Incorporating the reconstruction loss improves performance up to $9\%$ over the variants whose discriminator does not reconstruct the latent codes. While the variant T is the worst, integrating the triplet loss with adversarial learning outperforms the variants Gc and Gd which use only adversarial learning by more than $8\%$. Relative to Gc and Gd, larger performance gains are obtained by additionally using the reconstruction loss in GcM and GdB than using the triplet loss in GcT2 and GdT2. Finally, the proposed two-stage training in Alg.~\ref{algo:1} gives better results than a single-stage training, due to, in part, difficulty to optimize hyper parameters. The bottom three variants in Table.~\ref{table:ablation_study} evaluate GdBT2 for different sizes of the masking patch. From Table.~\ref{table:ablation_study}, GdBT2 gives the best results when the masking patch has size $16\times 16$ pixels, and we use this model for comparison with prior work. \begin{figure*}[ht!] \centering \includegraphics[scale=0.4]{images/qualitative_results2.pdf} \caption{Our image masking with rectangular patches for Mini-Imagenet. In every row, the images are organized from left to right in the descending order by their estimated distance to the original (unmasked) image.} \label{fig:qualitative} \end{figure*} \textbf{Comparison with state of the art:} Tab~\ref{table:compare-mini-imagenet} compares our GdBT2 with the state of the art on the tasks of unsupervised 1-shot and 5-shot image classification on Mini-Imagenet and Tiered-Imagenet. For fair comparison, we follow the standard label assignment to query images as in \cite{snell2017prototypical}. As can be seen, we significantly outperform the state of the art \cite{hsu2018unsupervised} by $9\%$ in 1-shot and nearly $13\%$ in 5-shot settings of Mini-Imagenet dataset. At the bottom, Tab.~\ref{table:compare-mini-imagenet} also shows results of recent fully-supervised approaches to few-shot classification, as their performance represents our upper bound. Surprisingly, our GdBT2 achieves significantly outperforms the fully supervised ProtoNets \cite{snell2017prototypical}. Our approach's performance can be even further boosted in practice since we can make use of abundant unsupervised data while supervised approaches are not applicable. \textbf{Qualitative Results}: Fig.~\ref{fig:qualitative} illustrates our masking procedure for generating positive and negative images in the triplets for distance-metric learning. In each row, the images are organized from left to right by their estimated distance to the original (unmasked) image in the descending order, where the rightmost image is the closest. From Fig.~\ref{fig:qualitative}, masked images that are the closest to the original have the masking patch in the image corner, and thus are good candidates for the positives in the triplets. Also, when the masking patch covers central image areas the resulting masked images have greater distances from the original, and are good candidates for the negatives in the triplets. \section{Conclusion} \label{sec:conclusion} We have addressed unsupervised few-shot object recognition, where all training images are unlabeled and do not share classes with test images. We have extended the vanilla GAN so as to integrate the standard adversarial learning with our two new strategies for self-supervised learning. The latter is specified by enforcing the GAN's discriminator to: (a) reconstruct the randomly sampled latent codes, and (b) produce image encodings that respect similarity relationships of images. Results of an extensive ablation study on few-shot classification demonstrate that integrating: (i) triplet loss with adversarial learning outperforms the vanilla GAN by more than 8\%, (ii) reconstruction loss with adversarial learning gives a performance gain of more than 9\%, and (iii) both triplet and reconstruction losses with adversarial learning improves performance by 13\%. In unsupervised few-shot classification, we outperform the state of the art by $9\%$ on Mini-Imagenet in 1-shot and $13\%$ in 5-shot settings. \section*{Acknowledgement} This work was supported in part by DARPA XAI Award N66001-17-2-4029 and DARPA MCS Award N66001-19-2-4035. {\normalsize \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-21T02:01:22', 'yymm': '2008', 'arxiv_id': '2008.06982', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06982'}
arxiv
\section{Introduction} Face frontalization aims to synthesize the frontal view face from a given profile. Frontalized faces can be directly used for general face recognition methods without elaborating additional complex modules. Apart from face recognition, generating photo-realistic frontal face is beneficial for a series of face-related tasks, including face reconstruction, face attribute analysis, facial animation, \etc. Traditional methods address this problem through 2D/3D local texture warping \cite{hassner2015effective, zhu2015high} or statistical modeling\cite{sagonas2015robust}. Recently, GAN-based methods have been proposed to recover a frontal face in a data-driven manner \cite{huang2017beyond, zhao2018towards, tran2017disentangled, yin2017towards, hu2018pose, zhao20183d, cao2018learning, yin2020dual}. For instance, Yin \etal \cite{yin2020dual} propose DA-GAN to capture the long-displacement contextual information from illumination discrepancy images under large poses. However, it recovers inconsistent illumination on the synthesized image. Flow-based method \cite{zhang2018face} predicts a dense pixel correspondence between the profile and frontal image and uses it to deform the profile face to the frontal view. However, deforming the profile face in the image space directly leads to obvious artifacts and missing pixels should be addressed under large poses. \begin{figure}[t] \centering \includegraphics[width=0.85\textwidth]{iilu_inconsist} \caption{$ \pm 45^\circ $, $ \pm 60^\circ $, $ \pm 75^\circ $ and $ \pm 90^\circ $ images of the two persons in the Multi-PIE. Each row images have the same flash in the recording environment.} \label{fig:iilu_inconsist} \end{figure} The existing methods do not consider the illumination inconsistency between the profile and ground-truth frontal image. Taking the widely used benchmark Multi-PIE \cite{gross2010multi} as an example, the visual illumination conditions on several poses are significantly different from the ground-truth frontal images as shown in Fig. \ref{fig:iilu_inconsist}. Except $ \pm 90^\circ $, the other face images are produced by the same camera type. The variation in camera types causes obvious illumination inconsistency between the $ \pm 90^\circ $ images and the ground-truth frontal image. Although efforts have been made to manually color-balance those same type cameras, the illumination of resulting images within $ \pm 75^\circ $ (except $ 0^\circ $) still look visually distinguishable with the ground-truth frontal image. Since the existing methods minimize pixel-wise loss between the synthesized image and the illumination inconsistent ground-truth, they tend to change both the pose and the illumination of the profile face image, while the latter actually is not acceptable in face editing and synthesis. To address the above issue, this paper proposes a novel Flow-based Feature Warping Model (FFWM) which can synthesize photo-realistic and illumination preserving frontal image from illumination inconsistent image pairs. In particular, FFWM incorporates the flow estimation with two modules: Illumination Preserving Module (IPM) and Warp Attention Module (WAM). Specifically, we estimate the optical flow fields from the given profile: the reverse and forward flow fields are predicted to warp the front face to the profile view and vice versa, respectively. The estimated flow fields are fed to IPM and WAM to conduct face frontalization. The IPM is proposed to synthesize illumination preserving images with fine facial details from illumination inconsistent image pairs. Specifically, IPM contains two pathways: (1) Illumination Preserving Pathway and (2) Illumination Adaption Pathway. For (1), an illumination preserving loss equipped with the reverse flow field is introduced to constrain the illumination consistency between synthesized images and the profiles. For (2), guided filter \cite{he2010guided} is introduced to further eliminate the illumination discrepancy and learns frontal view facial details from illumination inconsistent ground-truth image. The WAM is introduced to reduce the pose discrepancy in the feature level. It uses the forward flow field to align the profile features to the frontal view. This flow provides an explicit and accurate supervision signal to guide the frontalization. The attention mechanism in WAM helps to reduce the artifacts caused by the displacements between the profile and frontal images. Quantitative and qualitative experimental results demonstrate the effectiveness of our FFWM on synthesizing photo-realistic and illumination preserving faces with large poses and the superiority over the state-of-the-art results on the testing benchmarks. Our contributions can be summarized as: \begin{itemize} \item A Flow-based Feature Warping Model (FFWM) is proposed to address the challenging problem in face frontalization, \ie photo-realistic and illumination preserving image synthesis. \item Illumination Preserving Module (IPM) equipped with guided filter and flow field is proposed to achieve illumination preserving image synthesis. Warp Attention Module (WAM) uses the attention mechanism to effectively reduce the pose discrepancy in the feature level under the explicit and effective guidance from flow estimation. \item Quantitative and qualitative results demonstrate that the proposed FFWM outperforms the state-of-the-art methods. \end{itemize} \section{Related Work} \subsection{Face Frontalization} Face frontalization aims to synthesize the frontal face from a given profile. Traditional methods address this problem through 2D/3D local texture warping \cite{hassner2015effective, zhu2015high} or statistical modeling\cite{sagonas2015robust}. Hassner \etal \cite{hassner2015effective} employ a mean 3D model for face normalization. A statistical model\cite{sagonas2015robust} is used for frontalization and landmark detection by solving a constrained low-rank minimization problem. Benefiting from deep learning, many GAN-based methods\cite{huang2017beyond,tran2017disentangled,zhang2018face,hu2018pose,tian2018cr, yin2020dual} are proposed for face frontalization. Huang \etal \cite{huang2017beyond} use a two-pathway GAN architecture for perceiving global structures and local details simultaneously. Domain knowledge such as symmetry and identity information of face is used to make the synthesized faces photo-realistic. Zhao \etal \cite{zhao2018towards} propose PIM with introducing a domain adaptation strategy for pose invariant face recognition. 3D-based methods \cite{yin2017towards,zhao20183d,deng2018uv,cao2018learning} attempt to combine prior knowledge of 3D face with face frontalization. Yin \etal \cite{yin2017towards} incorporate 3D face model into GAN to solve the problem of large pose face frontalization in the wild. HF-PIM \cite{cao2018learning} combines the advantages of 3D and GAN-based methods and frontalizes profile images via a novel texture warping procedure. In addition to supervised learning, Qian \etal \cite{qian2019unsupervised} propose a novel Face Normalization Model (FNM) for unsupervised face generation with unpaired face images in the wild. Note that FNM focuses on face normalization, without considering preserving illumination. Instead of learning function to represent the frontalization procedure, our method gets frontal warped feature by flow field and reconstructs illumination preserving and identity preserving frontal view face. \subsection{Optical Flow} Optical flow estimation has many applications, \eg, action recognition, autonomous driving and video editing. With the progress in deep learning, FlowNet\cite{dosovitskiy2015flownet}, FlowNet2\cite{ilg2017flownet} and others achieve good results by end-to-end supervised learning. While SpyNet\cite{ranjan2017optical}, PWC-Net\cite{sun2018pwc} and LiteFlowNet\cite{hui2018liteflownet} also use coarse-to-fine strategery to refine the initial flow. It is worth mentioning that PWC-Net and LiteFlowNet have smaller size and are easier to train. Based on weight sharing and residual subnetworks, Hur and Roth \cite{hur2019iterative} learn bi-directional optical flow and occlusion estimation jointly. Bilateral refinement of flow and occlusion address blurry estimation, particularly near motion boundaries. By the global and local correlation layers, GLU-Net\cite{truong2019glu} can resolve the challenges of large displacements, pixel-accuracy, and appearance changes. In this work, we estimate bi-directional flow fields to represent dense pixel correspondence between the profile and frontal faces, which are then exploited to obtain frontal view features and preserve illumination condition, respectively. \begin{figure}[t] \centering \includegraphics[width=1\textwidth]{network} \caption{The architecture of our FFWM. Illumination Preserve Module is incorporated to facilitate synthesized frontal image $\hat{I}$ to be illumination preserving and facial details preserving in two independent pathways. Based on the skip connection, the Warp Attention Module helps synthesize frontal image effectively. Losses are shown in red color, which $ \hat{I}^w $ is the synthesized image $ \hat{I} $ warped by $ \Phi' $ and the $ \hat{I}^G $ is the guided filter output. } \label{fig:network} \end{figure} \section{Proposed Method} Let \{$I, I^{gt}$\} be a pair of profile and frontal face image of the same person. Given a profile image $ I $, our goal is to train a model $\mathcal{R}$ to synthesize the corresponding frontal face image $ \hat{I} = \mathcal{R}(I) $, which is expected to be photo-realistic and illumination preserving. To achieve this, we propose the Flow-based Feature Warping Model (FFWM). As shown in Fig.~\ref{fig:network}, FFWM takes U-net \cite{ronneberger2015u} as the backbone and incorporates with the Illumination Preserving Module (IPM) and the Warp Attention Module (WAM) to synthesize $\hat{I}$. In addition, FFWM uses optical flow fields which are fed to IPM and WAM to conduct frontalization. Specifically, we compute the forward and reverse flow fields to warp the profile to the frontal view and vice versa, respectively. In this section, we first introduce the bi-direcrional flow fields estimation in Sec~\ref{section:3.1}. IPM and WAM are introduced in Sec~\ref{section:3.2} and Sec~\ref{section:3.3}. Finally, the loss functions are detailed in Sec~\ref{section:3.4}. \subsection{Bi-directional Flow Fields Estimation \label{section:3.1}} Face frontalization can be viewed as the face rotation transformation, and the flow field can model this rotation by establishing the pixel-level correspondence between the profile and frontal faces. Traditional optical flow methods \cite{dosovitskiy2015flownet, ilg2017flownet} take two frames as the input. However, we only use one profile image as the input. In this work, we adopt the FlowNetSD in FlowNet2 \cite{ilg2017flownet} as our flow estimation network, and change the input channel from 6 (two frames) to 3 (one image). For preserving illumination and frontalization, we estimate the reverse flow field $ \Phi' $ and the forward flow field $ \Phi $ from the profile image, respectively. \subsubsection{Reverse Flow Field.} Given the profile image $ I $, reverse flow estimation network $ \mathcal{F'} $ predicts the reverse flow field $ \Phi' $ which can warp the ground-truth frontal image $ I^{gt} $ to the profile view as $ I $. \begin{equation} \Phi' =\mathcal{F'}(I;\Theta_\mathcal{F'}), \end{equation} \begin{equation} {I^w}' = \mathcal{W}(I^{gt},\Phi'), \end{equation} where $\Theta_\mathcal{F'}$ denotes the parameters of $ \mathcal{F'} $, and $\mathcal{W}(\cdot)$ \cite{jaderberg2015spatial} is the bilinear sampling operation. To learn an accurate reverse flow field, $ \mathcal{F}' $ is pretrained with the landmark loss\cite{li2018learning}, sampling correctness loss\cite{ren2020deep} and the regularization term \cite{ren2020deep}. \subsubsection{Forward Flow Field.} Given the profile image $ I $, forward flow estimation network $ \mathcal{F} $ predicts the forward flow field $ \Phi $ which can warp $ I $ to the frontal view. \begin{equation} \Phi =\mathcal{F}(I;\Theta_\mathcal{F}), \end{equation} \begin{equation} I^w = \mathcal{W}(I,\Phi), \end{equation} where $\Theta_\mathcal{F}$ denotes the parameters of $ \mathcal{F} $. To learn an accurate forward flow field, $ \mathcal{F} $ is pretrained with the same losses as $ \mathcal{F}' $. Then two flow fields $ \Phi' $ and $ \Phi $ are used for the IPM and WAM to generate illumination preserving and photo-realistic frontal images. \subsection{Illumination Preserving Module \label{section:3.2}} Without considering inconsistent illumination in the face datasets, the existing frontalization methods potentially overfit to the wrong illumination. To effectively decouple the illumination and the facial details, hence to synthesize illumination preserving faces with fine details, we propose the Illumination Preserving Module (IPM). As shown in Fig. \ref{fig:network}, IPM consists of two pathways. Illumination preserving pathway ensures that the illumination condition of the synthesized image $\hat{I}$ is consistent with the profile $I$. Illumination adaption pathway ensures that the facial details of the synthesized image $\hat{I}$ are consistent with the ground-truth $I^{gt}$. \subsubsection{Illumination Preserving Pathway.} Because the illumination condition is diverse and cannot be quantified as a label, it is hard to learn reliable and independent illumination representation from face images. Instead of constraining the illumination consistency between the profile and the synthesized image in the feature space, we directly constrain it in the image space. As shown in Fig. \ref{fig:network}, in the illumination preserving pathway, we firstly use the reverse flow field ${\Phi}'$ to warp the synthesized image $ \hat{I} $ to the profile view, \begin{equation} \hat{I}^w = \mathcal{W}(\hat{I}, \Phi'). \end{equation} Then an illumination preserving loss is defined on the warped synthesized image $ \hat{I}^w $ to constrain the illumination consistency between the synthesized image $ \hat{I} $ and the profile $ I $. By minimizing it, FFWM can synthesize illumination preserving frontal images. \subsubsection{Illumination Adaption Pathway.} Illumination preserving pathway cannot ensure the consistency of facial details between the synthesized image $\hat{I}$ and the ground-truth $ I^{gt} $, so we constrain it in the illumination adaption pathway. Since the illumination of profile $ I $ is inconsistent with the ground-truth $ I^{gt} $ under large poses, adding constraints directly between $\hat{I}$ and $ I^{gt} $ eliminates the illumination consistency between $ \hat{I}$ and $ I $. So a guided filter layer\cite{he2010guided} is firstly used to transfer the illumination of images. Specifically, the guided filter takes $I^{gt}$ as the input image and $\hat{I}$ as the guidance image, \begin{equation} \hat{I}^G = \mathcal{G}(\hat{I},I^{gt}), \end{equation} where $ \mathcal{G}(\cdot) $ denotes the guided filter, and we set the radius of filter as the quarter of the image resolution. After filtering, the guided filter result $ \hat{I}^G $ has the same illumination with $ I^{gt} $ while keeping the same facial details with $ \hat{I} $. Then the illumination-related losses (\eg, pixel-wise loss, perceptual loss) are defined on $ \hat{I}^G $ to facilitate our model synthesize $ \hat{I} $ with much finer details. By this means, $\hat{I}$ can become much more similar to $I^{gt}$ in facial details without changing the illumination consistency between $ \hat{I} $ and $ I $. Note that the guided filter has no trainable parameters and potentially cause our model trap into local minima during training. So we apply the guided filter after several iterations, providing stable and robust initialization to our model. \subsection{Warp Attention Module \label{section:3.3}} The large pose discrepancy makes it difficult to synthesize correct facial details in the synthesized images. To reduce the pose discrepancy between the profile and frontal face, Warp Attention Module (WAM) is proposed to align the profile face to the frontal one in the feature space. We achieve this by warping the profile features guided by the forward flow field $ \Phi $. The architecture of our WAM is illustrated in Fig. \ref{fig:WAM}. It contains two steps: flow-guided feature warping and feature attention. \begin{figure}[t] \centering \includegraphics[width=0.75\textwidth]{WAM} \caption{The architecture of Warp Attention Module. Considering the symmetry prior of human face, WAM also contains flipped warped feature.} \label{fig:WAM} \end{figure} \subsubsection{Flow-Guided Feature Warping.} Because the profile and frontal face have different visible areas, the forward flow field $ \Phi $ cannot establish a complete pixel-level correspondence between them. Hence, warping profile face directly leads to artifacts. Here we incorporate $ \Phi $ with bilinear sampling operation $\mathcal{W}(\cdot)$ to warp the profile face to the frontal one in the feature space. Additionally, we use the symmetry prior of human face, and take both warped features and its horizontal flip to guide the frontal image synthesis. \begin{equation} f_w = \mathcal{W}(f, \Phi) , \end{equation} where $ f $ denotes the encoder feature of the profile. Let $ {f_w}' $ denotes the horizontal flip of $ f_w $, and $ (f_w \oplus {f_w}') $ denotes the concatenation of $ f_w $ and $ {f_w}' $. \subsubsection{Feature Attention.} After warping, the warped feature encodes the backgrounds and self-occlusion artifacts, which leads to degraded frontalization performance. To eliminate above issue and extract reliable frontal feature, an attention mechanism is then used to adaptively focus on the critical parts of $ (f_w \oplus {f_w}') $. The warped feature $ (f_w \oplus {f_w}') $ is firstly fed into a Conv-BN-ReLU-ResidualBlock Layer to generate an attention map $ A $, which has the same height, width and channel size with $ (f_w \oplus {f_w}') $. Then the reliable frontalized feature $\hat{f}$ is obtained by, \begin{equation} \hat{f} = A \otimes (f_w \oplus {f_w}') , \end{equation} where $\otimes$ denotes element-wise multiplication. $\hat{f}$ is then skip connected to the decoder to help generate photo-realistic frontal face image $ \hat{I} $. \subsection{Loss Functions \label{section:3.4}} In this section, we formulate the loss functions used in our work. The background of images is masked to make the loss functions focus on the facial area. \subsubsection{Pixel-wise Loss.} Following \cite{huang2017beyond, hu2018pose}, we employ a multi-scale pixel-wise loss on the guided filter result $ \hat{I}^G $ to constrain the content consistency, \begin{equation} \mathcal{L}_{pixel}= \sum_{s=1}^{S} \left \| \hat{I}^G_s - I^{gt}_s \right \|_1 , \label{eq:l1} \end{equation} where $ S $ denotes the number of scales. In our experiments, we set $S$ = 3, and the scales are 32 $\times$ 32, 64 $\times$ 64 and 128 $\times$ 128. \subsubsection{Perceptual Loss.} Pixel-wise loss tends to generate over-smoothing results. To alleviate this, we introduce the perceptual loss defined on the VGG-19 network \cite{simonyan2014very} pre-trained on ImageNet \cite{russakovsky2015imagenet}, \begin{equation} \mathcal{L}_{p}= \sum_{i}w_i \left \| \phi_i(\hat{I}^G) - \phi_i(I^{gt}) \right \|_1 , \label{eq:perceptaul} \end{equation} where $\phi_i(\cdot)$ denotes the output of the $i$-th VGG-19 layer. In our implementation, we use Conv1-1, Conv2-1, Conv3-1, Conv4-1 and Conv5-1 layer, and set $ w = \{1, 1/2, 1/4, 1/4, 1/8\} $. To improve synthesized imagery in the particular facial regions, we also use the perceptual loss on the facial regions like eyes, nose and mouth. \subsubsection{Adversarial Loss.} Following \cite{shocher2018ingan}, we adpot a multi-scale discriminator and adversarial learning to help synthesize photo-realistic images. \begin{equation} \mathcal{L}_{adv} = \min_{R}\max_{D} \mathbb{E}_{I^{gt}}[ \log D(I^{gt} ) ] - \mathbb{E}_{\hat{I}^G}[\log(1-D(\hat{I}^G))] . \end{equation} \subsubsection{Illumination Preserving Loss.} To preserve the illumination of profile $ I $ on synthesized image $ \hat{I} $, we define the illumination preserving loss on the warped synthesized image $ \hat{I}^w $ at different scales, \begin{equation} \mathcal{L}_{ip}= \sum_{s=1}^{S} \left \| \hat{I}^w_s - I_s \right \|_1 , \end{equation} where $ S $ denotes the number of scales, and the scale setting is same as Eqn.~(\ref{eq:l1}). \subsubsection{Identity Preserving Loss.} Following \cite{huang2017beyond, hu2018pose}, we present an identity preserving loss to preserve the identity information of the synthesized image $ \hat{I} $, \begin{equation} \mathcal{L}_{id}=\left \| \psi_{fc2} (\hat{I})-\psi_{fc2} (I^{gt} ) \right \|_1 + \left \| \psi_{pool } (\hat{I})-\psi_{pool } (I^{gt}) \right \|_1 , \end{equation} where $ \psi(\cdot) $ denotes the pretrained LightCNN-29\cite{wu2018light}. $ \psi_{fc2}(\cdot) $ and $ \psi_{pool}(\cdot) $ denote the outputs of the last pooling layer and the fully connected layer respectively. To preserve the identity information, we add the identity loss on both $ \hat{I} $ and $ \hat{I}^G $. \subsubsection{Overall Losses.} Finally, we combine all the above losses to give the overall model objective, \begin{equation} \mathcal{L}= \lambda_0 \mathcal{L}_{pixel} + \lambda_1 \mathcal{L}_{p} + \lambda_2 \mathcal{L}_{adv} + \lambda_3 \mathcal{L}_{ip} + \lambda_4 \mathcal{L}_{id}, \end{equation} where $ \lambda_{*} $ denotes the different losses tradeoff parameters. \section{Experiments} To illustrate our model can synthesize photo-realistic and illumination preserving images while preserving identity, we evaluate our model qualitatively and quantitatively under both controlled and in the wild settings. In the following subsections, we begin with an introduction of datasets and implementation details. Then we demonstrate the merits of our model on qualitative synthesis results and quantitative recognition results over the state-of-the-art methods. Lastly, we conduct an ablation study to demonstrate the benefits from each part of our model. \subsection{Experimental Settings} \begin{figure}[t] \centering \includegraphics[width=0.95\textwidth]{multipie_illu} \caption{Synthesis results of the Multi-PIE dataset by our model under large poses and illumination inconsistent conditions. Each pair presents profile (left), synthesized frontal face (middile) and ground-truth frontal face (right).} \label{fig:illumination} \end{figure} \subsubsection{Datasets.} We adopt the Multi-PIE dataset \cite{gross2010multi} as our training and testing set. Multi-PIE is widely used for evaluating face synthesis and recognition in the controlled setting. It contains 754,204 images of 337 identities from 15 poses and 20 illumination conditions. In this paper, the face images with neutral expression under 20 illuminations and 13 poses within $ \pm 90^\circ $ are used. For a fair comparison, we follow the test protocols in \cite{hu2018pose} and utilize two settings to evaluate our model. The first setting (Setting 1) only contains images from Session 1. The training set is composed of all the first 150 identities images. For testing, one gallery image with frontal view and normal illumination is used for the remaining 99 identities. For the second setting (Setting 2), we use neutral expression images from all four sessions. The first 200 identities and the remaining 137 identities are used for training and testing, respectively. Each testing identity has one gallery image with frontal view and normal illumination from the first appearance. LFW\cite{lfw} contains 13,233 face images collected in unconstrained environment. It will be used to evaluate the frontalization performance in uncontrolled settings. \subsubsection{Implementation Details.} All images in our experiments are cropped and resized to 128 $ \times $ 128 according to facial landmarks, and image intensities are linearly scaled to the range of [0, 1]. The LightCNN-29 \cite{wu2018light} is pretrained on MS-Celeb-1M \cite{guo2016ms} and fine-tuned on the training set of Multi-PIE. In all our experiments, we empirically set $ \lambda_0 = 5, \lambda_1 = 1, \lambda_2 = 0.1, \lambda_3 = 15, \lambda_4 = 1 $. The learning rate is initialized by 0.0004 and the batch size is 8. The flow estimation networks $ \mathcal{F} $ and $ \mathcal{F'} $ are pre-trained and then all networks are end-to-end trained by minimizing the objective $ \mathcal{L} $ with setting lr=0.00005 for $ \mathcal{F} $ and $ \mathcal{F'} $. \subsection{Qualitative evaluation} In this subsection, we qualitatively compare the synthesized results of our model against state-of-the-art face frontalization methods. We train our model on the training set of the Multi-PIE Setting 2, and evaluate it on the testing set of the Multi-PIE Setting 2 and the LFW \cite{lfw}. Fig. \ref{fig:illumination} shows the face synthesized results under large poses, and it is obvious that our model can synthesize photo-realistic images. To demonstrate the illumination preserving strength of our model, we choose the profiles with obvious inconsistent illumination. As shown in Fig. \ref{fig:illumination}, the illumination of profile faces can be well preserved in the synthesized images. More synthesized results are provided in the supplementary material. \begin{figure}[t] \centering \subfigure[Profile]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{r0.png} \end{minipage}} \subfigure[Ours]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{r1.png} \end{minipage}} \subfigure[~\cite{hu2018pose}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{r2.png} \end{minipage}} \subfigure[~\cite{huang2017beyond}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{r3.png} \end{minipage}} \subfigure[~\cite{yin2017towards}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{r4.png} \end{minipage}} \subfigure[\cite{qian2019unsupervised}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{r6.png} \end{minipage}} \subfigure[Frontal]{ \begin{minipage}[b]{0.12\linewidth} \includegraphics[width=0.85\linewidth]{r5.png} \end{minipage}} \caption{Face frontalization comparison on the Multi-PIE dataset under the pose of $ 90^\circ $ (first two rows) and $ 75^\circ $ (last two rows).} \label{fig:multipie} \end{figure} Fig. \ref{fig:multipie} illustrates the comparison with the state-of-the-art face frontalization methods \cite{hu2018pose, huang2017beyond, yin2017towards,qian2019unsupervised} on the Multi-PIE dataset. In the large pose cases, existing methods are disable to preserve the illumination of profiles on the synthesized results. Face shape and other face components (\eg, eyebrows, mustache and nose) also occur deformation. The reason is those methods are less able to preserve reliable details from the profiles. Compared with the existing methods, our method produces more identity preserving results while keeping the facial details of the profiles as much as possible. In particular, under large poses, our model can recover photo-realistic illumination conditions of the profiles, which is important when frontalized images are used for some other face-related tasks, such as face editing, face pose transfer and face-to-face synthesis. \begin{figure}[t] \centering \subfigure[Profile]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l0.png} \end{minipage}} \subfigure[Ours]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l1.png} \end{minipage}} \subfigure[~\cite{zhao2018towards}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l2.png} \end{minipage}} \subfigure[~\cite{huang2017beyond}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l3.png} \end{minipage}} \subfigure[~\cite{tran2017disentangled}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l4.png} \end{minipage}} \subfigure[\cite{hassner2015effective}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l5.png} \end{minipage}} \subfigure[\cite{qian2019unsupervised}]{ \begin{minipage}[b]{0.12\linewidth} \centering \includegraphics[width=0.85\linewidth]{l6.png} \end{minipage}} \caption{Face frontalization comparison on the LFW dataset. Our method is trained on Mulit-PIE and tested on LFW.} \label{fig:lfw} \end{figure} \begin{table}[t] \begin{center} \caption{Rank-1 recognition rates (\%) across poses under Setting 2 of the Multi-PIE. The best two results are highlighted by \textbf{bold} and \underline{underline} respectively.} \label{table:Multipie-Setting2-FRR} \begin{tabular}{lccccccc} \hline\noalign{\smallskip} Method& \(\pm 15^{\circ}\) & \(\pm 30^{\circ}\) & \(\pm 45^{\circ}\) & \(\pm 60^{\circ}\) & \(\pm 75^{\circ}\) & \(\pm 90^{\circ}\) & Avg \\ \hline Light CNN \cite{wu2018light}& 98.59 & 97.38 & 92.13 & 62.09 & 24.18 & 5.51 & 63.31 \\ DR-GAN \cite{tran2017disentangled}& 94.90 & 91.10 & 87.20 & 84.60 & - & - & 89.45 \\ FF-GAN \cite{yin2017towards}& 94.60 & 92.50 & 89.70 & 85.20 & 77.20 & 61.20 & 83.40 \\ TP-GAN \cite{huang2017beyond}& 98.68 & 98.06 & 95.38 & 87.72 & 77.43 & 64.64 & 86.99 \\ CAPG-GAN \cite{hu2018pose} & 99.82 & 99.56 & 97.33 & 90.63 & 83.05 & 66.05 & 89.41 \\ PIM \cite{zhao2018towards} & 99.30 & 99.00 & 98.50 & 98.10 & 95.00 & 86.50 & 96.07 \\ 3D-PIM \cite{zhao20183d} & 99.64 & 99.48 & 98.81 & 98.37 & 95.21 & 86.73 & 96.37 \\ DA-GAN \cite{yin2020dual} & \underline{99.98} & \underline{99.88} & 99.15 & 97.27 & 93.24 & 81.56 & 95.18 \\ HF-PIM \cite{cao2018learning} & \textbf{99.99} & \textbf{99.98} & \textbf{99.98} & \textbf{99.14} & \underline{96.40} & \underline{92.32} & \underline{97.97} \\ \hline \textbf{Ours} & 99.86 & 99.80 & \underline{99.37} & \underline{98.85} & \textbf{97.20} & \textbf{93.17} & \textbf{98.04} \\ \hline \end{tabular} \end{center} \end{table} We further qualitatively compare face frontalization results of our model on the LFW dataset with \cite{zhao2018towards, huang2017beyond, tran2017disentangled, hassner2015effective,qian2019unsupervised}. As shown in Fig.~\ref{fig:lfw}, the existing methods fail to recover clear global structures and fine facial details. Also they cannot preserve the illumination of the profiles. Though FNM\cite{qian2019unsupervised} generates high qualitative images, it is still disable to preserve identity. It is worth noting that our method produces more photo-realistic faces with identity and illumination well-preserved, which also demonstrates the generalizability of our model in the uncontrolled environment. More results under large poses are provided in the supplementary material. \subsection{Quantitative evaluation} In this subsection, we quantitatively compare the proposed method with other methods in terms of recognition accuracy on Multi-PIE and LFW. The recognition accuracy is calculated by firstly extracting deep features with LightCNN-29\cite{wu2018light} and then measuring similarity between features with a cosine-distance metric. Tab.~\ref{table:Multipie-Setting2-FRR} shows the Rank-1 recognition rates of different methods under Setting 2 of Multi-PIE. Our method has advantages over competitors, especially at large poses (\eg, $ 75^\circ $, $ 90^\circ $), which demonstrates that our model can synthesize frontal images while preserving the identity information. The recognition rates under Setting 1 is provided in the supplementary material. \begin{table}[t] \begin{center} \caption{Face verification accuracy (ACC) and area-under-curve (AUC) results on LFW.} \label{table:LFW-ACC-AUC} \begin{tabular}{lcccccc} \hline\noalign{\smallskip} Method & FaceNet\cite{schroff2015facenet} & VGG Face\cite{parkhi2015deep} & FF-GAN\cite{yin2017towards} & CAPG-GAN\cite{hu2018pose} & DA-GAN\cite{yin2020dual} & \textbf{Ours} \\ \hline ACC(\%) & 99.63 & 98.95 & 96.42 & 99.37 & 99.56 & \textbf{99.65} \\ AUC(\%) & - & - & 99.45 & 99.90 & 99.91 & \textbf{99.92} \\ \hline \end{tabular} \end{center} \end{table} Tab.~\ref{table:LFW-ACC-AUC} compares the face verification performance (ACC and AUC) of our method with other state-of-the-arts\cite{schroff2015facenet, parkhi2015deep, yin2017towards, hu2018pose, yin2020dual} on the LFW. Our method achieves 99.65 on accuracy and 99.92 on AUC, which is also comparable with other state-of-the-art methods. The above quantitative results prove that our method is able to preserve the identity information effectively. \subsection{Ablation Study} \begin{figure}[t] \centering \includegraphics[height=4.0cm]{ablationall.pdf} \caption{Model Comparsion: synthesis results of our model and its variants on Multi-PIE} \label{fig:ablationall.pdf} \end{figure} \begin{table}[t] \begin{center} \caption{Incomplete variants analysis: Rank-1 recognition rates (\%) across poses under Setting 2 of the Multi-PIE dataset. IAP and IPP denote the illumination adaption pathway and illumination preserving pathway in the Illumination Preserving Module (IPM). Warp, flip and att denote the three variants in Warp Attention Module (WAM).} \label{table:Multipie-Setting2-Ablation} \begin{tabular}{lccccccc} \hline\noalign{\smallskip} Method& \(\pm 15^{\circ}\) & \(\pm 30^{\circ}\) & \(\pm 45^{\circ}\) & \(\pm 60^{\circ}\) & \(\pm 75^{\circ}\) & \(\pm 90^{\circ}\)& Avg \\ \hline w/o IPM & 99.83 & 99.77 & 99.35 & 98.74 & 97.18 & 93.15 & 98.00 \\ IPM w/o IPP & 99.84 & 99.74 & 99.36 & 98.47 & 96.73 & 91.56 & 97.62 \\ IPM w/o IAP & 99.83 & 99.76 & 99.30 & 98.70 & 97.11 & 92.83 & 97.92 \\ \hline w/o WAM & 99.84 & 99.46 & 98.91 & 97.27 & 93.18 & 86.23 & 95.81 \\ WAM w/o flip & 99.84 & 99.69 & 99.27 & 98.10 & 96.57 & 92.65 & 97.69 \\ WAM w/o warp & 99.83 & 99.64 & 99.16 & 97.83 & 94.60 & 88.16 & 96.54 \\ WAM w/o att & 99.85 & 99.79 & 99.36 & 98.71 & 96.81 & 93.09 & 97.94 \\ \hline w/o $ \mathcal{L}_{adv} $ & 99.83 & 99.72 & 99.28 & 98.57 & 97.09 & 93.11 & 97.93 \\ w/o $ \mathcal{L}_{id} $ & 99.85 & 99.62 & 99.12 & 97.42 & 93.93 & 86.05 & 96.00 \\ w/o $ \mathcal{L}_{pixel} $ & 99.83 & 99.77 & 99.35 & 98.79 & 97.05 & 92.85 & 97.94 \\ w/o $ \mathcal{L}_{p} $ & 99.81 & 99.75 & 99.33 & 98.62 & 97.13 & 93.10 & 97.96\\ \hline \textbf{Ours} & \textbf{99.86} & \textbf{99.80} & \textbf{99.37} & \textbf{98.85} & \textbf{97.20} & \textbf{93.17} & \textbf{98.04}\\ \hline \end{tabular} \end{center} \end{table} In this subsection, we analyze the respective roles of the different modules and loss functions in frontal view synthesis. Both qualitative perceptual performance (Fig.~\ref{fig:ablationall.pdf}) and face recognition rates (Tab.~\ref{table:Multipie-Setting2-Ablation}) are reported for comprehensive comparison under the Multi-PIE Setting 2. We can see that our FFWM exceeds all its variants in both quantitative and qualitative evaluations. \subsubsection{Effects of the Illumination Preserving Module (IPM).} Although without IPM the recognition rates drop slightly (as shown in Tab.~\ref{table:Multipie-Setting2-Ablation}), the synthesized results cannot preserve illumination and are approximate to the inconsistent ground-truth illumination (as shown in Fig.~\ref{fig:ablationall.pdf}). We also explore the contributions of illumination adaption pathway (IAP) and illumination preserving pathway (IPP) in the IPM. As shown in Fig.~\ref{fig:ablationall.pdf}, without IPP, the illumination of synthesized images tend to be inconsistent with the profiles and ground-truth images. And without IAP, the illumination of synthesized images tends to be a tradeoff between the profiles and the illumination inconsistent ground-truth images. Only integrating IPP and IAP together, our model can achieve illumination preserving image synthesis. Furthermore, our model archives a lower recognition rate when removing the IPP, which demonstrates that the IPP prompts the synthesized results to keep reliable information of the profiles. \subsubsection{Effects of the Warp Attention Module (WAM).} We can see that without WAM, the synthesized results tend to be smooth and distorted in the self-occlusion parts (as shown in Fig.~\ref{fig:ablationall.pdf}). As shown in Tab.~\ref{table:Multipie-Setting2-Ablation}, without WAM, the recognition rates drop significantly, which proves that WAM dominates in preserving identity information. Moreover, we explore the contributions of three components in the WAM, including taking flipped warped feature as additional input (w/o flip), feature warping (w/o warp) and feature attention (w/o att). As shown in Fig.~\ref{fig:ablationall.pdf}, taking flip feature as additional input has benefits on recovering the self-occlusion parts on the synthesized images. Without the feature attention mechanism, there are artifacts on the synthesized images. Without feature warping, the synthesized results get worse visual performance. These results above suggest that each component in WAM is essential for synthesizing identity preserving and photo-realistic frontal images. \subsubsection{Effects of the losses.} As shown in Tab.~\ref{table:Multipie-Setting2-Ablation}, the recognition rates decrease if one loss function is removed. Particularly, the rates drop significantly for all poses if the $ \mathcal{L}_{id} $ loss is not adapted. We also report the qualitative visualization results in Fig.~\ref{fig:ablationall.pdf}. Without $ \mathcal{L}_{adv} $ loss, the synthesized images tend to be blurry, suggesting the usage of adversarial learning. Without $ \mathcal{L}_{id} $ and $ \mathcal{L}_{pixel} $, our model cannot promise the visual performance on the local textures (\eg, eyes). Without $\mathcal{L}_p$, the synthesized faces present artifacts at the edges (\eg, face and hair). \section{Conclusion} In this paper, we propose a novel Flow-based Feature Warping Model (FFWM) to effectively address the challenging problem in face frontalization, photo-realistic and illumination preserving image synthesis with illumination inconsistent supervision. Specifically, an Illumination Preserve Module is proposed to address the illumination inconsistent issue. It helps FFWM to synthesize photo-realistic frontal images while preserving the illumination of profile images. Furthermore, the proposed Warp Attention Module reduces the pose discrepancy in the feature space and helps to synthesize frontal images effectively. Experimental results demonstrate that our method not only synthesizes photo-realistic and illumination preserving results but also outperforms state-of-the-art methods on face recognition across large poses. \subsection*{Acknowledgement} This work is partially supported by the National Natural Science Foundation of China (NSFC) under Grant No.s 61671182 and U19A2073. \bibliographystyle{splncs04}
{'timestamp': '2020-09-10T02:15:19', 'yymm': '2008', 'arxiv_id': '2008.06843', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06843'}
arxiv
\section{Introduction} Conjunctive queries (CQs) are an extensively studied database query language and fragment of first-order logic. They correspond precisely to Datalog programs with a single non-recursive rule. In this paper, we study two problems related to CQs. The first problem is concerned with the existence and constructability of unique characterizations. \emph{For which CQs $q$ is it the case that $q$ can be characterized (up to logical equivalence) by its behavior on a small set of data examples? And, when such a set of data examples exists, can it be constructed efficiently?} The second problem pertains to \emph{exact learnability} of CQs in an interactive setting where the learner has access to a ``membership oracle'' that, given any database instance and a tuple of values, answers whether the tuple belongs to the answer of the goal CQ (that is, the hidden CQ that the learner is trying to learn). We can think of the membership oracle as a black-box, compiled version of the goal query, which the learner can execute on any number of examples. The task of the learner, then, is to reverse engineer the query based on the observed behavior. \begin{figure} \begin{center} \begin{tikzpicture}[level distance=36pt,sibling distance=4pt] \Tree [.\node(top){$\top$} ; \edge[draw=none]; [.\text{$A$} \edge[-] ; [.\node(f1){$F_1$}; ] \edge[draw=none] ; [.\text{\dots} \edge[draw=none] ; [.{} \edge[draw=none]; [.\node(bot){$\bot$}; ] ]] \edge[-] ; [.\node(fn){$F_n$}; ] ] ] \draw (top) edge[out=220,in=140,looseness=1.2] (bot.west); \draw (top) edge[out=-40,in=40,looseness=1.2] (bot.east); \draw (f1) edge[out=250,in=130] (bot.west); \draw (fn) edge[out=290,in=50] (bot.east); \draw[dashed] (-1.2,-2) rectangle (1.2,-2.8); \end{tikzpicture} \end{center} \caption{A frontier in the homomorphism lattice of structures} \label{fig:frontier} \end{figure} Note that these two problems (unique characterizability and exact learnability) are closely related to each other: a learner can identify the goal query with certainty, only when the set of examples that it has seen so far constitutes a unique characterization of the goal query. \begin{motivatingexample} This example, although stylized and described at a high level, aims to convey an important use case that motivated the present work. The \emph{Google Knowledge Graph} is a large database of entities and facts, gathered from a variety of sources. It is used to enhance the search engine's results for queries such as ``where was Barack Obama born'' with factual information in the form of \emph{knowledge panels} \cite{KGBlog2020} When a query triggers a specific knowledge panel, this may be the result of various different triggering and fulfillment mechanisms, which may involve a combination of structured queries to the knowledge graph, hard-coded business logic (in a Turing-complete language), and machine learned models. This makes it difficult to understand interactions between knowledge panels (e.g., whether the two knowledge panels are structurally equivalent or one subsumed by the other). If a declarative specification of (an approximation of) the triggering and fulfillment logic for a knowledge panel can be constructed programmatically, specified in a sufficiently restrictive formalism such as Datalog rules, this provides an avenue to the above, and other relevant static analysis tasks. The \emph{efficient exact learnability with membership queries} that we study in this paper, can be viewed as an idealized form of such a programmatic approach, where the membership oracle is the existing, black box, implementation of the knowledge panel, and the learner must produce a CQ that exactly captures it. \end{motivatingexample} As it turns out, the above problems about CQs are intimately linked to fundamental properties of the homomorphism lattice of finite structures. In particular, the existence of a unique characterization for a CQ can be reduced to the existence of a \emph{frontier} in the homomorphism lattice for an associated structure $A$, where, by a ``frontier'' for $A$, we mean a finite set of structures $F_1, \ldots, F_n$ that cover precisely the set of structures homomorphically strictly weaker than $A$, that is, such that $\{B\mid B \begin{array}{l}\rightarrow\\[-0.7em] \nleftarrow\end{array} A\} = \bigcup_i \{B\mid B\to F_i\}$ (cf.~Figure~\ref{fig:frontier}). Known results \cite{FoniokNT08,AlexeCKT2011} imply that not every finite structure has such a frontier, and, moreover, a finite structure has a frontier if and only if the structure (modulo homomorphic equivalence) satisfies a structural property called \emph{c-acyclicity}. These known results, however, are based on exponential constructions, and no polynomial algorithms for constructing frontiers were previously known. \begin{contribution}[Polynomial-time algorithms for constructing frontiers] We show that, for c-acyclic structures, a frontier can in fact be computed \emph{in polynomial time}. More specifically, we present two polynomial-time algorithms. The first algorithm takes any c-acyclic structure and produces a frontier consisting of structures that are themselves not necessarily c-acyclic. Indeed, we show that this is unavoidable. The second algorithm applies to a more restricted class of acyclic structures and yields a frontier consisting entirely of structures belonging to the same class (that is, the class of structures in question is frontier-closed). \end{contribution} We use these to obtain new results on the existence and efficient constructability of unique characterizations for CQs: \begin{contribution}[Polynomial Unique Characterizations for Conjunctive Queries] We show that a CQ is uniquely characterizable by polynomially many examples, precisely if (modulo logical equivalence) it is c-acyclic. Furthermore, for c-acyclic CQs, a uniquely characterizing set of examples can be constructed in polynomial time. In the special case of unary, acyclic, connected CQs, a uniquely characterizing set of examples can be constructed consisting entirely of queries from the same class. \end{contribution} Using the above results as a stepping stone, we obtain a polynomial-time exact learning algorithm for the class of c-acyclic CQs. \begin{contribution}[Polynomial-Time Learnability with Membership Queries] We show that c-acyclic CQs are efficiently exactly learnable in Angluin's model of exact learnability with membership queries~\cite{Angluin88}. \end{contribution} The above results are optimal, because, as we mentioned above, exact learnability with membership queries, requires the existence of a finite uniquely characterizing set of examples, which, in turn, requires the existence of a frontier, and frontiers exist (up to homomorphic equivalence) only for c-acyclic structures. Although our primary interest is in conjunctive queries, we show that our results also have implications for \emph{schema mappings} and \emph{description logic concepts}: \begin{contribution}[Schema Mappings and Description Logic Concepts] As a further corollary to the above, we obtain a number of results regarding the existence of polynomial unique characterizations, as well as exact learnability, for LAV (``Local-As-View'') schema mappings and for description logic concepts for the lightweight description logic $\mathcal{ELI}$. \end{contribution} \paragraph*{Outline} Section~\ref{sec:preliminaries} reviews basic facts and definitions. In Section~\ref{sec:frontiers}, we present our two new polynomial-time algorithms for constructing frontiers for finite structures with designated elements. We also review a result by \cite{NesetrilOssona2008}, which implies the existence of (not necessarily polynomially computable) frontiers w.r.t.~classes of structures of bounded expansion. In Section~\ref{sec:characterizations}, we apply these algorithms to show that a CQ is uniquely characterizable by polynomially many examples, precisely if (modulo logical equivalence) it is c-acyclic. Furthermore, for c-acyclic CQs, a uniquely characterizing set of examples can be constructed in polynomial time. In the special case of unary, acyclic, connected CQs, a uniquely characterizing set of examples can be constructed consisting entirely of queries from the same class. In Section~\ref{sec:learning}, we further build on these results, and we study the exact learnability of CQs. Section~\ref{sec:applications} presents applications to schema mappings and description logic concepts. \section{Preliminaries} \label{sec:preliminaries} \subparagraph*{Schemas, Structures, Homomorphisms, Cores} A \emph{schema} (or, relational signature) is a finite set of relation symbols $\mathcal{S}=\{R_1, \ldots, R_n\}$, where each relation $R_i$ as an associated arity $\text{arity}(R_i) \geq 1$. For $k\geq 0$, by a \emph{structure over $\mathcal{S}$ with $k$ distinguished elements} we will mean a tuple $(A, a_1, \ldots, a_k)$, where $A=(\text{dom}(A), R^A_1, \ldots, R^A_n)$ is a finite structure (in the traditional, model-theoretic sense) over the schema $\mathcal{S}$, and $a_1, \ldots, a_k$ are elements of the domain of $A$. Note that all structures, in this paper, are assumed to be finite, and we will drop the adjective ``finite''. By a \emph{fact} of a structure $A$ we mean an expression of the form $R(a_1, \ldots, a_n)$ where the tuple $(a_1, \ldots, a_n)$ belongs to the relation $R$ in $A$. Given two structures $(A,\textbf{a})$ and $(B,\textbf{b})$ over the same schema, where $\textbf{a}=a_1, \ldots a_k$ and $\textbf{b}=b_1, \ldots, b_k$, a \emph{homomorphism} $h: (A,\textbf{a})\to (B,\textbf{b})$ is a map $h$ from the domain of $A$ to the domain of $B$, such that $h$ preserves all facts, and such that $h(a_i)=b_i$ for $i=1\ldots k$. When such a homomorphism exists, we will also say that $(A,\textbf{a})$ ``homomorphically maps to'' $(B,\textbf{b})$ and we will write $(A,\textbf{a})\to (B,\textbf{b})$. We say that $(A,\textbf{a})$ and $(B,\textbf{b})$ are \emph{homomorphically equivalent} if $(A,\textbf{a})\to (B,\textbf{b})$ and $(B,\textbf{b})\to (A,\textbf{a})$. A structure is said to be a \emph{core} if there is no homomorphism from the structure in question to a proper substructure~\cite{HN92}. It is known~\cite{HN92} that every structure $(A,\textbf{a})$ has a substructure to which it is homomorphically equivalent and that is a core. This substructure, moreover, is unique up to isomorphism, and it is known as \emph{the core of $(A, \textbf{a})$}. \subparagraph*{Fact Graph, FG-Connectedness, FG-Disjoint Union} The \emph{fact graph} of a structure $(A,\textbf{a})$ is the undirected graph whose nodes are the facts of $A$, and such that there is an edge between two distinct facts if they share a non-designated element, i.e., there exists an element $b$ of the domain of $A$ that is distinct from the distinguished elements $\textbf{a}$, such that $b$ occurs in both facts. We say that $(A,\textbf{a})$ is \emph{fg-connected} if the fact graph is connected. A \emph{fg-connected component} of $(A,\textbf{a})$ is a maximal fg-connected substructure $(A',\textbf{a})$ of $(A,\textbf{a})$. If $(A_1,\textbf{a})$ and $(A_2,\textbf{a})$ are structures with the same distinguished elements, and whose domains are otherwise (except for these distinguished elements) disjoint, then the union $(A_1\cup A_2, \textbf{a})$ of these two structures will be called a \emph{fg-disjoint union} and will be denoted as $(A_1,\textbf{a})\uplus (A_2,\textbf{a})$. The same construction naturally extends to finite sets of structures. It is easy to see that every structure $(A,\textbf{a})$ is equal to the \text{fg-disjoint union} of its fg-connected components. See also~\cite{Fagin2008towards,tencate2009laconic}, where fg-connected components are called \emph{fact blocks}. \subparagraph*{Direct Product, Homomorphism Lattice} Given two structures $(A,\textbf{a})$ and $(B,\textbf{b})$ over the same schema, where $\textbf{a}=a_1, \ldots a_k$ and $\textbf{b}=b_1, \ldots, b_k$, the \emph{direct product} $(A,\textbf{a})\times (B,\textbf{b})$ is defined, as usual, as $((A\times B), \langle a_1, b_1\rangle, \ldots, \langle a_k, b_k\rangle)$, where the domain of $A\times B$ is the Cartesian product of the domains of $A$ and $B$, and where the facts of $A\times B$ are all facts $R(\langle c_1,d_1\rangle, \ldots, \langle c_n, d_n\rangle)$ for which it holds that $R(c_1, \ldots, c_n)$ is a fact of $A$ and $R(d_1, \ldots, d_n)$ is a fact of $B$. The direct product of a finite collection of structures is defined analogously. For a fixed schema $\mathcal{S}$ and $k\geq 0$, the collection of (homomorphic-equivalence classes of) structures over $\mathcal{S}$ with $k$ distinguished elements, ordered by homomorphism, forms a lattice, where the above \emph{direct product} operation is the meet operation. In particular, $(A,\textbf{a})\times (B,\textbf{b})$ homomorphically maps to both $(A,\textbf{a})$ and $(B,\textbf{b})$, and a structure $(C,\textbf{c})$ homomorphically maps to $(A,\textbf{a})\times (B,\textbf{b})$ if and only if it homomorphically maps to both $(A,\textbf{a})$ and $(B,\textbf{b})$. The join operation of the lattice is a little more tedious to define, and we only sketch it here, as it is not used in the remainder of the paper. When two structures have the same isomorphism type of distinguished elements, their join is simply the fg-disjoint union as defined earlier. In the general case, one must first compute the smallest equivalence relation over the index set of the distinguished elements that refines the equivalence relations induced by both structures, and factor both structures through, before taking their fg-disjoint union. For structures without designated elements, this lattice has been studied extensively (cf.~for instance~\cite{HellNesetril2004,nesetril2012sparsity}). The above exposition shows how to lift some of the basic definitions and constructions, in the appropriate way, to structures with distinguished elements. \subparagraph*{Incidence Graph, C-Acyclicity} Given a structure $(A,\textbf{a})$, the \emph{incidence graph} of $A$ is the bipartite multi-graph containing all elements of the domain of $A$ as well as all facts of $A$, and an edge $(a,f)$ whenever $a$ is an element and $f$ is a fact in which $a$ occurs. Note that if an element occurs more than once in the same fact, the incidence graph contains multiple edges. $(A,\textbf{a})$ is said to be \emph{c-acyclic} if every cycle in its incidence graph contains at least one distinguished elements, i.e., at least one elements in $\textbf{a}$. In particular, this means that no non-designated element occurs twice in the same fact. The concept of c-acyclicity was first introduced in~\cite{AlexeCKT2011} in the study of unique characterizability of GAV schema mappings (cf.~Section~\ref{sec:applications} for more details). A straightforward dynamic-programming argument shows: \begin{proposition}\label{prop:cacyclic-core} For c-acyclic structures $(A, \textbf{a})$ and $(B,\textbf{b})$ (over the same schema and with the same number of distinguished elements), we can test in polynomial time whether $(A,\textbf{a})\to(B,\textbf{b})$. The core of a c-acyclic structure can be computed in polynomial time. \end{proposition} In the case without designated elements, c-acyclicity simply means that the incidence graph is acyclic, a condition better known as \emph{Berge acyclicity} in the database theory literature~\cite{Fagin83:acyclicity}. \subparagraph*{C-Connectedness} We say that a structure $(A,\textbf{a})$ is \emph{c-connected} if every connected component of its incidence graph contains at least one designated element. Note that this condition is only meaningful for $k>0$, and that it differs subtly from the condition of fg-connectedness we defined above. For example, the structure consisting of the facts $R(a_1, a_2)$ and $S(a_2, a_1)$ with distinguished elements $a_1, a_2$, is c-connected but is \emph{not} fg-connected. For any structure $(A,\textbf{a})$, we denote by $(A, \textbf{a})^{\textrm{reach}}$ the (unique) maximal c-connected substructure, that is, the substructure containing everything reachable from the distinguished elements. \begin{proposition}\label{prop:reach} If $(A,\textbf{a})$ is c-connected, then $(A,\textbf{a})\to (B, \textbf{b})^{\textrm{reach}}$ iff $(A,\textbf{a})\to (B, \textbf{b})$. \end{proposition} \subparagraph*{Conjunctive Queries} Let $k\geq 0$. A $k$-ary \emph{conjunctive query (CQ)} $q$ over a schema $\mathcal{S}$ is an expression of the form ~ $ q(\textbf{x}) \text{ :- } \alpha_1\land\cdots\land\alpha_n $ ~ where $\textbf{x}=x_1, \ldots, x_k$ is a sequence of variables, and where each $\alpha_i$ is an atomic formula using a relation from $\mathcal{S}$. Note that $\alpha_i$ may use variables from $\textbf{x}$ as well as other variables. In addition, it is required that each variable in $\textbf{x}$ occurs in at least one conjunct $\alpha_i$. This requirement is referred to as the \emph{safety} condition. Note that, for simplicity, this definition of CQ does not allow the use of constants. Many of the results in this paper, however, can be extended in a straightforward way to CQs with a fixed finite number of constants (which can be simulated using additional free variables). If $A$ is a structure over the same schema as $q$, we denote by $q(A)$ the set of all $k$-tuples of values that satisfy the query $q$ in $A$. We write $q\subseteq q'$ if $q$ and $q'$ are queries over the same schema, and of the same arity, and $q(A)\subseteq q'(A)$ holds for all structures $A$. We say that $q$ and $q'$ are \emph{logically equivalent} if $q\subseteq q'$ and $q'\subseteq q$ both hold. We refer to any textbook on database theory for a more detailed exposition of the semantics of CQs. There is a well-known correspondence between $k$-ary CQs over a schema $\mathcal{S}$ and structures over $\mathcal{S}$ with $k$ distinguished elements. In one direction, we can associate to each $k$-ary CQ $q(\textbf{x})$ over the schema $\mathcal{S}$ a corresponding structure over $\mathcal{S}$ with $k$ distinguished elements, namely $\widehat{q} = (A_q,\textbf{x})$, where the domain of $A_q$ is the set of variables occurring in $q$, and the facts of $A_q$ are the conjuncts of $q$. We will call this structure $\widehat{q}$ the \emph{canonical structure} of $q$. Note that every distinguished element of $\widehat{q}$ occurs in at least one fact, as follows from the safety condition of CQs. Conversely, consider any structure $(A,\textbf{a})$, with $\textbf{a}=a_1, \ldots, a_k$, such that every distinguished element $a_i$ occurs in at least one fact of $A$. We can associate to $(A,\textbf{a})$ a $k$-ary \emph{canonical CQ}, namely the CQ that has a variable $x_a$ for every value $a$ in the domain of $A$ occurring in at least one fact, and a conjunct for every fact of $A$. By the classic \emph{Chandra-Merlin Theorem}~\cite{CM77}, a tuple $\textbf{a}$ belongs to $q(A)$ if and only if there is a homomorphism from $\widehat{q}$ to $(A,\textbf{a})$; and $q\subseteq q'$ holds if and only if there is a homomorphism from $\widehat{q'}$ to $\widehat{q}$. Finally, $q$ and $q'$ are logically equivalent if and only if $\widehat{q}$ and $\widehat{q'}$ are homomorphically equivalent. \subparagraph*{Exact Learning Models, Conjunctive Queries as a Concept Class} Informally, an \emph{exact learning algorithm} is an algorithm that identifies an unknown goal concept by asking a number of queries about it. The queries are answered by an oracle that has access to the goal concept. This model of learning was introduced by Dana Angluin, cf.~\cite{Angluin88}. In this paper, we consider the two most extensively studied kinds of oracle queries: \emph{membership queries} and \emph{equivalence queries}. We will first review basic notions from computational learning theory, such as the notion of a \emph{concept}, and then explain what it means for a concept class to be \emph{efficiently exactly learnable with membership and/or equivalence queries}. Let $X$ be a (possibly infinite) set of {\em examples}. A \emph{concept over $X$} is a function $c:X\rightarrow \{0,1\}$, and a \emph{concept class} ${\mathcal C}$ is a collection of such concepts. We say that $x\in X$ is a \emph{positive example} for a concept $c$ if $c(x)=1$, and that $x$ is a \emph{negative example} for $c$ if $c(x)=0$. Conjunctive queries (over a fixed schema $\mathcal{S}$ and with a fixed arity $k$) are a particular example of such a concept class, where the example space is the class of all structures over $\mathcal{S}$ with $k$ distinct elements, and where an example $(A,\textbf{a})$ is labeled as positive if the tuple $\textbf{a}$ belongs to $q(A)$, and negative otherwise. It is always assumed that concepts are specified using some representation system so that one can speak of the length of the specification of a concept. More formally, a \emph{representation system for $\mathcal{C}$} is a string language $\mathcal{L}$ over some finite alphabet, together with a surjective function $r:\mathcal{L}\to\mathcal{C}$. By the \emph{size} of a concept $c\in\mathcal{C}$, we will mean the length of the smallest representation. Similarly, we assume a representation system, with a corresponding notion of length, for the examples in $X$. When there is no risk of confusion, we may conflate concepts (and examples) with their representations. Specifically, for us, when it comes to \emph{structures}, any natural choice of representation will do; we only assume that the length of the specification of a structure (for a fixed schema) is polynomial in the domain size, the number of facts and the number of distinguished elements. Likewise for \emph{CQs}, we assume that the length of the representation of a CQ is polynomial in that of its canonical structure. \newcommand{\texttt{alg}}{\texttt{alg}} For every concept $c$, we denote by $\text{\rm MEM}_c$ the \emph{membership oracle} for $c$, that is, the oracle that takes as input an example $x$ and returns its label, $c(x)$, according to $c$. Similarly, for every concept $c\in \mathcal{C}$, we denote by $\text{\rm EQ}_c$, the \emph{equivalence oracle} for $c$, that is, the oracle that takes as input the representation of a concept $h$ and returns ``yes'', if $h=c$, or returns a counterexample $x$ otherwise (that is, an example $x$ such that $h(x)\neq c(x)$). An \emph{exact learning algorithm with membership and/or equivalence queries} for a concept class $C$ is an algorithm $\texttt{alg}$ that takes no input but has access to the membership oracle and/or equivalence oracle for an unknown \emph{goal concept} $c\in C$.\footnote{It is common in the learning theory literature to assume that the learning algorithm is given an upper bound on the size of the goal concept as input. However, it turns out that such an assumption is not needed for any of our positive results concerning learnability.} The algorithm $\texttt{alg}$ must terminate after finite amount of time and output (some representation of) the goal concept $c$. This notion was introduced by Angluin~\cite{Angluin88}, who also introduced the notion of a \emph{polynomial-time} exact learning algorithm. We say that an exact learning algorithm $\texttt{alg}$ with membership and/or equivalence queries \emph{runs in polynomial time} if there exists a two-variable polynomial $p(n,m)$ such that at any point during the run of the algorithm, the time used by $\texttt{alg}$ up to that point (counting one step per oracle call) is bounded by $p(n,m)$, where $n$ is the size of the goal concept and $m$ the size of the largest counterexample returned by calls to the equivalence oracle up to that point in the run ($m=0$ if no equivalence queries have been used). A concept class ${\mathcal C}$ is \emph{efficiently exactly learnable with membership and/or equivalence queries} if there is an exact learning algorithm with membership and/or equivalence queries for $\mathcal{C}$ that runs in polynomial time. There is a delicate issue about this notion of polynomial time that we now discuss. One might be tempted to relax the previous definition by requiring merely that the total running time is bounded by $p(n,m)$. However, this change in the definition would give rise to a {\em wrong} notion of a polynomial-time algorithms in this context by way of a loophole in the definition. Indeed, under this change, one could design a learning algorithm that, in a first stage, identifies the goal hypothesis by (expensive) exhaustive search and that, once this is achieved, forces ---by asking equivalence queries with appropriate modification of the goal concept--- the equivalence oracle to return large counterexamples that would make up for the time spent during the exhaustive search phase. \section{Frontiers in the homomorphism lattice of structures} \label{sec:frontiers} In this section, we define frontiers and discuss their relationships to gaps and (restricted) homomorphism dualities. We present two polynomial-time methods for constructing frontiers. For the applications in the next sections, it is important to consider structures with designated elements. These designated elements, intuitively, correspond to the free variables of a CQ. \begin{definition} Fix a schema and $k\geq 0$, and let $\mathcal{C}$ be a class of structures with $k$ designated elements and let $(A,\textbf{a})$ be a structure with $k$ designated elements as well. A \emph{frontier} for $(A,\textbf{a})$ w.r.t.~$\mathcal{C}$, is a set of structures $F$ such that \begin{enumerate} \item $(B,\textbf{b})\to(A,\textbf{a})$ for all $(B,\textbf{b})\in F$. \item $(A,\textbf{a})\not\to(B,\textbf{b})$ for all $(B,\textbf{b})\in F$. \item For all $(C,\textbf{c})\in\mathcal{C}$ with $(C,\textbf{c})\to (A,\textbf{a})$ and $(A,\textbf{a})\not\to(C,\textbf{c})$, we have that $(C,\textbf{c})\to (B,\textbf{b})$ for some $(B,\textbf{b})\in F$. \end{enumerate} \end{definition} See Figure~\ref{fig:frontier} for a graphical depiction of a frontier. The notion of a frontier is closely related to that of a gap pair. A pair of structures $(B,A)$ with $B\to A$ is said to be a \emph{gap pair} if $A\not\to B$, and every structure $C$ satisfying $B\to C$ and $C\to A$ is homomorphically equivalent to either $B$ or $A$~\cite{NesetrilTardif2000}. The same concept applies to structures with designated elements. It is easy to see that any frontier for a structure $A$ must contain (modulo homomorphic equivalence) all structures $B$ such that $(B,A)$ is a gap pair. \begin{example} The structure $(A,a_1)$ consisting of facts $Pa_1$ and $Qa_1$ (with designated element $a_1$) has a frontier of size 2 (w.r.t.~the class of all finite structures), namely $F=\{(B, a_1), (C, a_1)\}$ where $B$ consists of the facts $Pa_1,Pb,Qb$ and $C$ consists of the facts $Qa_1,Pb,Qb$, respectively. Note that $((B, a_1), (A, a_1))$ and $((C, a_1), (A, a_1))$ are gap pairs. It can be shown that the structure $(A,a_0)$ has no frontier of size 1 (as such a frontier would have to consist of a structure that contains both facts $Pa_1$ and $Qa_1$). For another example, consider the structure $(A',a_1)$ consisting of facts $Pa_1$ and $Rbb$. It is the right hand side of a gap pair (the left hand side being the structure $(B', a_1)$ consisting of the facts $Rbb$ and $Pb'$), but $(A',a_1)$ has no finite frontier as follows from Theorem~\ref{thm:cacyclic} below. \end{example} Frontiers are also closely related to (generalized) homomorphism dualities~\cite{FoniokNT08}. We say that a structure $(A,\textbf{a})$ \emph{has a finite duality} w.r.t.~ a class $\mathcal{C}$ if there is a finite set of structures $D$ such that for all $(C,\textbf{c})\in\mathcal{C}$, $(A,\textbf{a})\to (C,\textbf{c})$ iff for all $(B,\textbf{b})\in D$, $(C,\textbf{c})\not\to (B,\textbf{b})$. If ${\mathcal C}$ is the set of all structures (over the same schema as $(A,\textbf{a})$), we simply say that $(A,\textbf{a})$ \emph{has a finite duality}.\footnote{We note here that in the literature on Constraint Satisfaction, it is usual to consider the 'other side' of the duality, i.e, a structure $A$ is said to have finite duality if there exists a finite set of structures $F$ such that for every structure $C$, $C\to A$ iff for all $B\in F$, $B\not\to C$.} \begin{example} In the realm of digraphs, viewed as relational structures without designated elements with a single binary relation, every directed path $A$ of, say, $k>1$ nodes has finite duality (w.r.t.~the class of digraphs). Indeed, it is not difficult to verify that for every digraph $C$, $A\rightarrow C$ iff $C\not\rightarrow D$ where $D$ is the digraph with nodes $\{1,\dots k-1\}$ and edges $\{(i,j) \mid i<j\}$. \end{example} \begin{lemma} \label{lem:frontiers-and-dualities} Let $\mathcal{C}$ be any class of structures. \begin{enumerate} \item If a structure $(A,\textbf{a})$ has a finite duality w.r.t. $\mathcal{C}$ then $(A,\textbf{a})$ has a finite frontier w.r.t. $\mathcal{C}$. \item If a structure $(A,\textbf{a})\in\mathcal{C}$ has a finite frontier w.r.t. $\mathcal{C}$ and $\mathcal{C}$ is closed under direct products, then $(A,\textbf{a})$ has a finite duality w.r.t. $\mathcal{C}$. \end{enumerate} \end{lemma} Note that the construction of the frontier from the duality is polynomial, while the construction of the duality from the frontier involves an exponential blowup. The following example shows that this is unavoidable. \begin{example} The path $\circ \xrightarrow{R}\circ \xrightarrow{R_1}\circ \xrightarrow{R}\circ \xrightarrow{R_2}\circ\cdots \circ \xrightarrow{R_n}\circ \xrightarrow{R}\circ$, viewed as a structure without any designated elements, has a frontier (w.r.t.~the class of all finite structures) of size polynomial in $n$, as will follow from Theorem~\ref{thm:cacyclic-polyfrontier} below. It is known, however, that any finite duality for this structure must involve a structure whose size is exponential in $n$, and the example can be modified to use a fixed schema (cf.~\cite{NesetrilTardif2005}). \end{example} \subsection{Frontiers for classes with bounded expansion} The notion of a \emph{class of graphs with bounded expansion} was introduced in~\cite{nesetril2018grad}. We will not give a precise definition here, but important examples include graphs of bounded degree, graphs of bounded treewidth, planar graphs, and any class of graphs excluding a minor. The same concept of bounded expansion can be applied also to arbitrary structures: a class of structures $\mathcal{C}$ is said to have bounded expansion if the class of Gaifman graphs of structures in $\mathcal{C}$ has bounded expansion. We refer to~\cite{nesetril2012sparsity} for more details. Classes of structures of bounded expansion are in many ways computationally well-behaved (cf.~for example~\cite{kazana2020firsts}). Ne\v{s}et\v{r}il and Ossona de Mendez \cite{NesetrilOssona2008, nesetril2012sparsity} show that if $\mathcal{C}$ is any class of structures with bounded expansion, then every structure has a finite duality w.r.t. $\mathcal{C}$. It follows by Lemma~\ref{lem:frontiers-and-dualities} that also every structure has a finite fontier w.r.t.~$\mathcal{C}$. Ne\v{s}et\v{r}il and Ossona de Mendez~\cite{NesetrilOssona2008, nesetril2012sparsity} only consider connected structures without designated elements, but their result extends in a straightforward way to the general case of structures with designated elements. Furthermore, it yields an effective procedure for constructing frontiers, although non-elementary (i.e., not bounded by a fixed tower of exponentials). \begin{theorem}[from \cite{NesetrilOssona2008, nesetril2012sparsity}] \label{thm:frontiers-bounded-expansion} Let $\mathcal{C}$ be any class of structures that has bounded expansion. Then every structure $(A,\textbf{a})$ has a finite frontier w.r.t. $\mathcal{C}$, which can be effectively constructed. \end{theorem} \subsection{Polynomial frontiers for c-acyclic structures} Alexe et al.~\cite{AlexeCKT2011}, building on Foniok et al.~\cite{FoniokNT08}, show that a structure has a finite duality if and only if its core is c-acyclic. By Lemma~\ref{lem:frontiers-and-dualities}, this implies that a structure has a finite frontier if and only if its core is c-acyclic. \begin{theorem}[from~\cite{FoniokNT08,AlexeCKT2011}] \label{thm:cacyclic} A structure has a finite frontier w.r.t.~the class of all structures iff it is homomorphically equivalent to a c-acyclic structure, iff its core is c-acyclic. \end{theorem} One of our main results is a new proof of the right-to-left direction, which, unlike the original, provides a polynomial-time construction of a frontier from a c-acyclic structure: \begin{theorem}\label{thm:cacyclic-polyfrontier} Fix a schema $\mathcal{S}$ and $k\geq 0$. Given a c-acyclic structure over $\mathcal{S}$ with $k$ distinguished elements, we can construct in polynomial time a frontier w.r.t. the class of all structures over $\mathcal{S}$ that have $k$ distinguished elements. \end{theorem} Note that the size of the smallest frontier is in general exponential in $k$. Indeed, consider the single-element structure $(A,\textbf{a})$ where $A$ consists of the single fact $P(a)$ and $\textbf{a}=a,\ldots,a$ has length $k$. It is not hard to show that every frontier of this (c-acyclic) structure must contain, up to homomorphic equivalence, all structures of the form $(B,\textbf{b})$ where $B$ consists of two facts, $P(a_1)$ and $P(a_2)$, and $\textbf{b}\in \{a_1, a_2\}^k$ is a sequence in which both $a_1$ and $a_2$ occur. There are exponentially many pairwise homomorphically incomparable such structures. The proof of Theorem~\ref{thm:cacyclic-polyfrontier} is based on a construction that improves over a similar but exponential construction of gap pairs for acyclic structures given in~\cite[Def.~3.9]{NesetrilTardif2000}. Our results also shed new light on a question posed in the same paper: after presenting a double-exponential construction of duals (for connected structures without designated elements), involving first constructing an exponential-sized gap pair, the authors ask: ``\emph{It would be interesting to know to what extent the characterisation of duals can be simplified, and whether the indirect approach via density is optimal}.'' This question appeared to have been answered in~\cite{NesetrilTardif2005}, where a direct method was established for constructing single-exponential size duals. Theorem~\ref{thm:cacyclic-polyfrontier} together with Lemma~\ref{lem:frontiers-and-dualities}, however, gives another answer: single-exponential duals can be constructed by going through frontiers (i.e., ``via density'') as well. Recall the definition of fg-connectedness from the preliminaries. We first prove a restricted version of Theorem~\ref{thm:cacyclic-polyfrontier} for special case of core, fg-connected, c-acyclic structures with the Unique Names Property. We subsequently lift these extra assumptions. A structure $(A, \textbf{a})$ with $\textbf{a}=a_1, \ldots a_k$ has the \emph{Unique Names Property (UNP)} if $a_i\neq a_j$ for all $i\leq j$ (cf.~\cite{baader2003basic}). \begin{proposition}\label{prop:fgconnected-cacyclic-unp} Given a core, fg-connected, c-acyclic structure with UNP, we can construct in polynomial time (for fixed schema $\mathcal{S}$ and number of distinguished elements $k$) a frontier w.r.t. the class of all finite structures. Furthermore, the frontier consists of a single structure, which has the UNP. \end{proposition} \begin{proof} Let a core fg-connected c-acyclic structure $(A, \textbf{a})$ with UNP be given. Note that each fg-connected structure either (i) consists of a single fact containing only designated elements, or (ii) consists of a number of facts that all contain at least one non-designated element. Therefore, we can distinguish two cases: Case 1. $A$ consists of a single fact $f$ without non-designated elements. Let $(B, \textbf{a})$ be the structure whose domain is $\{\textbf{a}, b\}$, where $b$ is a fresh value distinct from the values in $\textbf{a}$, and which contains all facts over this domain except $f$. It is easy to see that $(B,\textbf{a})$ is a homomorphism dual for $(A,\textbf{a})$, and consequently, the direct product of the two structures constitutes a singleton frontier for $(A, \textbf{a})$. Note that this construction is polynomial because we assume that the schema $\mathcal{S}$ and $k$ are both fixed. Case 2. $A$ consists of one or more facts that each contain a non-designated element. In this case, we construct a singleton frontier $F=\{B\}$ where \begin{itemize} \item the domain of $B$ consists of \begin{enumerate} \item all pairs $(a,f)$ where $a$ is a non-designated element of $A$ and $f$ is a fact of $A$ in which $a$ occurs, and \item All pairs $(a, \textsf{id})$ where $a$ is a designated element of $A$ \end{enumerate} \item a fact $R((a_1,f_1),\ldots, (a_n,f_n))$ holds in $B$ if and only if $R(a_1, \ldots, a_n)$ holds in $A$ and at least one $f_i$ is a fact that is different from the fact $R(a_1, \ldots, a_n)$ itself. \end{itemize} Note that, in the above construction, $\textsf{id}$ is an arbitrary symbol, used only to simplify notation by ensuring that every element of $B$ can we written as a pair. In what follows we will not distinguish between a designated element $a_i$ and the corresponding pair $(a_i, \textsf{id})$. We claim that $F=\{(B, \textbf{a})\}$ is a frontier for $(A, \textbf{a})$. It is clear that the natural projection $h:B\to A$ is a homomorphism. We claim that there is no homomorphism $h':A\to B$. Assume, for the sake of a contradiction, that there was such a homomorphism. We may assume that the composition of $h$ and $h'$ is the identity on $A$ (since $A$ is a core, the composition of $h$ and $h'$ is an automorphism of $A$, that is, an isomorphism from $A$ to itself. By composing $h$ with the inverse of this automorphism if needed, we ensure that its composition with $h'$ is the identity function). In particular, this means that $h'$ maps each designated element $a$ to $(a, \textsf{id})$ and for each non-designated element $a$ of $A$, $h'(a) = (a,f)$ for some fact $f$. For a non-designated element $a$, let us denote by $f_a$ the unique fact $f$ for which $h'(a)=(a,f_a)$. We will consider ``walks'' in $A$ of the form $$ a_1 \xrightarrow{f_{a_1}} a_2 \xrightarrow{f_{a_2}} \ldots a_n$$ with $n\geq 1$, where \begin{enumerate} \item $a_1, \ldots, a_n$ are non-designated elements, \item $f_{a_i} \neq f_{a_{i+1}}$, and \item $a_i$ and $a_{i+1}$ co-occur in fact $f_{a_i}$, \end{enumerate} Since $A$ is c-acyclic, the length of any such sequence is bounded by the diameter of $A$ (otherwise some fact would have to be traversed twice in succession, which would violate condition 2). Furthermore, trivially, such a walk of length $n=1$ exists: just choose as $a_1$ an arbitrary non-designated element of $A$. Furthermore, we claim that any such finite sequence can be extended to a longer one: let the fact $f_{a_n}$ be of the form $R(b_1, \ldots, b_m)$ (where $a_n = b_i$ for some $i\leq m$). Since $h$ is a homomorphism, it must map $f_{a_n}$ to some fact $R((b_1,f_{b_1}), \ldots, (b_m, f_{b_m}))$ of $B$, where some $f_{b_j}$ is a fact that is different from $f_{a_n}$. We can choose $b_j$ as our element $a_{n+1}$. Thus, we reach our desired contradiction. Finally, consider any $C$ with $h:C\to A$ and $A\not\to C$. We construct a function $h':C\to B$ as follows: consider any element $c$ of $C$, and let $h(c)=a$. If $a$ is a designated element, we set $h'(c)=(a,\textsf{id})$. Otherwise, we proceed as follows: since $A$ is c-acyclic and fg-connected, for each non-distinguished element $a'$ of $A$ (other than $a$ itself) there is a unique minimal path in the incidence graph, containing only non-distinguished elements, from $a'$ to $a$. We can represent this path by a sequence of the form \[a'=a_0 \xrightarrow{(f_0,i_0,j_0)} a_1 \xrightarrow{(f_1,i_1,j_1)} a_2 \cdots \xrightarrow{(f_{n-1},i_{n-1},j_{n-1})} a_n = a\] where each $f_\ell$ is a fact of $A$ in which $a_\ell$ occurs in the $i_\ell$-th position and $a_{\ell+1}$ occurs in the $j_\ell$-th position. We can partition the non-distinguished elements $a'$ of $A$ (other than $a$ itself) according to the last fact on this path, that is, $f_{n-1}$. Furthermore, it follows from fg-connectedness that each fact of $A$ contains a non-distinguished element. It is easy to see that if a fact contains multiple non-distinguished elements (other than $a$) then they must all belong to the same part of the partition as defined above. Therefore, the above partition on non-distinguished elements naturally extends to a partition on the facts of $A$. Note that if $A$ contains any facts in which $a$ is the only non-distinguished element, we will refer to these facts as ``local facts'' and they will be handled separately. In this way, we have essentially decomposed $A$ into a union $A_{\text{local}}\cup\bigcup_i A_i$, where $A_{\text{local}}$ contains all local facts and each ``component'' $A_i$ is a substructure of $A$ consisting of non-local facts, in such a way that (i) different substructures $A_i$ do not share any facts with each other, (ii) different substructures do not share any elements with each other, except for $a$ and distinguished elements, (iii) each $A_i$ contains precisely one fact involving $a$. Since we know that $(A,a)\not\to (C,c)$, it follows that either some local fact $f$ of $A$ does not map to $C$ (when sending $a$ to $c$), or some ``component'' $A_i$ of $A$ does not map to $C$ through any homomorphism sending $a$ to $c$. In the first case, we set $h'(a) = (a,f)$. In the second case, we choose such a component (if there are multiple, we choose one of minimal size) and let $f$ be the unique fact in that component containing $a$ (that is, $f$ is the fact $f_{n-1}$ that by construction connected the non-distinguished elements of the component in question to $a$). We set $h'(c) = (a,f)$. Intuitively, when $h'(c) = (h(c), f)$, then $f$ is a fact of $A$ involving $h(c)$ that ``points in a direction where homomorphism from $(A,h(c))$ back to $(C,c)$ fails''. We claim that $h'$ is a homomorphism from $C$ to $B$: let $R(c_1, \ldots, c_n)$ be a fact of $C$. Then $R(h(c_1), \ldots, h(c_n))$ holds in $A$. Let $h'(c_i)=(h(c_i), f_i)$ (where $f_i=\textsf{id}$ if $h(c_i)$ is a designated element of $A$). To show that $R(h'(c_1), \ldots, h'(c_n))$ holds in $B$, it suffices to show that some $f_i$ is different from the fact $R(h(c_1), \ldots, h(c_n))$ itself. If $f_i$ is a local fact, then this follows immediately from the construction. Otherwise, let $n_i$ be the size of the smallest ``component'' (as defined above) of $(A,h(c_i))$ that does not homomorphically map to $(C,c_i)$, and choose an element $c_i$ with minimal $n_i$. Then, clearly, $f_i$ must be different from the fact $R(h(c_1), \ldots, h(c_n))$ itself. \end{proof} Next, we remove the assumptions of fg-connectedness and being a core. \begin{proposition}\label{prop:unp-disconnected} Given a c-acyclic structure with UNP, we can construct in polynomial time a frontier w.r.t. the class of all finite structures. Furthermore, the frontier consists of structures that have the UNP. \end{proposition} \begin{proof} By Proposition~\ref{prop:cacyclic-core}, we may assume that $(A, \textbf{a})$ is a core. Note that the c-acyclicity and UNP properties are preserved under the passage from a structure to its core. Let $(A, \textbf{a})$ be a structure with designated elements that is UNP and that is a fg-disjoint union of homomorphically incomparable fg-connected structures $(A_1,\textbf{a}), \ldots, (A_n, \textbf{a})$. By Proposition~\ref{prop:fgconnected-cacyclic-unp}, $(A_1,\textbf{a}), \ldots, (A_n, \textbf{a})$ have, respectively, frontiers $F_1, \ldots, F_n$, each consisting of a single structure with the UNP. We may assume without loss of generality that each $F_i$ consists of structures that have the same designated elements $\textbf{a}$ as $A$ (we know that the structures in question satisfy the UNP, and therefore, modulo homomorphism, we can assume that their designated elements are precisely $\textbf{a}$). We claim that $F = \{ \big(\biguplus_{j\neq i} (A_j,\textbf{a})\big) \uplus (B,\textbf{a}) \mid 1\leq i\leq n, (B, \textbf{a})\in F_i\}$ is a frontier for $(A,\textbf{a})$ w.r.t.~$\mathcal{C}$. Clearly, each structure in $F$ maps homomorphically to $A$. Suppose, for the sake of contradiction, that there were a homomorphism from $h: (A,\textbf{a}) \to \big(\biguplus_{j\neq i} (A_j,\textbf{a})\big) \uplus (B,\textbf{a})$ for some $\mid 1\leq i\leq n$ and $(B,\textbf{a})\in F_i$. Observe that $h$ must send each designated element to itself, and it must send each non-designated element to a non-designated element (otherwise, the composition of $h$ with the backward homomorphism would be a non-injective endomorphism on $(A,\textbf{a})$ which would contradict the fact that $(A,\textbf{a})$ is a core). Since $(A_i,\textbf{a})$ is fg-connected (and because $h$ cannot send non-designated elements to designated elements), its $h$-image must be contained either in some $(A_j,\textbf{a})$ ($j\neq i$) or in $B$. The former would cannot happen because $A_i$ and $A_j$ are homomorphically incomparable. The latter cannot happen either, because $B$ belongs to a frontier of $A_i$. Finally, let $C\in\mathcal{C}$ be any structure such that there is a homomorphism $h:C\to A$ but $A\not\to C$. Let $A_i$ be a fg-connected component of $A$ such that $A_i\not\to C$. Since $A_i$ is fg-connected, we can partition our structure $C$ as $C_1\uplus C_2$ where the $h$-image of $C_1$ is contained in $A_i$ while the $h$-image of $C_2$ is disjoint from $A_i$. We know that $A_i\not\to C_1$ and therefore $C_1\to B$ for some $B\in F_i$. Furthermore, we have that $C_2\to \biguplus_{j\neq i} A_j$. Therefore, $C\to \big(\biguplus_{j\neq i} A_j\big) \uplus B \mid 1\leq i\leq n, B\mid B\in F_i\}$. \end{proof} Finally, we can prove Theorem~\ref{thm:cacyclic-polyfrontier} itself. \begin{proof}[Proof of Theorem~\ref{thm:cacyclic-polyfrontier}] Let $(A,\textbf{a})$ be c-acyclic. If it has the UNP, we are done. Consider the other case, where the sequence $\textbf{a}$ contains repetitions. Let $\textbf{a}' = a'_1, \ldots, a'_n$ consists of the same elements without repetition (in some order). We construct a frontier for it as follows: \begin{enumerate} \item Consider the structure $(A, \textbf{a}')$, which, by construction, has the UNP. Let $F$ be a frontier for $(A, \textbf{a}')$ (again consisting of structures with the UNP), using Proposition~\ref{prop:unp-disconnected}. Note that, through isomorphism, we may assume that each structure in $F$ has the same designated elements $\textbf{a}'$. For each $(B,\textbf{a}')\in F$, we take the structure $(B,\textbf{a})$. \item Let $k$ be the length of the tuple $\textbf{a}$. For each function $f:\{1, \ldots, k\}\to \{1, \ldots, k\}$, whose range has size strictly greater than $n$, consider structure $(C, \textbf{c}^f)$ where $C$ contains all facts over the domain $\{1, \ldots, k\}$, and $c^f_i = f(i)$. We take its direct product with $(A,\textbf{a})$. \end{enumerate} It is easy to see that the set of all structures constructed above, constitutes a frontier for $(A, \textbf{a})$. Indeed, suppose a structure maps to $(A,\textbf{a})$ but not vice versa. If the tuple of designated elements of the structure in question has the same identity type as the tuple $\textbf{a}$ (i.e., the same equalities hold between values at different indices in the tuple) then it is easy to see that the structure in question must map to some structure $(B, \textbf{a})$ as constructed under item 1 above. Otherwise, if the tuple of designated elements of the structure in question does \emph{not} have the same identity type, then it is easy to see that the structure in question must map to $(C^f, \textbf{c}^f)\times (A, \textbf{a})$, as constructed under item 2 above, where $f$ reflects the identity type of the designated elements of the structure in question. \end{proof} As a corollary of Theorem~\ref{thm:cacyclic-polyfrontier}, we obtain the following interesting by-product: \begin{theorem} \label{thm:testing-frontier} For a fixed schema $\mathcal{S}$ and $k\geq 0$, the following problem is solvable in NP: given a finite set of structures $F$ and a structure $A$ (all with $k$ designated elements), is $F$ a frontier for $A$ w.r.t.~the class of all structures? For some $\mathcal{S}$ and $k$, it is NP-complete. \end{theorem} \begin{proof} For the upper bound, we use the fact that, if $A$ is homomorphically equivalent to a c-acyclic structure $A'$, then the core of $A$ is c-acyclic (cf.~Theorem~\ref{thm:cacyclic}). The problem can therefore be solved in non-deterministic polynomial time as follows: First we guess a substructure $A'$ and we verify that $A'$ is c-acyclic and homomorphically equivalent to $A$. Note that the existence of such $A'$ is a necessary precondition for $F$ to be a frontier of $A$. Furthermore, c-acyclicity can be checked in polynomial time using any PTIME algorithm for graph acyclicity (recall that a structure is c-acyclic if and only if its incidence graph is acyclic after removing all nodes corresponding to designated elements). Next, we apply Theorem~\ref{thm:cacyclic-polyfrontier} to construct a frontier $F'$ for $A'$ (and hence for $A$). Finally, we verify that each $B\in F$ homomorphically maps to some $B'\in F'$ and, vice versa, every $B'\in F'$ homomorphically maps to some $B\in F$. It is not hard to see that this non-deterministic algorithm has an accepting run if and only if $F$ is a frontier for $A$. For the lower bound, we reduce from graph 3-colorability. Let $A$ be the structure, over a 3-element domain, that consists of the facts $R(a,b)$ for all pairs $a,b$ with $a\neq b$. In addition, each of the three elements is named by a constant symbol. Since $A$ is c-acyclic, by Theorem~\ref{thm:cacyclic}, it has a frontier $F$. Now, given any graph $G$ (viewed as a relational structure with binary relation $R$ and without constant symbols), we have that $G$ is 3-colorable if and only if $F$ is a frontier for the disjoint union of $A$ with $G$. To see that this is the case, note that if $G$ is 3-colorable, then the disjoint union of $A$ with $G$ is homomorphically equivalent to $A$ itself, whereas if $G$ is not 3-colorable, then the disjoint union of $A$ with $G$ is strictly greater than $A$ in the homomorphism order. \end{proof} \subsection{A polynomially frontier-closed class of structures} We call a class $\mathcal{C}$ of structures \emph{frontier-closed} if every structure $(A,\textbf{a})\in\mathcal{C}$ has a frontier w.r.t.~$\mathcal{C}$, consisting of structures belonging to $\mathcal{C}$. If, moreover, the frontier in question can be constructed from $(A,\textbf{a})$ in polynomial time, then we say that $\mathcal{C}$ is \emph{polynomially frontier-closed}. \begin{theorem}\label{thm:frontier-closed} The class of c-connected acyclic structures with 1 designated element is polynomially frontier-closed.~\footnote{Note that for structures with one distinguished element, c-connectedness is the same as connectedness.} \end{theorem} As will follow from results in Section~\ref{sec:characterizations} (cf.~Theorems~\ref{thm:unary-is-necessary}-\ref{thm:acyclicity-is-necessary} below) the theorem fails if we drop any of the three restrictions in the statement (i.e., c-connectedness, acyclicity, and $k=1$). However, it might quite well be the case that still holds for some other values of $k$. Indeed, we conjecture that Theorem~\ref{thm:frontier-closed} remains true for any $k>1$. \section{Unique Characterizations for Conjunctive Queries} \label{sec:characterizations} In this section, we study the question when a CQ is uniquely characterizable by a finite set of positive and/or negative examples. \begin{definition}[Data Examples, Fitting, Unique Characterizations] Let $\mathcal{C}$ be a class of $k$-ary CQs over a schema $\mathcal{S}$ (for some $k\geq 0$), and let $q$ be a $k$-ary query over $\mathcal{S}$. \begin{enumerate} \item A \emph{data example} is a structure $(A,\textbf{a})$ over schema $\mathcal{S}$ with $k$ distinguished elements. If $\textbf{a} \in q(A)$, we call $(A,\textbf{a})$ a \emph{positive example} (for $q$), otherwise a \emph{negative example}. \item Let $E^+, E^-$ be finite sets of data examples. We say that $q$ \emph{fits} $(E^+,E^-)$ if every example in $E^+$ is a positive example for $q$ and every example in $E^-$ is a negative example for $q$. We say that $(E^+,E^-)$ \emph{uniquely characterizes $q$ w.r.t.~$\mathcal{C}$} if $q$ fits $(E^+,E^-)$ and every $q'\in\mathcal{C}$ that fits $(E^+,E^-)$ is logically equivalent to $q$. \end{enumerate} \end{definition} It turns out that there is a precise correspondence between unique characterizations and frontiers. Recall that the canonical structure of a query $q$ is denoted by $\widehat{q}$. Similarly, for any class of CQs $\mathcal{C}$, we will denote by $\widehat{\mathcal{C}}$ the class of structures $\{\widehat{q}\mid q\in\mathcal{C}\}$. \begin{proposition}[Frontiers vs Unique Characterizations] \label{prop:frontiers-characterizations} Fix a schema $\mathcal{S}$ and $k\geq 0$. Let $q$ be any $k$-ary CQ over $\mathcal{S}$ and $\mathcal{C}$ a class of $k$-ary CQs over $\mathcal{S}$. \begin{enumerate} \item If $F$ is a frontier for $\widehat{q}$ w.r.t.~$\widehat{\mathcal{C}}$, then $(E^+ = \{\widehat{q}\},E^- = F)$ uniquely characterizes $q$ w.r.t.~$\mathcal{C}$. \item Conversely, if $(E^+,E^-)$ uniquely characterizes $Q$ w.r.t.~$\mathcal{C}$, then $F = \{ \widehat{q} \times (B,\textbf{b}) \mid (B,\textbf{b})\in E^-\}$ is a frontier for $\widehat{q}$ w.r.t.~$\widehat{\mathcal{C}}$. \end{enumerate} \end{proposition} Proposition~\ref{prop:frontiers-characterizations} allows us to take the results on frontiers from the previous section, and rephrase them in terms of unique characterizations. Incidentally, note that results in~\cite{AlexeCKT2011} imply an analogous relationship between \emph{finite dualities} and uniquely characterizing sets of examples for \emph{unions of conjunctive queries}. We need two more lemmas. Recall that a structure $(A,\textbf{a})$ corresponds to a conjunctive query only if every distinguished element occurs in at least one fact. Let us call such structures \emph{safe}. The following lemmas, essentially, allow us to ignore unsafe structures, thereby bridging the gap between structures and CQs. \begin{lemma} \label{lem:characterisation-safe} Let $q$ be a $k$-ary CQ over schema $\mathcal{S}$ and $\mathcal{C}$ a class of $k$-ary CQs over $\mathcal{S}$. If $q$ is uniquely characterized w.r.t.~$\mathcal{C}$ by positive and negative examples $(E^+,E^-)$, then $q$ is uniquely characterized w.r.t.~$\mathcal{C}$ by $(\{(A,\textbf{a})\in E^+\mid \text{$(A,\textbf{a})$ is safe}\}, \{(A,\textbf{a})\in E^-\mid \text{$(A,\textbf{a})$ is safe}\})$. \end{lemma} \begin{lemma}\label{lem:frontier-safe} A safe structure has a finite frontier w.r.t.~all structures if and only if it has a finite frontier w.r.t.~the class of all safe structures. \end{lemma} Putting everything together, we obtain the main result of this section. We call a CQ $q$ c-acyclic (or acyclic, or c-connected) if the structure $\widehat{q}$ is c-acyclic (resp.~acyclic, c-connected). \begin{theorem} \label{thm:characterizations-main} Fix a schema and fix $k\geq 0$. \begin{enumerate} \item If $\mathcal{C}$ is a class of $k$-ary CQs such that $\widehat{C}$ has bounded expansion, then every CQ $q\in\mathcal{C}$ is uniquely characterizable w.r.t.~$\mathcal{C}$ by finitely many positive and negative examples (which can be effectively constructed from the query). \item A $k$-ary CQ $q$ is uniquely characterizable by finitely many positive and negative examples (w.r.t.~the class of all $k$-ary CQs) iff $q$ is logically equivalent to a c-acyclic CQ. Moreover, for a c-acyclic CQ, a uniquely characterizing set of examples can be constructed in polynomial time. \item Assume $k=1$ and let $\mathcal{C}_{ca}$ be the class of $k$-ary CQs that are c-connected and acyclic. Then every $q\in \mathcal{C}_{ca}$ is uniquely characterizable w.r.t.~$\mathcal{C}_{ca}$ by finitely many positive and negative examples belonging to $\widehat{\mathcal{C}_{ca}}$. Moreover, the set of examples in question can be constructed in polynomial time. \end{enumerate} \end{theorem} \begin{remark}\label{rem:unsafe} For the purpose of applications discussed in Section~\ref{sec:applications}, we note that Theorem~\ref{thm:characterizations-main} remains true if the safety condition for CQs were to be dropped. Indeed, the proof in this case is even simpler, as it does not require Lemma~\ref{lem:characterisation-safe} and Lemma~\ref{lem:frontier-safe}. \end{remark} Theorem~\ref{thm:characterizations-main}(3) applies to CQs with $k=1$ that are c-connected, and acyclic. None of these restrictions can be dropped. \newcommand{\operatorname{{\bf G}}}{\operatorname{{\bf G}}} \newcommand{\operatorname{{\bf I}}}{\operatorname{{\bf I}}} \newcommand{\operatorname{{\bf J}}}{\operatorname{{\bf J}}} \newcommand{\operatorname{{\bf A}}}{\operatorname{{\bf A}}} \newcommand{\operatorname{{\bf B}}}{\operatorname{{\bf B}}} \newcommand{\operatorname{dom}}{\operatorname{dom}} \newcommand{\operatorname{{\bf T}}}{\operatorname{{\bf T}}} \newcommand{\operatorname{{\bf R}}}{\operatorname{{\bf R}}} \newcommand{\operatorname{{\bf S}}}{\operatorname{{\bf S}}} \newcommand{\operatorname{sdr}}{\operatorname{sdr}} \begin{theorem}\label{thm:unary-is-necessary} The Boolean acyclic connected CQ ~ $\operatorname{{\bf T}}() \textrm{ :- } Ry_1y_2\land Ry_2y_3\land Ry_3y_4 \land Ry_4y_5$ is not characterized, w.r.t.~the class of Boolean acyclic connected CQs, by finitely many acyclic positive and negative examples. \end{theorem} This shows that in Theorem~\ref{thm:characterizations-main}(3), the restriction to \emph{unary} queries cannot be dropped. Similarly, the restriction to \emph{c-connected} queries cannot be dropped, and acyclicity cannot be replaced by the weaker condition of c-acyclicity. \begin{theorem}\label{thm:connectedness-is-necessary} The unary acyclic CQ ~~ $\operatorname{{\bf T}}'(x) \text{ :- } P(x)\land Ry_1 y_2\land Ry_2y_3\land Ry_3y_4 \land Ry_4 y_5$ is not uniquely characterizable, w.r.t.~the class of unary acyclic CQs, by finitely many acyclic positive and negative examples. \end{theorem} \begin{theorem}\label{thm:acyclicity-is-necessary} The unary c-acyclic c-connected CQ ~ $\operatorname{{\bf T}}''(x) \text{ :- } Ry_1 y_2\land Ry_2y_3\land Ry_3y_4 \land Ry_4 y_5\land \bigwedge_{i=1\ldots 5} Rxy_i$ ~ is not uniquely characterizable, w.r.t.~the class of unary c-acyclic c-connected CQs, by finitely many c-acyclic positive and negative examples. \end{theorem} \section{Exact learnability with membership queries} \label{sec:learning} The unique characterization results in the previous section immediately imply (not-necessarily-efficient) exact learnability results: \begin{theorem} \label{th:learn-bounded-expansion} Fix a schema and $k\geq 0$. Let $\mathcal{C}$ be a computably enumerable class of $k$-ary CQs. If $\widehat{\mathcal{C}}$ has bounded expansion, then $\mathcal{C}$ is exactly learnable with membership queries. \end{theorem} The learning algorithm in question simply enumerates all queries $q\in\mathcal{C}$ and uses membership queries to test if the goal query fits the uniquely characterizing set of examples of $q$ (cf.~Theorem~\ref{thm:characterizations-main}(1)). Unfortunately, this learning algorithm does not run in polynomial time. Indeed, the number of membership queries is not bounded by any fixed tower of exponentials. For the special case of c-acyclic queries, we can do a little better by taking advantage of the fact that a uniquely characterizing set of examples can be constructed in polynomial time. Indeed, the class of c-acyclic $k$-ary CQs is exponential-time exactly learnable with membership queries: the learner can simply enumerates all c-acyclic queries in order of increasing size. For each query $q$ (starting with the smallest query), it uses Theorem~\ref{thm:characterizations-main}(2) to test, using polynomially many membership queries, whether the goal query is equivalent to $q$. After at most $2^{O(n)}$ many attempts (where $n$ is the size of the goal query), the algorithm is guaranteed to find a query that is equivalent to the goal query.% \footnote{Similarly, by Theorem~\ref{thm:characterizations-main}(3), the class of unary acyclic c-connected queries is exponential-time exactly learnable with subset queries, where a \emph{subset query} is an oracle query asking whether a given CQ from the concept class is implied by the goal query. Subset queries correspond precisely to membership queries where the example is the canonical structure of a query from the concept class.} Our main result in this section improves on this by establishing \emph{efficient} (i.e., polynomial-time) exact learnability: \begin{theorem} \label{th:membership} For each schema and $k\geq 0$, the class of c-acyclic $k$-ary CQs is efficiently exactly learnable with membership queries. \end{theorem} At a high level, the learning algorithm works by maintaining a c-acyclic hypothesis that is an over-approximation of the actual goal query. At each iteration, the hypothesis is strengthened by replacing it with one of the elements of its frontier, a process that is shown to terminate and yield a query that is logically equivalent to the goal query. Note, however, that the frontier of a c-acyclic structure does not, in general, consist of c-acyclic structures. At the heart of the proof of Theorem~\ref{th:membership} lies a non-trivial argument showing how to turn an arbitrary hypothesis into a c-acyclic one with polynomially many membership queries. The class of \emph{all} $k$-ary queries is not exactly learnable with membership queries (even with unbounded amount of time and the ability to ask an unbounded number of oracle queries), because exact learnability with membership queries would imply that every query in the class is uniquely characterizable, which we know is not the case. On the other hand, we have: \begin{theorem}[from~\cite{CateDK13:learning}]\label{thm:memb-equiv} For each schema $\mathcal{S}$ and $k\geq 0$, the class of all $k$-ary CQs over $\mathcal{S}$ is efficiently exactly learnable with membership and equivalence queries. \end{theorem} In fact, it follows from results in~\cite{CateDK13:learning} that the larger class of all \emph{unions of conjunctive queries} is efficiently exactly learnable with membership and equivalence queries (for fixed $k$ and fixed schema). Efficient exact learnability with membership and equivalence queries is not a monotone property of concept classes, but the result from~\cite{CateDK13:learning} transfers to CQs as well. For the sake of completeness, a self-contained proof of Theorem~\ref{thm:memb-equiv} is in the appendix. \begin{remark}\label{rem:learning-unsafe} For the purpose of applications discussed in Section~\ref{sec:applications}, we note that Theorems~\ref{th:learn-bounded-expansion}-~\ref{thm:memb-equiv} remain true if the safety condition for CQs were to be dropped. \end{remark} \subparagraph*{Related Work} There has been considerable prior work that formally studies the task of identifying some unknown goal query $Q$ from examples. Work in this direction includes learning CQs, Xpath queries, Sparql, tree patterns, description logic concepts, ontologies, and schema mappings among others \cite{BonifatiCL15,CateDK13:learning,GottlobS10,StaworkoW12}. We shall describe mostly the previous work regarding learning CQs. Some of the work in this direction (\cite{Barcelo017,CateD15,Cohen94a,Hirata00,Willard10} for example) assumes that a background structure $A$ is fixed and known by the algorithm. In this setting, a {\em example} is a $k$-ary tuple $(a_1,\dots,a_k)$ of elements in $A$, labelled positively or negatively depending on whether it belongs or not to $Q(A)$. In the present paper (as in \cite{CateDK13:learning,Haussler89}) we do not fix any background structure (i,e, examples are pairs of the form $(A,\textbf{a})$). Our setting corresponds also to the extended instances with empty background in \cite{Cohen95}. In both cases a number of different learning protocols has been considered. In the reverse-engineering problem (as defined in~\cite{WeissC17}) it is only required that the algorithm produces a query consistent with the examples. In a similar direction, the problem of determining whether such a query exists has been intensively studied under some variants (satisfiability, query-by-example, definability, inverse satisfiability) \cite{Barcelo017,CateD15,Willard10}. In some scenarios, it is desirable that the query produced by the learner not only explains the examples received during the training phase, but also has also predictive power. In particular, the model considered in \cite{BonifatiCS16} follows the paradigm of identification in the limit by Gold and requires that, additionally, there exists a finite set of examples that uniquely determines the target query $Q$. In a different direction, the model introduced in \cite{GottlobS10}, inspired by the minimum description length principle, requires to produce a hypothesis consistent after some repairs. A third line of work (see \cite{Cohen93,Haussler89,Hirata00}) studies this problem under Valiant's probably approximately correct (PAC) model. The present paper is part of a fourth direction based on the exact model of query identification by Angluin. In this model, instead of receiving labelled examples, the learner obtains information about the target query by mean of calls to an oracle. As far as we know, we are the first to study the exact learnability of CQs using a membership oracle. \section{Further Applications} \label{sec:applications} While our main focus in this paper is on unique characterizability and exact learnability for CQs, in this section, we explore some implications for other application domains. \subsection{Characterizability and learnability of LAV schema mappings} A schema mapping is a high-level declarative specifications of the relationships between two database schemas~\cite{Kolaitis05schema}. Two of the most well-studied schema mapping specification languages are \emph{LAV (``Local-as-View'')} and \emph{GAV (``Global-as-View'')} schema mappings. In~\cite{AlexeCKT2011}, the authors studied the question when a schema mapping can be uniquely characterized by a finite set of data examples. Different types of data examples were introduced and studied, namely positive examples, negative examples, and ``universal'' examples. In particular, it was shown in~\cite{AlexeCKT2011} that a GAV schema mapping can be uniquely characterized by a finite set of positive and negative examples (or, equivalently, by a finite set of universal examples) if and only if the schema mapping in question is logically equivalent to one that is specified using c-acyclic GAV constraints. It was shown in~\cite{AlexeCKT2011} that every LAV schema mapping is uniquely characterized by a finite set of universal examples, and that there are LAV schema mappings that are not uniquely characterized by any finite set of positive and negative examples. In this section, we will consider the question \emph{which} LAV schema mappings are uniquely characterizable by a finite set of positive and negative examples, and how to construct such a set of examples efficiently. We will also consider the exact learnability of LAV schema mappings with membership queries. Exact learnability of GAV schema mappings was studied in~\cite{CateDK13:learning}, where it was shown that GAV schema mappings are learnable with membership and equivalence queries (and, subsequently, also in a variant of the PAC model) but is not exactly learnable with membership queries alone or with equivalence queries alone. The exact learning algorithm for GAV schema mappings from~\cite{CateDK13:learning} was further put to use and validated experimentally in~\cite{Kun18active}. Here, we consider exact learnability of LAV schema mappings with membership queries. \begin{definition A \emph{LAV (``Local-As-View'') schema mapping} is a triple $M=(S,T,\Sigma)$ where $S$ and $T$ are disjoint schemas (the ``source schema'' and ``target schema''), and $\Sigma$ is a finite set of \emph{LAV constraints}, that is, first-order sentences of the form $\forall\textbf{x}(\alpha(\textbf{x})\to\exists \textbf{y}\phi(\textbf{x},\textbf{y}))$, where $\alpha(\textbf{x})$ is an atomic formula using a relation from $S$, and $\phi(\textbf{x},\textbf{y})$ is a conjunction of atomic formulas using relations from $T$. \end{definition} By a \emph{schema-mapping example} we will mean a pair $(I,J)$ where $I$ is a structure over schema $\mathcal{S}$ without distinguished elements, and $J$ is a structure over schema $\mathcal{T}$ without distinguished elements. We say that $(I,J)$ is a \emph{positive example} for a schema mapping $M=(\mathcal{S},\mathcal{T},\Sigma)$ if $(I,J)$, viewed as a single structure over the joint schema $\mathcal{S}\cup\mathcal{T}$, satisfies all constraints in $\Sigma$, and we call $(I,J)$ a \emph{negative example} for $M$ otherwise. Note that schema-mapping examples were called \emph{data examples} in~\cite{AlexeCKT2011}. Unique characterizations and learnability with membership queries are defined as before. In particular, by a \emph{membership query}, in the context of learning LAV schema mappings, we will mean an oracle query that consists of a schema-mapping example, which the oracle then labels as positive or negative depending on whether it satisfies the constraints of the goal LAV schema mapping. It is assumed here, that the source and target schemas are fixed and known to the learner. Given a fixed source schema $\mathcal{S}$, there are only finitely many different possible left-hand sides $\alpha$ for a LAV constraint, up to renaming of variables. Furthermore, if a schema mapping contains two LAV constraints with the same left-hand side, then they can be combined into a single LAV constraint by conjoining the respective right-hand sides. Since the right-hand side of a LAV constraint can be thought of as a CQ, this means that, intuitively, a LAV schema mapping can be thought of as a finite collection of CQs (one for each possible left-hand side). In the light of this observation, it is no surprise that questions about the unique characterizability and learnability of LAV schema mappings can be reduced to questions about the unique characterizability and learnability of CQs. \newcommand{\textrm{ATOMS}}{\textrm{ATOMS}} Let us capture this observation a little more precisely. Let $k$ be the maximum arity of a relation in $\mathcal{S}$, and let $\textrm{ATOMS}_{\mathcal{S}}$ be the finite set of all atomic formulas using a relation from $\mathcal{S}$ and variables from $\{z_1, \ldots, z_k\}$. Given a LAV schema mapping $M=(\mathcal{S},\mathcal{T},\Sigma)$ and an $\alpha(\textbf{z})\in \textrm{ATOMS}_{\mathcal{S}}$, we denote by $q_{M,\alpha}(\textbf{z})$ the following first-order formula over schema $\mathcal{T}$: \[\mathop{\bigwedge_{\forall\textbf{x}(\beta(\textbf{x})\to\exists \textbf{y}\phi(\textbf{x},\textbf{y}))\in \Sigma}}_{ \text{$h:\{\textbf{x}\}\to\{\textbf{z}\}$ a function s.t.~$\beta(h(\textbf{x})) = \alpha(\textbf{z})$}} \exists \textbf{y}\phi(h(\textbf{x}),\textbf{y})\] For example, if $M$ consists of the LAV constraints $\forall x_1, x_2, x_3 . R(x_1,x_2,x_3)\to S(x_1,x_2,x_3)$ and $\forall x_1, x_2 . R(x_1,x_2,x_2)\to \exists y T(x_1,y)$, and $\alpha(z_1)$ is $R(z_1, z_1, z_1)$, then $q_{M,\alpha} = S(z_1,z_1,z_1)\land \exists y T(z_1,y)$. Similarly, for $\alpha'(z_1, z_2, z_3) = R(z_1, z_2, z_3)$ then $q_{M,\alpha'} = S(z_1,z_2,z_3)$. Note that $q_{M,\alpha}(\textbf{z})$ can be equivalently written as a not-necessarily-safe CQ over $\mathcal{T}$ (by pulling the existential quantifies to the front). \begin{lemma}\label{lem:lav-lemma1} Let $M=(\mathcal{S},\mathcal{T},\Sigma)$ be any LAV schema mapping, and let $\alpha(\textbf{z})\in \textrm{ATOMS}_\mathcal{S}$ have $k$ many distinct variables. For every structure $(A,\textbf{a})$, over schema $\mathcal{T}$ and with $k$ distinguished elements, the following are equivalent: \begin{enumerate} \item $(A,\textbf{a})$ is a positive data example for $q_{M,\alpha}(\textbf{z})$, \item The schema-mapping example $(I,J)$ is a positive example for $M$, where $I$ is the structure over $\mathcal{S}$ consisting of the single fact $\alpha(\textbf{a})$, and $J = A$. \end{enumerate} \end{lemma} We omit the proof, which is straightforward (note that the left-hand side of a LAV constraint can have at most one homomorphism to $I$, and the latter can be extended to the right-hand side of the constraint to $J$ iff the respective conjunct of $q_{M,\alpha}$ is satisfied). Intuitively, Lemma~\ref{lem:lav-lemma1} shows that the behavior of $q_{M,\alpha}$ on arbitrary data examples, is fully determined by the behavior of $M$ on arbitrary schema-mapping examples. The converse turns out to be true as well, that is, the semantics of a LAV schema mapping $M=(\mathcal{S},\mathcal{T},\Sigma)$ is determined (up to logical equivalence) by its associated queries $q_{M,\alpha}$ for $\alpha\in \textrm{ATOMS}_{\mathcal{S}}$: \begin{lemma}\label{lem:lav-lemma2} Two LAV schema mappings $M_1 = (\mathcal{S},\mathcal{T},\Sigma_1)$, $M_2 = (\mathcal{S},\mathcal{T},\Sigma_1)$ are logically equivalent iff, for every $\alpha(\textbf{z})\in \textrm{ATOMS}_{\mathcal{S}}$, $q_{M_1,\alpha}(\textbf{z})$ and $q_{M_2,\alpha}(\textbf{z})$ are logically equivalent. \end{lemma} \begin{proof} The left-to-right direction follows immediately from the preceding Lemma. For the right-to-left direction: suppose $M_1$ and $M_2$ are not logically equivalent. Then they disagree on some schema-mapping example $(I,J)$. Without loss of generality, we may assume that $(I,J)$ is a positive example for $M_1$ and a negative example for $M_2$. In particular, one of the LAV constraints in $\Sigma_2$ is false in $(I,J)$. Since the left-hand side of a LAV constraint consists of a single atom, it follows that, for some fact $R(\textbf{a})$ of $I$, the schema-mapping example $(\{R(\textbf{a})\}, J)$ is a negative example for $M_2$. Moreover, an easy monotonicity argument shows that $(\{R(\textbf{a})\}, J)$ is a positive example for $M_1$. Let $\alpha$ be obtained from the fact $R(\textbf{a})$ by replacing each distinct element $a_i$ by a corresponding variable $z_i$. It follows from Lemma~\ref{lem:lav-lemma1} that $q_{M_1,\alpha}$ and $q_{M_2,\alpha}$ disagree on the structure $(J,\textbf{a})$, and are not logically equivalent. \end{proof} It follows directly from the above Lemmas that the unique characterizability of a LAV schema mapping $M$ reduces to the unique characterizability of each query $q_{M,\alpha}$: \begin{lemma}\label{lem:lav-lemma3} For all LAV schema mappings $M=(\mathcal{S},\mathcal{T},\Sigma)$, the following are equivalent: \begin{enumerate} \item $M$ is uniquely characterizable by finitely many positive and negative schema-mapping examples (w.r.t.~the class of all LAV schema mappings over $\mathcal{S},\mathcal{T}$). \item For each $\alpha(z_1, \ldots, z_k)\in \textrm{ATOMS}_{\mathcal{S}}$, $q_{M,\alpha}(z_1, \ldots, z_k)$ is uniquely characterizable by finitely many positive and negative data examples w.r.t. the class of all $k$-ary not-necessarily-safe CQs over $\mathcal{T}$. \end{enumerate} \end{lemma} Intuitively, this shows that a LAV schema mapping is uniquely characterizable iff each of its constraints (joined together according to their left-hand side atom) are. By combining these lemmas with Theorem~\ref{thm:characterizations-main} (cf.~Remark~\ref{rem:unsafe}), we can link the unique characterizability of a LAV schema mapping to the condition of c-acyclicity. We say that a LAV schema mapping $M$ is c-acyclic if the right-hand side of each of its LAV constraints is a c-acyclic not-necessarily-safe CQ. Note that, in this case, also $q_{M,\alpha}$ is c-acyclic, for each $\alpha\in \textrm{ATOMS}_{\mathcal{S}}$. \begin{theorem}\label{thm:lav-characterizations} Fix a source schema $\mathcal{S}$ and a target schema $\mathcal{T}$. A LAV schema mapping $M=(\mathcal{S},\mathcal{T},\Sigma)$ is uniquely characterizable by a finite set of positive and negative schema-mapping examples if and only if $M$ is logically equivalent to a c-acyclic LAV schema mapping. Moreover, if $M$ is c-acyclic, then a uniquely characterizing set of positive and negative schema-mapping examples can be constructed in polynomial time (for fixed $\mathcal{S}, \mathcal{T}$). \end{theorem} \begin{proof} The direction going from c-acyclicity to the uniquely characterizing set of schema-mapping examples, follows immediately from the above lemmas together with Theorem~\ref{thm:characterizations-main}. For the other direction, assume that $M$ is uniquely characterizable by finitely many positive and negative schema-mapping examples. It follows by Lemma~\ref{lem:lav-lemma3} that each $q_{M,\alpha}$ is uniquely characterizable by finitely many positive and negative data examples. Hence, each $q_{M,\alpha}$ is logically equivalent to a c-acyclic not-necessarily-safe conjunctive query $q'_{M,\alpha}$. Finally, let $M'=(\mathcal{S}, \mathcal{T}, \Sigma')$, where $\Sigma'$ consists of all LAV constraints of the form $\forall \textbf{z}(q_{M,\alpha}(\textbf{z}) \to \alpha(\textbf{z}))$ for $\alpha(\textbf{z})\in \textrm{ATOMS}_\mathcal{S}$. Then $M'$ is c-acyclic and logically equivalent to $M$. \end{proof} Similarly, Lemma~\ref{lem:lav-lemma1} and Lemma~\ref{lem:lav-lemma2}, together with Theorem~\ref{th:membership}, directly imply: \begin{theorem} Fix a source schema $\mathcal{S}$ and a target schema $\mathcal{T}$. The class of c-acyclic LAV schema mappings over $\mathcal{S}, \mathcal{T}$ is efficiently exactly learnable with membership queries. \end{theorem} Note that the class of \emph{all} LAV schema mappings over $\mathcal{S}, \mathcal{T}$ is \emph{not} exactly learnable with membership queries (assuming that $\mathcal{S}$ is non-empty and $\mathcal{T}$ contains a relation of arity at least 2). This follows immediately from the existence of LAV schema mappings that are not uniquely characterizable by finitely many positive and negative schema-mapping examples. As mentioned earlier, LAV schema mappings and GAV schema mappings are two of the most well-studied schema mapping languages. GLAV (``Global-and-Local-As-Views'') schema mappings is another, which forms a common generalization. An important remaining open question in the area example-driven approaches to schema mapping design is the following~\cite{AlexeCKT2011}: \emph{which GLAV schema mappings are uniquely characterizable by a finite set of examples}? \subsection{Learning description logic concept expressions and ABoxes} Description logics are formal specification languages used to represent domain knowledge. Example-driven and machine-learning based approaches have a long history in this area, and have received renewed interest in the last years~\cite{Ozaki2020:learning}. In particular, ontologies specified in the lightweight description logic $\mathcal{ELI}$, focusing on the exact learnability of ontologies using entailment queries and equivalence queries. As we show in this section, our results on c-acyclic CQs have some implications for the exact learnability of $\mathcal{ELI}$ concept expressions. \begin{definition}[$\mathcal{ELI}$ Concept expressions, ABoxes, TBoxes] Let $N_C, N_R, N_I$ be fixed, disjoint sets, whose members we will refer to as ``concept names'', ``role names'', and ''individual names'', respectively. $N_C$ and $N_R$ are assumed to be finite, while $N_I$ is assumed to be infinite. A \emph{concept expression} $C$ is an expression built up from from concept names in $N_C$ and $\top$, using conjunction ($C_1\sqcap C_2$) and existential restriction ($\exists r.C$ or $\exists r^-.C$, where $r\in N_R$). An \emph{ABox} is a finite set of \emph{ABox axioms} of the form $P(a)$ and/or $r(a, b)$, where $P\in N_C$, $r\in N_R$, and $a,b\in N_I$. A \emph{TBox} is a finite set of \emph{TBox axioms} $C\sqsubseteq D$, where $C, D$ are concept expressions. \end{definition} The semantics of these expressions can be explained by translation to first-order logic: \begin{definition The \emph{correspondence schema} is the schema that contains a unary relation for every $A\in N_C$ and a binary relation for every $r\in N_R$. Through the standard translation from description logic to first-order logic (cf.~Table~\ref{tab:standard-translation}), every concept expression $C$ translates to a first-order formula $q_C(x)$ over the correspondence schema. By extension, every TBox $\mathcal{T}$ translates to a finite first-order theory $\mathcal{T}^\text{fo}$, where $C_1\sqsubseteq C_2$ translates to $\forall x(q_{C_1}(x)\to q_{C_2}(x))$. \end{definition} \begin{table} \[ \begin{array}{rcl} q_{P}(x) &=& A(x) ~ \text{ for $P\in N_C$} \\ q_\top(x) &=& \top \\ q_{C_1\sqcap C_2}(x) &=& q_{C_1}(x) \land q_{C_2}(x) \\ q_{\exists r.C}(x) &=& \exists y (r(x,y)\land q_{C}(y) \\ q_{\exists r^-.C}(x) &=& \exists y (r(y,x)\land q_{C}(y) \\ \end{array} \] \caption{Standard translation from concept expressions to first-order logic} \label{tab:standard-translation} \end{table} An ABox can equivalently viewed as a finite structure (without designated elements), whose domain consists of individual names from $N_I$, and whose facts are the ABox assertions. Since $N_I$ is assumed to be infinite, every finite structure over the correspondence schema can (up to isomorphism) be represented as an ABox. Therefore, in what follows we will use ABoxes and structures interchangeably. We can think of an ABox as a (possibly incomplete) list of facts, and a TBox as domain knowledge in the form of rules for deriving more facts. This idea underlies the next definition: \begin{definition A \emph{QA-example} is a pair $(\mathcal{A},a)$ where $\mathcal{A}$ is an ABox and $a\in N_I$. We say that $(\mathcal{A},a)$ is a \emph{positive} QA-example for a concept expression $C$ relative to a TBox $\mathcal{T}$ if $a\in\text{certain}(C,\mathcal{A},\mathcal{T})$ where $\text{certain}(C,\mathcal{A},\mathcal{T}) = \bigcap\{ q_C(B) \mid \text{$\mathcal{A}\subseteq B$ and $B\models \mathcal{T}^\text{fo}$}\}$. If $a\not\in\text{certain}(C,\mathcal{A},\mathcal{T})$, we say that $(\mathcal{A},a)$ is a negative QA-example for $C$ relative to $\mathcal{T}$. \end{definition} The name \emph{QA-example}, here, reflects the fact that the task of computing $\text{certain}(C,\mathcal{A},\mathcal{T})$ is commonly known as \emph{query answering}. It is one of the core inference tasks studied in the description logic literature. In general, there are two variants of the definition of $\text{certain}(C,\mathcal{A},\mathcal{T})$: one where $B$ ranges over finite structures, and one where $B$ ranges over all, finite or infinite, structures. The description logic $\mathcal{ELI}$ that we consider here has been shown to be \emph{finitely controllable} \cite{Barany2013querying}, meaning that both definitions are equivalent. For more expressive description logics, this is in general not the case. \begin{table} \[\begin{array}{l@{~~~~~}l@{~~~}l} & \text{Example} & \text{First-order logic translation} \\[1mm] \text{ABox:} & \mathcal{A} = \{ P(a), r(a,b) \} \\ \text{TBox:} & \mathcal{T} = \{ P \sqsubseteq Q\sqcap \exists r.P\} & \mathcal{T}^\text{fo} = \{\forall x(P(x)\to Q(x)\land \exists y(r(x,y)\land P(y))\} \\ \text{Concept expr:} & C = \exists r.Q & q_{C}(x) = \exists y(r(x,y)\land Q(y)) \end{array}\] \caption{Example description logic ABox, TBox and concept expression} \label{tab:example-dl} \end{table} \begin{example} Consider the ABox, TBox, and concept expression in Table~\ref{tab:example-dl}. Every model of $\mathcal{T}^\text{fo}$ containing the facts in $\mathcal{A}$ must contain also $r(a,c)$ and $Q(c)$ for some $c\in N_I$. It follows that $a\in \text{certain}(C,\mathcal{A},\mathcal{T})$. In other words, $(\mathcal{A},a)$ is a positive QA-example for $C$ relative to $\mathcal{T}$. On the other hand, $(\mathcal{A},b)$ is a negative QA-example for $C$ relative to $\mathcal{T}$. \end{example} See~\cite{Baader2017:introduction} for more details on description logic syntax and semantics. We now explain how our results from Section~\ref{sec:characterizations} and~\ref{sec:learning} can be applied here. Although a QA-example is just a data example with one distinguished element, over the correspondence schema, the definition of \emph{positive}/\emph{negative} QA-examples diverges from the definition of positive/negative data examples, because of the TBox $\mathcal{T}$. For the special case where $\mathcal{T}=\emptyset$, the two coincide: \begin{lemma} \label{lem:qa-examples} Let $\mathcal{T}=\emptyset$. A QA-example $(\mathcal{A},a)$ is a positive (negative) QA-example for a concept expression $C$ relative to $\mathcal{T}$ iff $(\mathcal{A},a)$ is a positive (negative) data example for $q_C(x)$. \end{lemma} Lemma~\ref{lem:qa-examples} follows from the well-known monotonicity property of CQs (i.e., whenever $A\subseteq B$, then $q(A)\subseteq q(B)$), which implies that $\text{certain}(C,\mathcal{A},\emptyset) = q_{C}(\mathcal{A})$. Concept expressions turn out to correspond precisely to unary, acyclic, c-connected CQs: \begin{lemma} \label{lem:dl-acyclic} The standard translation $q_C(x)$ of every $\mathcal{ELI}$ concept expression $C$ is equivalent to a not-necessarily-safe unary CQ that is acyclic and c-connected. Conversely, every unary, acyclic, c-connected not-necessarily-safe CQ over the correspondence schema is logically equivalent to $q_C(x)$ for some $\mathcal{ELI}$ concept expression $C$. \end{lemma} Both directions of Lemma~\ref{lem:dl-acyclic} can be proved using a straightforward induction. The above two lemmas, together with Theorem~\ref{thm:characterizations-main}(2) and Theorem~\ref{th:membership} (cf.~Remark~\ref{rem:unsafe} and Remark~\ref{rem:learning-unsafe}) immediately yield our main result here. We say that a collection of positive and engative QA-examples \emph{uniquely characterizes} a concept expression $C$ relative to a TBox $\mathcal{T}$ if $C$ fits the examples (relative to $\mathcal{T}$) and every other concept expression that does so is equivalent (relative to $\mathcal{T}$) to $C$. By a \emph{QA-membership query} we mean an oracle query consisting of a QA example, where the oracle answers yes or no depending on whether the input is a positive QA example or a negative QA example for the goal concept, relative to the TBox. It is assumed that the TBox is fixed and known to the learner. \begin{theorem}\label{thm:dl-main} Let $\mathcal{T}=\emptyset$. Every $\mathcal{ELI}$ concept expression is uniquely characterizable by a finite collection of positive and negative QA examples (relative to $\mathcal{T}$), which can be computed in polynomial time. Furthermore, the class of $\mathcal{ELI}$ concept expressions is efficiently exactly learnable with QA-membership queries. \end{theorem} Moreover, by Theorem~\ref{thm:characterizations-main}(3), the uniquely characterizing examples can be constructed so that each example $(\mathcal{A},a)$ is the canonical QA-example of a concept expression. By the \emph{canonical QA-example} of a concept expression $C$, here, we mean the QA-example that (viewed as a structure with one distinguished element) is the canonical structure of the not-necessarily-safe CQ $q_C(x)$. Theorem~\ref{thm:dl-main} remains true when the concept language is extended with unrestricted existential quantification (of the form $\exists.C$) and a restricted form of the \textbf{I}-\textbf{me} self-reference construct introduced in~\cite{Marx2002narcissists}, namely where the $\textbf{I}$ operator can only occur once, and in the very front of the concept expression. Indeed, it can be shown that this extended concept language (by a straightforward extension of the standard translation) captures precisely the class of c-acyclic unary not-necessarily-safe CQs over the correspondence schema. \begin{openquestion} Does Theorem~\ref{thm:dl-main} holds true for arbitrary TBoxes? \end{openquestion} Results in~\cite{lutz2016data} imply that $\text{certain}(C,\cdot,\mathcal{T})$ can be expressed in a fragment of monadic Datalog. More precisely, for each $\mathcal{ELI}$ concept expression $C$ and TBox $\mathcal{T}$, there is a monadic Datalog program $\Pi$ that, such that, for every ABox $\mathcal{A}$, $\text{certain}(C,\mathcal{A},\mathcal{T}) = \Pi(\mathcal{A})$. Moreover, the left-hand side of every Datalog rule of $\Pi$ is an acyclic, c-connected (unary) CQ. The above question, therefore, may perhaps be approached by studying unique characterizability and exact learnability for a class of acyclic, c-connected monadic Datalog programs. \footnote{In a recent manuscript~\cite{Lutz2020manuscript}, a positive answer is given to a weaker variant of the question, namely for the description logic $\mathcal{EL}$, when the learning algorithm is also allowed to ask equivalence queries. } \bibliographystyle{plainurl}
{'timestamp': '2021-09-07T02:06:23', 'yymm': '2008', 'arxiv_id': '2008.06824', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06824'}
arxiv
\section{Introduction} Although it has been over two decades since its inception as an open standard, the OpenPGP (Pretty Good Privacy) standard is still widely deployed despite issues with usability, key management, and numerous attacks. The most recent process of standardization of OpenPGP at the IETF (Internet Engineering Task Force) started in 2015 and ended in November 2017, but did not attempt to address these underlying issues, instead focusing on upgrading the core primitives to use modern cryptographic primitives -- a task which even the IETF standards process could not fully fix. After years of unsuccessful attempts to address PGP problems trying to make PGP more functional via new advanced server-side architecture~\cite{leap} and Working Group activities at the IETF, a number of OpenPGP client developers created a new community effort called ``Autocrypt'' to address the underlying usability and key management issues. This effort also introduces new attacks and does not address some of the underlying cryptographic problems in PGP, problems that have been addressed in more modern protocol designs like Signal or IETF Message Layer Security (MLS). After decades of work, why can't the OpenPGP standard be fixed? First, we start with the history of standardization of OpenPGP in Section~\ref{pgp:standards}. We consider the PGP protocol itself according to the modern understanding of cryptography in Section~\ref{pgp:protocol}, inspecting whether some original design choices still make sense in terms of the security and privacy properties a user would expect. Then we move to summarizing the numerous attacks on PGP that the design and incomplete standardization of PGP opens up in Section~\ref{pgp:attacks}. Note that there has been a large body of usability work on PGP, mostly with negative results and a large number of attacks based purely on usability problems, that we will only briefly overview as our primary focus in on standardization and protocol issues with PGP~\cite{johnny}. Lastly, we analyze the failed attempts to fix these issues via standardization in Section~\ref{pgp:failed}, including informal community-driven approaches like Autocrypt. Given the plethora of issues that exist with PGP, we analyze whether or not OpenPGP as a standard should continue at the IETF, given the underlying problem is a lack of a decentralized public key infrastructure in Section~\ref{conclusion}. \section{Standardization of OpenPGP} \label{pgp:standards} Pretty Good Privacy (PGP) is a well-known cryptographic protocol for using asymmetric cryptography to provision confidentiality to the masses. At the very time when the U.S. government was attempting to restrict the spread of ``strong'' encryption in what was known as the first ``Crypto Wars,'' the release of PGP's open source code made it seemingly impossible to control the spread of tools for encryption~\cite{singh1999code}. The original scheme of PGP (``PGP 1.0'') was written by Philip Zimmerman, a peace activist, with its source code published on the Internet in 1991, first to a ISP called PeaceNet and then to Usenet. The goal was encrypting email, based on the plaintext Simple Mail Transfer Protocol (SMTP). As PGP depended on RSA primitives for public key encryption and signatures, PGP attracted the attention of the company RSA Security Inc., which had patented the original RSA algorithms -- and even the United States government, which attempted to prosecute Zimmerman on breaking an encryption ban on ``strong'' cryptography by posting the source code internationally. Turning PGP into a standard at the IETF both helped prevent a single company from preventing its further spread via patent claims by providing a version that did not use RSA (thus the standard was called ``OpenPGP'') and served as a strategic bulwark against further repression by weaving encryption into the open standards that defined the Internet itself.\footnote{Much of the history of PGP and its standardization has been summarized from various mailing lists on \emph{ietf.org}.} Although Ron Rivest and others at MIT convinced RSA Security Inc. not to pursue any further patent actions and the United States government dropped their court case against Zimmerman in January 1996, Phil Zimmerman submitted an informational (non-standard) RFC 1991 called ``PGP Message Exchange Formats''\footnote{\url{https://tools.ietf.org/html/rfc1991}} to the IETF in August 1996, describing various minor versions of ``PGP 2.0.'' Importantly, this document divided the actual encrypted message into separate variable length ``packets,'' where each packet contained a header specifying its type (``tag'') and a packet body. These packets may contain encrypted keys, encrypted messages, signatures, certificates, and so on. RFC 1991 featured not only RSA, but also the patented IDEA algorithm\footnote{\url{https://register.epo.org/application?number=EP91908542}} and MD5 for hash functions.\footnote{Although these may seem questionable choices today given various known attacks on IDEA and MD5, it should be remembered that cryptography was generally not standardized at the time with both IDEA and MD5 considered secure. Zimmerman replaced his own broken cipher Bass-o-matic in PGP 1.0 with IDEA after the release of PGP.} In order to harmonize with email standards, OpenPGP was made compatible with Multi-purpose Internet Mail Extensions (MIME)\footnote{The IETF standard for sending messages with multiple components (such as a digital signature and a body as specified in IETF RFC 1521 \url{https://tools.ietf.org/html/rfc1521}} via IETF RFC 2015 ``MIME Security with Pretty Good Privacy.''\footnote{\url{https://tools.ietf.org/html/rfc2015}} While OpenPGP-encrypted email was originally delivered simply as encrypted and signed plaintext in the OpenPGP Message format using standard SMTP, email best practices mandated some parts be delivered as multi-part MIME messages. In MIME messages, the content of the message is divided between different MIME parts, so that the encrypted body is delivered as a separate MIME part than the signature or attached keys. The year after the original submission by Zimmerman, the original IETF OpenPGP Working Group opened in September 1997. Within a year the OpenPGP produced IETF RFC 2440 in 1998\footnote{\url{https://tools.ietf.org/html/rfc2440}} on ``the OpenPGP Message Format.''\footnote{Confusingly, this standard described PGP 5.0, because the rights to PGP 4.0 (and all even numbered versions of PGP) was bought by Viacrypt (which became PGP Incorporated), PGP 3.0 evolved PGP 5.0 as Zimmerman held the rights to odd numbered PGP versions.} This document also described certificates, identities, and in more detail the operations necessary for signing, encryption, and decryption of data with OpenPGP. In particular, it expanded the ciphersuite choice by making mandatory the patent-free El-Gamal for asymmetric encryption, SHA-1 for hash functions, DSA for signatures, and 3DES for symmetric encryption. It also ended up recommending CAST-128, with an infamous 128 bit key and the weak S2K (String-to-Key) KDF for converting plaintext passwords to keys. MIME usage was also updated in 2001 as RFC 3156 ``MIME Security with Open PGP.''\footnote{\url{https://tools.ietf.org/html/rfc3156}} The OpenPGP Working Group was then closed. Due to advances in cryptography and attacks detailed in Section~\ref{pgp:attacks}, the IETF reopened the OpenPGP Working Group in May 2003. Four years later RFC 2440 was updated by the Working Group as IETF RFC 4880 in 2007.\footnote{\url{https://tools.ietf.org/html/rfc4880}} The primary change was the addition of PKCS1-v1\_5 encoding and the optional use of a modified version of AES-CFB mode for symmetric encryption with the addition of Modification Detection Codes (MDCs) to provide a limited form of integrity to symmetric encryption. In brief, an MDC attempts to alert the recipient if their message has been corrupted by attaching an encrypted SHA-1 hash of the plaintext as the last packet in a message. Also, MD5 was deprecated and IDEA made optional. The OpenPGP Working Group was again closed in 2008, but the mailing list continued to be somewhat active, with PGP able to work with most major operating systems, including eventually Microsoft Outlook, Apple Mail, Mozilla Thunderbird, and others. The majority of PGP implementations eventually ended up depending on the GNU Privacy Guard (GPG) library.\footnote{https://gnupg.org/} Although the cryptographic primitive choices seems questionable today and many options were given, it should be remembered that OpenPGP was built during a period when cryptographic standardization was just starting, and so simply including every plausible algorithm seemed to make sense given the security level of many algorithms was unknown. Also, cryptographic protocol design was also in its infancy, and so the PGP protocol itself is historic as an initial, if ad-hoc, ``real world'' open source cryptographic deployment. \section{PGP Protocol Design} \label{pgp:protocol} \subsection{Basic PGP Protocol} The core design of PGP is more than two decades old, and despite outstanding usability and key management issues, PGP is still used for encryption and signatures, although it does not have clear formal security properties and assumptions. The PGP protocol can encrypt and sign a plaintext message $m$. This requires the sender having a private asymmetric key $sk$ and the recipient public key $pk$ \begin{enumerate} \item A signature $\sigma_m = SIGN(sk, m)$ is created with the key $sk$ . \item By default, $m$ is compressed to $m'$. The compressed message $m'$ is concatenated with the signature of its uncompressed version, $\sigma_m$. \item A fresh new symmetric key $k$ is generated and encrypts the message such that the ciphertext $c_m = E(k, m' | \sigma_m)$. \item This symmetric key $k$ is encrypted with $pk$ so $c_k = E(pk, k)$. \item The resulting encrypted message $c$ is the concatenation of the encrypted symmetric key and ciphertext, i.e. $c = c_k | c_m$. \end{enumerate} The creation of a fresh random symmetric key $k$ in order to encrypt the actual plaintext message later became best practice. By the generation of the randomized symmetric key per message, PGP achieves probabilistic encryption for the message itself; each encryption of the same plaintext results in an unlinkable new ciphertext even if a deterministic encryption scheme is used. Speed is also achieved by depending primarily on symmetric encryption. The original message that is symmetrically encrypted is unbounded in length, while the symmetric key $k$ always the same size and so can be asymmetrically encrypted relatively quickly. Lastly, PGP allows group messages as used in email efficiently, as the same encrypted message $c_m$ can simply be sent with different $c_k$ for the new public key $pk$ of each recipient, so the plaintext is not encrypted multiple times. \subsection{Design Issues in OpenPGP} \label{pgp:design} Nonetheless, PGP does make some design choices that simply do not make sense in terms of modern cryptographic protocol design, regardless of the primitives used or efficiency gains. The highlights of the fundamental problems are given below. \subsection{Message Compression} Hiding the length of a plaintext message is not typically a security property but a privacy property, and so many protocols do not defend against attacks on the length of the ciphertext, including PGP. Furthermore, when standards like OpenPGP and TLS 1.2 were created, due to bandwidth considerations the cleartext was often compressed. What was not known at the time was that message compression can lead to attacks on encrypted data as information about plaintext entropy can gained from the information leaked by the compressed length~\cite{kelsey}, and so compression is no longer used in standards like TLS. Compression attacks work by virtue of repeated transmission of (nearly) the same message with only slight modifications by the attacker, and having those messages cause a response to be returned that includes the encrypted value that the attacker wants to find in a part of the message that is not controlled by the attacker. In practice rate-limiting can prevent this attack (unlike in TLS) and the kinds of secrets it would likely be able to find are limited -- the attack does not lead to a decryption of the content of the message, but could allow an attacker to guess authentication tokens or secret links like ``unsubscribe'' in parts of messages. When OpenPGP-level compression is explicitly disabled, applications for which the plaintext length is sensitive should implement some application-specific padding scheme in order to disguise the length of the plaintext. These sorts of techniques are already used by packet formats such as the Sphinx format for mix networking so that all messages have uniform length~\cite{danezis2009sphinx}. This can be done in a more lightweight manner for OpenPGP by simply adding (even randomized) padding to the uncompressed message. Currently, OpenPGP also does not encrypt the sender and other information not needed for message routing, and proposals like PURBs manage to hide all fields not needed for routing and the length of messages~\cite{nikitin2019reducing}. \subsection{Sign-then-encrypt} The second issue is that OpenPGP itself functions as a library that allows any use of encryption and signing as API calls. For example, many users do not sign any messages at all as they believe these signatures may leak metadata about them. By default, strangely OpenPGP uses a sign-then-encrypt scheme so the recipient of the message is not authenticated, only the sender. Therefore even when a message is signed, sign-then-encrypt allows surreptitious forwarding attacks~\cite{davis}, where the legitimate recipient of a message signed by the sender can re-encrypt the message to an unlimited number of arbitrary recipients of their choice -- while the original signature of the sender remains valid! This likely violates a user's expectation both about how messages and signatures work. These ``spoofing'' attacks that alter messages en route between email providers both easily possible although surprisingly not widespread outside of spam, and could target OpenPGP-encrypted messages~\cite{hu2018end}. To concretely illustrate, imagine that Bob sends the signed message ``I love you'' to Alice using OpenPGP encryption. Alice can decrypt the message, re-encrypt it and send it to Carol. Carol may obviously misinterpret the message as a statement that Bob loves her, not Alice - and the cryptographic assurances of the digital signature are violated. Alice can even make it seem that the message came directly from Bob to Carol. While not devastating, this attack could lead to very surprising results, particularly in terms of encrypted group messaging where it would allow anyone to arbitrarily expand the group while the ``appearance'' of encryption and digital signatures would remain the same to the original members. This problem of a lack of clear signing authority over a given message can also lead to many attacks on the difficulty of determining the authority behind the signer or which particular message has a particular signer in multi-part and nested messages, a situation exacerbated by PGP's unlimited nesting of signed messages~\cite{fired}. \subsection{Unauthenticated Headers} Not only can signatures be stolen, but all SMTP headers are unauthenticated by OpenPGP. Indeed, the surreptitious forwarding attack is made even easier due to this underlying issue~\cite{muller2019re}. For example, the \emph{From:} header specifies the sender and this identity should match the identity of the OpenPGP identifier of the sender in the signature, yet this is not done. In practice, DomainKeys Identified Mail (DKIM) enabled mail providers and even mail agents agents can already match the identity of DKIM email signature with the \emph{From:} field value, and display a warning if a mismatch is found from the originating domain.\footnote{\url{https://tools.ietf.org/html/rfc6376}} Unfortunately, not all MUAs perform this check~\cite{liao}, leaving some users exposed to impersonation attacks. Regardless, it is only the sender's domain, not the user, that is checked by DKIM. So, an impersonation attack that replaces \emph{[email protected]} with \emph{[email protected]} would work even with DKIM-certified mail. The \emph{Subject:} field is also sensitive and can be tampered with. A few encrypted email agents have began removing subjects by default and replacing them with strings such as ``...'' and putting the header in the body using a technique called ``memory hole.''\footnote{\url{https://0xacab.org/leap/pymemoryhole}} Lastly, altering the \emph{Reply-To:} field could allow an adversary to redirect the response to an inbox of their choosing, and email users may be unaware that emails do not return to the address in the \emph{From:} field automatically. Historically this field can be used to respond to mailing lists and current encrypted mailing list software like Schleuder\footnote{\url{https://schleuder.org/}} use a trusted third-party server to manage a single long-term RSA keypair for the mailing list, and this field could be tampered with in order to prevent messages from returning to the correct mailing list even if encryption is used. These are only the most abstract design issues with PGP. There are even more problems with PGP on a less fundamental level. For example, the use of MDC codes being attached at the end of a message allows them to be easily stripped by an attacker. Worse, it also prevents large files from being streamed with PGP, as the MDC is checked only at the end of the file. How these design flaws play out in terms of concrete attacks is shown in the next section. \section{Attacks on PGP} \label{pgp:attacks} \subsection{Protocol Attacks} Even without directly attacking the known broken cryptographic primitives supported by OpenPGP due to ``backwards compatibility,'' there have been a number of attacks on PGP's cryptographic foundations. For example, one of the earliest academically published attacks was to use a chosen ciphertext attack, where an adversary would send an encrypted message that could not be decrypted and then the user would respond, quoting the ciphertext sent by the adversary in the response~\cite{katz2000chosen}. This would allow the adversary to know if their ciphertext could be decrypted or not, which would eventually lead to the breaking of the encryption itself, which was shown to be the case in early versions of OpenPGP-compliant software~\cite{jallad2002}. Another attack was done on the PGP's changes to AES-CFB mode (i.e. ``PGP-CFB'' mode) that were made partially in response to the previous attack~\cite{jallad2002}. PGP could leak significant bits of the plaintext via an attack that takes advantage of a idiosyncratic ``quick check'' for session key correctness added to PGP-CFB mode, although the attack works only if timing attacks can be exploited quickly, so ``quick check'' bytes are simply not checked in newer implementations~\cite{mister2005attack}. Although RSA PKCS \#1 v1.5 padding was mandated for the RSA keys in OpenPGP, the more recent IETF RFC also mandated that the errors in key processing return the same error the clients as decryption errors, so surprisingly it appears all modern PGP clients are not vulnerable to Bleichenbacher's attack~\cite{fired}. \subsection{Client Attacks} The usage of complex MIME types has been the source of more recent attacks on the modern OpenPGP standard. The problem is email clients handle the PGP MIME types differently, with some clients allowing the handling of rich HTML content with Javascript and CSS for messages. As HTML content with Javasript allows the insertion of arbitrary remote content without proper security boundaries (which many email clients do not enforce), the ``eFail'' attack allowed PGP messages to have their plaintext content captured and sent to an adversary operating a remote server via wrapping the ciphertext in a MIME part controlled by an adversary and also taking advantage of problems caused by compression~\cite{efail}. This attack took advantage of a failed MDC code to reveal the plaintext of a message. This was not due to a failure in the standard, clients implementing the standard correctly, namely the suggestion of RFC 4880 that in the case of a failed MDC that an ``implementation[s] MAY allow the user access to the erroneous data'' with a warning. The lack of authentication in the PGP protocol leads to real-world surreptitious forwarding attacks that take advantage of the poor usability and conflicting client behavior in OpenPGP-compatible clients. In general, these attacks cause a user to mistakenly believe a PGP message that has a detached signature (of an ``Encrypt-then-Sign'') in a separate MIME part to appear to be a valid signature for in an entirely different MIME part in some clients~\cite{fired}. For example, an adversary can take a valid encrypted message with a signature attached via MIME, strip the original signature, and simply insert their own signature MIME part, forwarding the entire PGP/MIME message to their victim whose client UI mistakenly shows the attacker's signature as valid for the original message. These attacks are not confined to PGP/MIME processing, but also can happen with inline PGP signatures that do not use MIME types but embed the signature directly in the text of an email without a MIME separation of content due to the earlier issues on ``sign-then-encrypt'' combined with unlimited signature nesting. Until 2007 arbitrary unsigned data could be injected into to a message with an inline signature and the entire message would validate as signed in PGP~\cite{fired}. In inline messages, content at the beginning of a message could be changed without invalidating the signature.~\footnote{\url{https://dkg.fifthhorseman.net/notes/inline-pgp-harmful/}} \subsection{Key Management Attacks} The lack of well-specified key management in OpenPGP has also led to numerous attacks on the common ``folk practice'' used in OpenPGP for key management. Keys in PGP are usually not transmitted as the raw bytes of the key itself, but via a PGP certificate as specified that matches each key to a User ID, a string that may contain an email address. The PGP key certificate is for a signing key that then self-signs the entire certificate, verifying the binding between the User ID and one or more keys. Also for each key there is a key ID (a truncated number of bits of the public key), PGP version number, a revocation status, and possibly expiration date as well as a host of optional fields such as an (often unused) field for the preferred key server. Each PGP certificate for a key may contain multiple sub-keys, which are full-fledged keys in their own right used for either encryption or signing, where the signature of a key also applies to a subkey of that key. Soon after PGP itself was launched by Zimmerman, a key server\footnote{\url{https://pgp.mit.edu}} was launched at MIT by Brian LaMacchia to allow the discovery of keys via lookup via User IDs and Key IDs. There were three critical flaws with key servers, whose operations were never standardized. First, there is no requirement that Key IDs and User IDs be unique, so attacks such as the ``Evil 32'' attack showed that practical collusion were possible with 32 bit Key IDs in 4 seconds.\footnote{\url{https://evil32.com/}} More dangerously, there was no authentication used by key servers, so anyone could upload a key to any key server claiming to be anyone. HTTP Key Server (HKS) allows the maintenance of keys,\footnote{\url{https://tools.ietf.org/html/draft-shaw-openpgp-hkp-00}} and keys servers can share keys using Synchronized Key Servers (SKS).\footnote{\url{https://sks-keyservers.net/}} As key servers allowed the updating of keys, anyone could update a key belonging to anyone else. In 2019, two OpenPGP designers were attacked by a ``certificate flooding'' attack where an adversary maliciously added a large amount of keys to the key certificates of a user on one or more key servers, effectively rendering the certificates incapable of being processed.\footnote{\url{https://access.redhat.com/articles/4264021}} Lastly, key verification is in theory done via a ``Web of Trust'' with multiple trust levels (unknown, none, marginal, full, and ultimate) that are interpreted by users differently, and the ``Web of Trust'' forms a ``small world'' network that essentially leads to the same kinds of trust as a centralized PKI.\footnote{\url{https://pgp.cs.uu.nl/plot/}} User key material on key servers, including their social graph of ``trust,'' is completely public and so reveals the personal data of everyone's web of trust, which seems against any privacy properties. \section{Autocrypt: Fixing PGP?} \label{pgp:failed} When there are well-known attacks on an IETF standard, such as the numerous attacks on TLS 1.2, the standard is usually upgraded by a rechartered IETF Working Group. However, many in the community and IETF did not think PGP needed upgrading as the majority of attacks outlined in Section~\ref{pgp:attacks} are not cryptographic attacks on PGP itself, but primarily due to OpenPGP's interaction with a wider and mostly under-specified infrastructure such as email clients and key servers. An attempt to provide a list of sensible changes to address problems with PGP, such as using AES-GCM or ChaCha20 with Poly1305 for symmetric encryption, as well as improve the metadata properties of the OpenPGP format, were given the ``Modernizing the OpenPGP Message Format'' draft.\footnote{\url{https://tools.ietf.org/html/draft-ford-openpgp-format-00}} The OpenPGP Working Group was re-opened for a third time in 2015, and the IETF restricted its charter to updating the primitives to use modern elliptic curve cryptography and AEAD encryption for the underlying encrypted data that were at the time protected by the SHA1-based MDC.\footnote{Earlier in 2012, NIST curve compatibility as given by IETF RFC 6637: \url{https://tools.ietf.org/html/rfc6637}} Although there were drafts to add EdDSA for signatures\footnote{\url{https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04}} and a revised RFC4880bis that used Curve 25519 as well as AEAD ciphersuites,\footnote{\url{https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07}} the OpenPGP Working Group at the IETF was closed in November due to lack of community involvement and review of the proposed standard. The mailing list and updates to RFC4880bis are still active, but this community has no mandate by the IETF to create an official standard. The previous co-chairs of the Working Group have suggested if energy could be found to finalize RFC 4880bis that the OpenPGP Working Group could be re-chartered.\footnote{Personal communication, Barry Leiba, former IETF OpenPGP Working Group chair.} Attacks on key servers and PGP certificates would require updating the PGP certificate part of RFC 4880bis as well as specifying how key servers work. Non-standardized guidance has been presented to prevent these attacks that pre-dated the attacks themselves, but the document runs over fifty pages, pointing to the seemingly impossible security and privacy issues with existing PGP key servers.\footnote{\url{https://tools.ietf.org/html/draft-dkg-openpgp-abuse-resistant-keystore-03}} The OpenPGP Working Group drafted a proposed key server draft at the IETF which verified keys uploaded via TLS by sending an encrypted nonce from the key server to the user's email and receiving the signed nonce in a reply email but there have been no implementations.\footnote{\url{https://tools.ietf.org/html/draft-koch-openpgp-webkey-service-08}} A number of ambitious projects were initiated to fix the flaws in key discovery and management in PGP like Pretty Easy Privacy,\footnote{\url{https://tools.ietf.org/id/draft-marques-pep-email-02.html}} and the Leap Encryption Access Project (LEAP) to automate key discovery by relying on a federation of email servers~\cite{leap}. These approaches were not deployed as existing email servers did not wish to upgrade their existing server-side infrastructure to handle key management. The goal of new \emph{Autocrypt} community effort is to allow keys to be transmitted not via OpenPGP keyservers, but via the emails themselves.\footnote{\url{https://autocrypt.org/}} Emails should default to encrypted where possible, and so it is better to be confidential ``most of the time'' rather than not. This requires ``Trust on First Use'' (TOFU) messages that, while defaulting to cleartext, attempt to upgrade to encryption as soon as possible in the flow of the protocol. Autocrypt does not alter the cryptographic constructions or primitives, but instead adds Autocrypt-specific mail headers in email clients that are backwards compatible with all OpenPGP clients and do not cause email users who do not use OpenPGP to become aware of encryption. Email users who do not use OpenPGP are naturally confused by receiving an encrypted message or key material as an attachment using PGP/MIME, and users of encrypted email can receive messages they cannot open due to expired or incorrect keys being used. Autocrypt solves this problem as headers that are not understood by an existing mail client will just be dropped, and so not displayed to the user. Details are given in the Autocrypt specification 1.1.\footnote{\url{https://autocrypt.org/autocrypt-spec-1.1.0.pdf}} The Autocrypt community is not an official standard, but a ``bottom-up'' community-driven process led by email client developers. They released the first version of the ``Autocrypt Level 1'' specification in December 2017 (after the IETF closed the OpenPGP Working Group), which was updated to version 1.1 at the end of 2019. The primary change between version 1.0 and version 1.1 was the movement of the default from large RSA keys for signing and encryption to Ed25519 and Curve 25519 keys. Currently, a number of different OpenPGP-compliant clients also support Autocrypt, in particular Enigmail, K-9 mail, mutt, and eight other OpenPGP email clients. The core problem with Autocrypt is that it does not address the underlying problems with lack of authentication in PGP, and so suffers from the same attacks on SMTP message spoofing due to unauthenticated headers. In particular, an attacker can spoof both the initial Autocrypt headers by creating an impersonated email header and force an Autocrypt-enabled client to insert the attacker's key in their keystore for an arbitrary contact. Due to Autocrypt's key updating mechanism, an attacker can simply replay this attack via faking unauthenticated headers to replace a communication peer's key with an attacker's key or gossip incorrect new keys for users. Given the promotion of Autocrypt usage via security messaging using PGP with Delta.chat in places like Russia and Ukraine, these problems may become serious.\footnote{\url{https://delta.chat}} The danger is that users believe their messages are confidential and even authenticated, when they are indeed not~\cite{halpin}. Although the alternatives like Signal are centralized, they are likely more secure and inline with user expectations. Opportunistic encryption does simply not provide the certainty needed by many users about their communication. \section{Conclusion: Can PGP be fixed?} \label{conclusion} The question facing users, developers, and security researchers is whether PGP should be considered harmful and thus deprecated from common usage and future standardization. As we have shown, many of the problems with PGP come from its lack of an authenticated encryption with additional data construction (AEAD)~\cite{aead}. A number of recommendations have been made on the level of the OpenPGP itself: \begin{itemize} \item Removing compression, as it is no longer needed due to the increased capacity of the internet and the only reason for keeping it, a chosen ciphertext attack, is prevented by the use of an AEAD symmetric ciphers like ChaCha20-Poly1305 and even MDCs. \item Moving to modern elliptic curve cryptography for signing and public-key encryption and AEAD for symmetric encryption, as specified in the defunct 2015 OpenPGP charter. \item As MDCs are redundant if the message is signed or an AEAD ciper is used, as well as being hard-coded to be based on SHA1 and even lead to attacks~\cite{mister2005attack}, MDCs should be removed when a modern AEAD scheme is used for symmetric encryption. \item Use AEAD not only on the OpenPGP message format, but email itself, with routing specific headers like \emph{From:, To:}, and \emph{Reply-To:} given integrity. \end{itemize} Yet as pointed out, the protocol itself is so flawed in terms of design (such as lacking forward secrecy~\cite{otr}\footnote{Although there have been attempts to add forward secrecy to OpenPGP such as \url{https://tools.ietf.org/html/draft-brown-pgp-pfs-03}}), it seems impossible to fix without breaking backwards compatibility and compatibility with email and MIME (in order to support AEAD natively). One option is simply to abandon fixing PGP and start from a cleaner design that natively supports modern cryptography and a per-message AEAD construction. In 2018, the IETF convened a new Working Group, Message Layer Security (MLS) to design an IETF standardized AEAD group messaging protocol that could scale to large groups, a problem the unstandardized Signal Protocol is unable to tackle due to its design.\footnote{\url{https://datatracker.ietf.org/wg/mls/about/}} Would it make sense to drop fixing OpenPGP for messaging entirely and concentrate only on MLS and usability in encrypted messaging? Perhaps, but let's not forget the larger picture: Technically, decentralized public key infrastructure is an open research problem, both in terms of cryptography and usability. The usability of keys as identifiers is \emph{the} root usability problem of PGP, and without a breakthrough, new standards will not fix this unless keys are managed on behalf of the user -- which goes against the values of decentralization and user control. Simply deprecating OpenPGP without further work misses the real reason why there are still many supporters of OpenPGP for encryption in the developer community: OpenPGP is viewed as open and decentralized as opposed to current fragmented secure messaging applications. Decentralized key management would be needed for authentication in a decentralized environment, and a lack of this infrastructure explains the lack of usage of an AEAD construction in OpenPGP. There has been considerable work on privacy-preserving and authenticated centralized key-servers for generic key material, such as CONIKS~\cite{melara2015coniks} and its implementation in Key Transparency.~\footnote{\url{https://github.com/google/keytransparency}} Although Key Transparency was originally going to be used for OpenPGP-compatible email between Google and Yahoo, the project was discontinued. Inspired by decentralized blockchain technology, ClaimChain presents a decentralized, gossip-based alternative to centralized key management without key servers with privacy~\cite{claimchain}. Autocrypt has already supported the sending of communication peer keys via gossip protocols.\footnote{\url{https://countermitm.readthedocs.io/en/latest/}} Decentralization via gossip has its drawbacks; the approach using a real-world data-set and could reach consensus only on 66\% of users in terms of key discovery~\cite{claimchain}. Further work on automated key discovery and access control based on decentralization, such as the nearly forgotten Simple Public Key Infrastructure standards\footnote{\url{https://tools.ietf.org/wg/spki/}} based on SDSI~\cite{sdsi}, could create more robust and privacy-preserving decentralized key management solutions. The real problem standards bodies can't fix PGP is not due to the legacy ciphersuites or even protocol details, but the hard problem of key decentralized management. \begin{acks} Harry Halpin was funded in part by the European Commission H2020 through the NEXTLEAP Project (Grant No. 6882). He would like to thank Alfredo Pironti for his talk to the NEXTLEAP project members at IMDEA in March 2017 on PGP and then sharing his draft article ``Reconciling actual and expected security in OpenPGP,'' which inspired Section~\ref{pgp:protocol}, and looks forward for Pironti developing his work further. He would also like to thank Holger Krekel, Barry Leiba, and Daniel Kahn Gilmor for discussions on PGP and Autocrypt, although they may not agree with the conclusions given in this paper. \end{acks} \bibliographystyle{plain}
{'timestamp': '2020-08-18T02:17:53', 'yymm': '2008', 'arxiv_id': '2008.06913', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06913'}
arxiv
\section{Generating the High-fidelity Model} \label{section:actLearn} \vspace{-0.05in} To build the high-fidelity model, CEAL first creates a sample pool $C_{\R{pool}}$ by selecting configurations randomly from the workflow's configuration space $C$. All configurations used subsequently to train the high-fidelity model are selected from $C_{\R{pool}}$. As we evolve the model, we repeatedly evaluate and rank all configurations remaining in $C_{\R{pool}}$; thus, we want $|C_{\R{pool}}| \ll |C|$ to keep evaluation costs manageable. However, we also want $C_{\R{pool}}$ to be reasonably representative of $C$ and, in particular, to contain enough well-performing configurations to train a good high-fidelity model. Say that we want the best configuration in $C_{\R{pool}}$ to be in the top 1/$n$ of all configurations, with probability $P$. With a pool size $p$, the chance of selecting $p$ configurations each not in the top 1/$n$ is less than $(1-1/n)^p$. Thus, we want $p \approx -n\cdot \ln (1-P)$, because $P > 1-(1-1/n)^p = 1-[(1-1/n)^n]^{p/n} > 1-(1/e)^{p/n}$. For example, if 1/$n$ = 1/500 = 0.2\% and $P$~=~98.2\%, then $p\approx$ 2000. To establish the high-fidelity model, CEAL selects $m_{0}$ configurations at random from $C_{\R{pool}}$; selects the $m_{B}$ best of the configurations remaining in $C_{\R{pool}}$, based on scores from the low-fidelity model; runs the workflow with the $m_0+m_{B}$ selected configurations; and uses the results as samples to train an initial high-fidelity model. We discuss the factors influencing the choice of $m_{B}$ and $m_{0}$ below. To evolve the model, CEAL evaluates the configurations remaining in $C_{\R{pool}}$ and selects the $m_{B}$ highest-scoring. % Then, it runs the workflow with those configurations and uses those results to train the high-fidelity model further. It repeats these operations until the cost budget is reached. The high-fidelity model is initially primitive and thus the low-fidelity model is a superior choice for evaluating configurations. As more training data are acquired, the high-fidelity model eventually outperforms the low-fidelity model. Thus, we monitor the capability of the high-fidelity model in evaluating configurations, and substitute it for the low-fidelity model when it becomes a better choice. Specifically, each time that we perform more runs, we use the new data to compute the top-1, top-2, and top-3 recalls (see \S\ref{section:recallScore}) of the low- and high-fidelity models: that is, the extent to which their best 1, 2, and 3 configurations, respectively, match the best 1, 2, and 3 as determined by experiment. When these scores for the high-fidelity model (summed to increase stability) exceed the low-fidelity sum, we switch to the high-fidelity model. As we show quantitatively when we present experimental results in \S\ref{section:evaluation}, the power of the CEAL approach derives from the fact that it selects mostly top configurations when collecting data to train the high-fidelity model. The rationale here is this: our ultimate goal is a surrogate model that the searcher can use to find the best configurations, and for that purpose it should be highly accurate for good configurations, but can be less accurate for bad configurations. Thus, we prefer to use our limited sample budget for samples collected for high-performing configurations. (Focusing sample collection on high-performing configurations also has the useful side effect that these samples, by definition, take less time.) Thus, as described above, we use the low-fidelity model to bootstrap the sample selection process, and transition to the high-fidelity trained model as the number of samples grows. But what if our low-fidelity model is % biased in such a way that it never gives good scores to high-performing configurations? Then the high-fidelity model may never improve. This concern motivates us to select, in the first phase, $m_{0}$ random configurations as well as the $m_{B}$ configurations selected with the low-fidelity model. We discuss the sensitivity of CEAL to these hyper-parameters in \S\ref{section:hp}. \section{CEAL Algorithm} \label{section:algo} \vspace{-0.05in} The CEAL algorithm, \Algorithm{CEAL}, takes as input a data collection budget ($m$), expressed in terms of workflow runs for simplicity. (If a budget on real resource consumption is preferred, the algorithm can be adapted to monitor the resource consumption of the workflow and its component applications.) \MultiLines{cpntLoop}{estimate}, the low-fidelity model generation via component combination phase, run each component application $m_{\R{R}}$ times to test randomly selected configurations and build component models. The cost is equivalent to running the complete workflow $m_{\R{R}}$ times, incurring a charge of $m_{\R{R}}$ from budget $m$ (\Line{count}). If a component application has been tested earlier in other workflows, some configuration-performance data $D_j^{\R{hist}}$ can be reused to further improve component model quality (\Line{data}). In the case, $m_{\R{R}}$ should be close to 0. Otherwise, $m_{\R{R}}$ is generally set to be from $m \cdot 20\%$ to $m \cdot 70\%$. \begin{algorithm}[!t] \footnotesize \caption{\small % \B{C}omponent-based \B{E}nsemble \B{A}ctive \B{L}earning { \footnotesize \newline \B{Inputs:} Workflow runs budget $\bm{m}$; budget used to run component applications $\bm{m_{\B{\R{R}}}}$; for each component application $1 \le j \le J$, configuration space $\bm{C}_j$ and historical measured configuration-performance samples $\bm{D}_j^{\B{\R{hist}}}$; sample pool $\bm{C}_{\B{\R{pool}}}$; % % number of initial random samples $\bm{m_0}$; number of iterations $\bm{I}$. \newline \B{Output:} High-fidelity workflow model $\bm{M_{\R{H}}}$. } } \label{algorithm:CEAL} \begin{algorithmic}[1] \For {$j \in \{1, 2, \cdots, J\}$} \label{line:cpntLoop} \State Randomly select $m_{\R{R}}$ configurations from $C_j$ as $C_j^{\R{meas}}$; \label{line:srcRandSlct} % % \State Run $j$\textsuperscript{th} component with configurations in $C_j^{\R{meas}}$, giving $D_j^{\R{meas}}$; \label{line:srcMeas} % \State $D_j^{\R{meas}} \leftarrow D_j^{\R{meas}} \cup D_j^{\R{hist}}$; \label{line:data} \State Train component model $M_j^{\R{cpnt}}$ with $D_j^{\R{meas}}$ for the $j$\textsuperscript{th} application; \label{line:srcTrain} % \EndFor \State Generate low-fidelity model $M_{\R{L}}$ from component models and combination function (see \SL{combo}); \label{line:estimate} % \State Move $m_0$ randomly selected configurations from $C_{\R{pool}}$ to form $C_{\R{meas}}$; \label{line:tgtRandSlct} \State $m_B \leftarrow (m - m_0 - m_{\R{R}}) / I$; \label{line:count} \State Score all configurations in $C_{\R{pool}}$ with $M_{\R{L}}$; \label{line:m0_evaluate} \State Move top $m_B$ configurations from $C_{\R{pool}}$ into $C_{\R{meas}}$; \label{line:topSlct} \State $M \leftarrow M_{\R{L}}$; \ \ \ \ // Set the model used for evaluating configurations \State $M_{\R{H}} \leftarrow$ ML model (e.g., boosted tree~\cite{Chen:XGBoostScalTreeBoosSys:KDD16}); // Init high-fidelity model \label{line:initMdl} \For {$i \in \{1, \cdots, I\}$} \label{line:beginRefine} \State Run workflow for all configurations in $C_{\R{meas}}$, giving $D_{\R{meas}}$; \label{line:meas} % \If{$M = M_{\R{L}}$}\ \ \ \ // Begin model switch detection \label{line:detStart} % % % % \State // Score models: recalls for top 1, 2, 3 configurations \State $S_{\R{H}} = \sum_{i=1,2,3} S_r(i, C_{\R{meas}}, M_H, D_{\R{meas}}) $; \ \ // See \S\ref{section:recallScore} \State $S_{\R{L}} = \sum_{i=1,2,3} S_r(i, C_{\R{meas}}, M_L, D_{\R{meas}}) $; \ \ \ // See \S\ref{section:recallScore} % % % \State \textbf{if} $S_{\R{H}} \ge S_{\R{L}}\ \textbf{then}\ M \leftarrow M_{\R{H}}$ \textbf{endif}; \label{line:switch} % % \EndIf \ \ \ \ \ // End model switch detection \label{line:detEnd} \State Use $D_{\R{meas}}$ to train/refine $M_{\R{H}}$, and update $M$ if it switched to $M_{\R{H}}$; \label{line:tgtTrain} % \State Use $M$ to evaluate the configurations in $C_{\R{pool}}$; \State Move the top $m_B$ configurations from $C_{\R{pool}}$ to form $C_{\R{meas}}$ again; \label{line:tgtPred} \EndFor \label{line:endRefine} \State \Return $M_{\R{H}}$. \label{line:mdlGen} \end{algorithmic} \end{algorithm} The second phase, high-fidelity model generation via dynamic ensemble active learning, is \MultiLines{tgtRandSlct}{mdlGen}. First, $m_0$ random training samples are selected (\Line{tgtRandSlct}) to characterize the overall performance distribution of the workflow over all configurations. In general, $m_0$ is set to be from $m \cdot 5\%$ to $m \cdot 45\%$, depending on % workflow structure and optimization objective. Sensitivity studies reported in \SL{hp} show that CEAL is insensitive to the values used for $m_{\R{R}}$ and $m_0$ in a large range. We recommend $m_0 \approx 25\% \cdot m$ when $|D_j^{\R{hist}}| \gg m$ ($j$=1,...,$J$) and thus $m_{\R{R}}$=0, and $m_0 \approx 15\% \cdot m$ if no historical measurements are available (i.e., $|D_j^{\R{hist}}|$=0). Then, top configurations are selected (\TwoLines{topSlct}{tgtPred}) based on the evaluation with model $M$. (\MultiLines{detStart}{detEnd} handle the switching from low-fidelity to high-fidelity model.) The high-fidelity model is retrained repeatedly as more training data are acquired (\MultiLines{beginRefine}{endRefine}), and returned as the output of the algorithm. \section{Background and Motivation} \label{section:background} \vspace{-0.05in} HPC applications are often run repeatedly on similar computers and problems. These similarities can make it rewarding to tune configuration parameters to improve performance. Given the growing complexity of applications and HPC infrastructures, tuning increasingly relies on auto-tuners, particularly empirical model-based auto-tuners, which train a performance model of an application that they then use to search for and select a good set of configuration parameters. Though there are various auto-tuning approaches~\cite{Balaprakash:AutotunHPCApp:PIEEE18}, this paper focuses on empirical model-based auto-tuning, because of its effectiveness and prevalence. For brevity, we here refer to ``empirical model-based auto-tuning/auto-tuners'' as ``auto-tuning/auto-tuners.'' We next describe the basic mechanisms used in auto-tuners and identify the challenges in designing such auto-tuners for in-situ workflows. \vspace{-0.06in} \subsection{Empirical Model-based Auto-tuners} \vspace{-0.03in} An auto-tuner typically has three components: collector, modeler, and searcher \cite{Marathe:PerfMdlResConsTransLearn:SC17, Thiagarajan:BootParaSpacExplFastTun:ICS18, Golovin:GoogleVizierServBlacBoxOpt:KDD17, Tillet:InputAwareAutoTunCompBoundHPCKernel:SC17, Cao:UnderBlackAutoTunCompAnalStorSys:ATC18, Meng:PatternAlgoAutotunGraphProcGPU:PPoPP19, Behzad:OptIOPerfHPCAppAutotun:TOPC19}. The \emph{collector} runs the target application with different configurations selected by the modeler, and collects performance measurements. The \emph{modeler} selects configurations from the parameter configuration space of the target application, drives the collector to obtain the corresponding performance measurements, and uses the measurements as training data to construct a surrogate performance model: a high-dimensional function of configuration parameters, usually obtained by ML. The \emph{searcher} uses the model to search for a good configuration, i.e., one that produces good performance. During the search, the searcher uses the model to predict the performance for the configurations being examined, and selects the configuration with the best predicted performance. The core of an auto-tuner design is an auto-tuning algorithm. Factors to consider when designing this algorithm include model type and the methods used to select configurations used as training samples, train the model, and to search configuration space. Thus, for example, neural networks, which require many training samples, are not used in our solution, because the cost of collecting so many samples is prohibitive for HPC workflows. A well-designed auto-tuning algorithm can substantially both reduce the cost and improve the performance of an auto-tuner. For resource-intensive applications, such as HPC programs, {\it auto-tuner cost} is dominated by the time required to run the target application repeatedly to collect training data. Model training and configuration space search, in contrast, are inexpensive: for traditional ML models, such as boosted trees and random forests, they may take only a few minutes. {\it Auto-tuner performance}, the capacity to find good configurations and improve application performance, is determined primarily by how well the model predicts application performance for given configurations. (It is also affected by how the parameter space is searched, but as search mechanisms are mature, most efforts focus on improving the model.) \vspace{-0.06in} \subsection{Auto-Tuning for In-situ Workflows} \label{section:bgworkflows} \vspace{-0.03in} \begin{figure}[!t] \begin{center} \begin{subfigure}[t]{.57\linewidth} \includegraphics[width=1.0\linewidth]{posthoc.pdf} \caption{\it Post-hoc processing} \label{figure:post-hoc} \end{subfigure} \begin{subfigure}[t]{.41\linewidth} \includegraphics[width=1.0\linewidth]{intransit.pdf} \caption{\it In-situ workflow} \label{figure:in-transit} \end{subfigure} \vspace{-3ex} \caption{Post hoc processing vs.\ in-situ workflows} \label{figure:processing} \end{center} \vspace{-0.25in} \end{figure} In our context, a workflow is % a directed acyclic graph (DAG), with application components as nodes and data as edges. Components are typically coupled by using a higher-level programming model or language, thus exposing a \mbox{\emph{structure}} that can be exploited for % performance modeling and optimization. In a file-based post-hoc processing workflow, component applications are executed in an order determined by their data dependencies. For example, in \Figure{post-hoc}, when the simulation finishes, it saves data to persistent storage; only then can the analysis/visualization, which processes the data, be started. Performance optimization can then proceed in two steps. First, we model the performance of each component independently. Second, we find the best configuration based on the DAG and the component models. % In contrast, as shown in \Figure{in-transit}, component applications in an in-situ workflow run concurrently, exchanging data via network or shared memory. Workflow performance is determined by the complex interplay of the applications, which may involve factors such as load imbalances, contending network bandwidth, synchronizations, and locks~\cite{Fu:PerfAnalOptSituIntSimuAnalZipAppUp:HPDC18}. High performance requires that the component applications execute in a balanced and coordinated way. For an in-situ workflow, performance optimization cannot simply be done with separate performance models of each component application due to the complicated interactions among component applications. Instead, a performance model for the whole workflow must be built, and all parameters from all components should be optimized together. For empirical model-based auto-tuners, the fact that an in-situ workflow includes multiple coupled components raises considerable challenges. Because all parameters from all components must be considered together, the potential parameter combinations increases multiplicatively. For example, in the two-component workflows of \SL{benchmarks}, the configuration space sizes are more than 10$^5\times$ larger than those of their component applications. This dramatically raises the number of configurations to be measured as training samples for building a usable surrogate model. However, for in-situ workflows, it is not realistic to measure many parameter combinations, given the high resource consumption of running HPC applications. Without fundamentally renovating auto-tuning algorithms, particularly the techniques used to build the surrogate model, auto-tuners for in-situ workflows face a difficult dilemma---whether to suffer a prohibitive cost in creating the accurate surrogate model needed for optimal performance, or to tolerate the poor performance associated with an inaccurate surrogate model generated at an affordable cost. The CEAL algorithm proposed in this paper fundamentally improves the techniques to build surrogate models, such that auto-tuner cost can be reduced substantially while retaining high performance. The large resources needed to run a complete workflow repeatedly when building an auto-tuner, data collection costs are usually limited in practical settings by a resource budget. Thus, in this scenario, the advantage of the algorithm is reflected by improving the performance of the auto-tuner within a cost budget. \section{Generating the Low-fidelity Model} \label{section:combo} \vspace{-0.05in} We use the low-fidelity model to evaluate configurations by predicting how well the workflow may perform. The main challenge is to build a usable model with minimal cost, such that the auto-tuner can quickly start from it and use it to build and improve the high-fidelity model. \begin{figure}[!t] \begin{center} \includegraphics[width=.9\linewidth]{FaCe.pdf} \vspace{-2ex} \caption{Combining component models.} \vspace{-0.2in} \label{figure:Combo} \end{center} \end{figure} We build the low-fidelity model by first constructing and then combining predictive models for the component applications: see~\Figure{Combo}. Each individual \emph{component model}, $M_j$ ($j = 1, 2, \cdots$), outputs a performance prediction for its component for a given configuration. Its predictions should be aligned with the optimization goal of the auto-tuner; for example, execution times if the goal is shortening execution times. Component models can be built by using conventional methods, e.g., by randomly selecting configurations to collect samples and then training a boosted tree ML model. Since component applications are independent, they may be used separately or in other workflows. Costs can be reduced by including measurements collected in earlier runs in training, or by reusing models developed for other workflows. Due to space limitations, we do not elaborate here on how to build or reuse these models, but focus on how to combine component models to form the integral low-fidelity model. There are two issues in forming the low-fidelity model. The first is what the model should output. As we will use this model only to choose among configurations, we do not need it to predict workflow performance directly. Instead, we make it output for each configuration just a score indicating how well the workflow performs relative to other configurations. The second issue is how to combine per-component model results to build a low-fidelity model with minimal cost. One approach, which for later quantitative comparison we implement in an algorithm called ALpH, is to train a component-combining model $M_0$ from both component model predictions and actual workflow runs. % That is, for each candidate configuration $c$, we use the $\{ M_j \}$ to predict the performances, $\{ P_j \}$, of the components for $c$; run the workflow with $c$, measuring its performance $p$; and add $\{ c, \{ P_j \}, p \}$ to the training set for $M_0$. ALpH uses AL~\cite{Mametjanov:AutotunFPGAParaPerfPow:FCCM15} to select the configurations for which it generates such workflow training samples. A deficiency of this approach is that it does not exploit any knowledge of the workflow structure. An alternative, which we use in CEAL, is to use a simple function (e.g., max, min, sum), chosen according to the performance metric being optimized by the auto-tuner, to combine the component model predictions. We select this function as follows. If the performance metric is determined largely by the bottleneck components, such as execution time and throughput, we use {\it max} (for execution time) or {\it min} (for throughput). If the performance metric is largely an aggregation of the shares from all components, such as computing resource and energy consumption, we use {\it sum}. Notice that CEAL, unlike ALpH, does not need to run the workflow. We examine the relative accuracy and costs of CEAL and ALpH below. We postpone detailed evaluation to \S\ref{section:evaluation}, but report here on a study in which we use two optimization objectives with different metrics---shortening execution time and minimizing computer time---to illustrate and characterize the function approach. We define execution time as wall-clock time and computer time as the number of core-hours consumed by workflow execution. We define the functions used to determine a configuration's scores as follows. \vspace{-1ex} \begin{equation} \emph{Score}^{\R{e}}(c) = \max\limits_{j}{t^{\R{e}}}(c_j), \label{equation:max} \vspace{-1ex} \end{equation} \noindent \vspace{-1ex} \begin{equation} \emph{Score}^{\R{c}}(c) = \sum\limits_{j}{t^{\R{c}}}(c_j), \label{equation:sum} \vspace{-1ex} \end{equation} where for a configuration $c$, $\emph{Score}^{\R{e}}(c)$ and $\emph{Score}^{\R{c}}(c)$ are the {\it \B{e}}xecution and {\it \B{c}}omputer times (the lower, the better) of configuration $c$; $c_j$ is the parameter values related to component $j$ extracted from $c$; and $t^{\R{e}}(c_j)$ and $t^{\R{c}}(c_j)$ are the model-predicted execution and computer times of the $j^{\R{th}}$ component. \begin{figure}[t] \begin{center} \includegraphics[width=.6\linewidth]{top_rs_mdl-eps-converted-to.pdf} \vspace{-2ex} \caption{Recall scores based on combination functions.}\label{figure:cmb-rs} \end{center} \vspace{-5ex} \end{figure} To illustrate the effectiveness of this approach, \Figure{cmb-rs} shows the recall scores of the low-fidelity models (Eqns~\ref{equation:max} and~\ref{equation:sum}) when used to score 500 randomly selected configurations for workflow {\it LV}. (For details on experimental settings, see \S\ref{section:evaluation}.) Recall scores reflect the possibility that the highest-scoring configurations lead to high workflow performance (\SL{recallScore}). To calculate recall scores, we rank configurations based both on their model-predicted scores and on the performance observed when the workflow is executed with them. The recall score of the top $n$ configurations is then the ratio between 1) the number of common configurations found in the top $n$ configurations on these ranked lists and 2) $n$. We see that the models achieve recall scores above 30\% for top 5 to 25 configurations, much higher than those of random selection. This verifies that even using simple functions in the low-fidelity model can effectively locate good configurations. The solution described in this section mainly targets loosely-coupled in-situ workflows~\cite{Fu:PerfAnalOptSituIntSimuAnalZipAppUp:HPDC18, Subedi:StackerAutoDataMoveEngiExtScalStagSituWf:SC18}, in which components are coupled via high-level libraries (e.g., ADIOS~\cite{Liu:ADIOSChallLessDevLeadClasIOFw:CCPE14}, Flexpath~\cite{Dayal:FlexpathTypePubSubSysLScalScieAnal:CCGrid14}, DataSpaces~\cite{Docan:DataSpacesIntCoorFwCoupWf:CC12}, FlexIO~\cite{Zheng:FlexIOMiddLocaFlexScieDataAnal:IPDPS13}, GLEAN~\cite{Vishwanath:TopoDataMoveStagIOAcceBlueGeneP:SC11}, DIMES \cite{Zhang:DIMESInMemStagDataTaskPlacCoupWf:CCPE17}, Decaf~\cite{Dreher:DecafDecoDataSituWf:TR17}, or Zipper~\cite{Fu:PerfAnalOptSituIntSimuAnalZipAppUp:HPDC18}). The relative ease of development and deployment of loosely-coupled in-situ workflows relative to tightly-coupled in-situ workflows makes the former much more prevalent. However, our solution can easily be adapted to optimize tightly-coupled in-situ workflows. \section{Conclusion} \label{section:conclusion} \vspace{-0.05in} The use of machine learning (ML)-based auto-tuners has been considered infeasible for in-situ workflows due to their large configuration spaces. Our new approach achieves high-quality ML auto-tuners for in-situ workflows, even with a tight cost budget, by leveraging the fact that in-situ workflows often link multiple component applications in relatively simple structures. Specifically, our CEAL algorithm 1) combines models for component applications into a low-fidelity workflow model, and then 2) uses the low-fidelity model to guide the collection of samples for training a high-fidelity model. Experiments with three scientific in-situ workflows confirm the viability of the CEAL approach, showing it can build a high-quality auto-tuner that is better at finding best-performing configurations than auto-tuners built with other methods. In one example, CEAL with just 50 training samples optimizes workflow execution time so well than only 219 subsequent runs are required to recoup cost. \section{Experimental Evaluation} \label{section:evaluation} We describe % our benchmarks (\SL{benchmarks}), evaluation metrics (\SL{metrics}), and comparison targets (\SL{comparison}). Then, we evaluate the performance of CEAL and other algorithms in a general auto-tuning scenario without historical measurements, and investigate reasons for CEAL's superiority (\SL{noHist}). We also consider % optimization with historical component measurements, and compare CEAL with an algorithm that incorporates component performance by training a ML model (\SL{evalHist}). Finally, we study CEAL's sensitivity to hyper-parameter values (\SL{paraSens}). \vspace{-0.1in} \subsection{Experimental Setup} \label{section:benchmarks} \vspace{-0.05in} We conducted experiments on a 600-node cluster with Intel Omni-Path Fabric Interconnect. Each node has two 18-core 2.10GHz Intel Broadwell Xeon E5-2695 v4 processors with hyperthreading disabled and 128 GB DDR4 SDRAM. We ran each workflow with exclusive access to node resources, on allocation sizes up to 32 compute nodes. We used three in-situ workflows, namely \B{LV}, \B{HS}, and \B{GP}, in our experiments: \B{LV} couples two components: the LAMMPS~\cite{LAMMPS} molecular dynamics simulator and Voro++~\cite{Voropp}, a Voronoi tesselator. LV involves full-featured, realistic applications coupled via ADIOS. The sample run used here simulates \num{16000} atoms and streams position and velocity data into the tesselator for analysis and visualization. This application is a model for many cases in particle simulation and visualization. \B{HS} also couples two components: a Heat Transfer~\cite{HeatTransfer} simulation with an analysis application, Stage Write. Heat Transfer is a mini-application that runs the heat equation over the grid of a given size and forwards simulation state over ADIOS to Stage Write, which produces output in the file system. % % % This application is a model for many cases in numerical PDE calculations and I/O buffering and forwarding. \B{GP} couples four components: Gray-Scott reaction-diffusion simulation; an analysis application, PDF calculator, applied to the Gray-Scott output; a visualization application, G-Plot, also applied to Gray-Scott output; and a second visualization application, P-Plot, applied to PDF output. GP involves applications of intermediate complexity, also coupled via ADIOS. Two component applications, Gray-Scott and PDF calculator are configurable, but G-Plot and P-Plot are not. This application is a model for many cases in chemical reaction dynamics and more complex multi-purpose analysis workflows. \begin{table} \begin{center} \caption{Parameter spaces for our three target workflows} \vspace{-3ex} \scriptsize \begin{tabular}{|c|c|l|l|} \hline \B{Workflow} & \B{Application} & \B{Parameter} & \B{Options} \\ \hline & & \# processes & 2, 3, $\cdots$, \num{1085} \\ \cline{3-4} & LAMMPS & \# processes per node & 1, 2, $\cdots$, 35\\ \cline{3-4} LV & & \# threads per process & 1, 2, 3, 4 \\ \cline{3-4} & & \# steps in an IO interval & 50, 100, $\cdots$, 400 \\ \cline{2-4} & & \# processes & 2, 3, $\cdots$, \num{1085} \\ \cline{3-4} & Voro++ & \# processes per node & 1, 2, $\cdots$, 35 \\ \cline{3-4} & & \# threads per process & 1, 2, 3, 4 \\ \hline & & \# processes in X & 2, 3, $\cdots$, 32 \\ \cline{3-4} & Heat & \# processes in Y & 2, 3, $\cdots$, 32 \\ \cline{3-4} HS & transfer & \# processes per node & 1, 2, $\cdots$, 35 \\ \cline{3-4} & & \# IO writes & 4, 8, $\cdots$, 32 \\ \cline{3-4} & & buffer size (MB) & 1, 2, $\cdots$, 40 \\ \cline{2-4} & Stage & \# processes & 2, 3, $\cdots$, \num{1085} \\ \cline{3-4} & write & \# processes per node & 1, 2, $\cdots$, 35 \\ \hline & Gray- & \# processes & 2, 3, $\cdots$, 1085 \\ \cline{3-4} GP & Scott & \# processes per node & 1, 2, $\cdots$, 35 \\ \cline{2-4} & PDF & \# processes & 1, 2, $\cdots$, 512 \\ \cline{3-4} & calculate & \# processes per node & 1, 2, $\cdots$, 35 \\ \cline{2-4} & Gray plot & \# processes & 1 \\ \cline{2-4} & PDF plot & \# processes & 1 \\ \hline \end{tabular} \label{table:parameter} \vspace{-4ex} \end{center} \end{table} Application configuration options, shown in~\Table{parameter}, form a total of 2.3 $\times$ 10$^{10}$ possible configurations for LV (LAMMPS: 6.1 $\times$ 10$^{5}$; Voro++: 7.6 $\times$ 10$^{4}$), 5.1 $\times$ 10$^{10}$ for HS (Heat Transfer: 5.4 $\times$ 10$^{6}$; Stage Write: 1.9 $\times$ 10$^{4}$), and 8.5 $\times$ 10$^{7}$ for GP (Gray-Scott: 1.9 $\times$ 10$^{4}$; PDF calculator: 9.0 $\times$ 10$^{3}$). We obtained expert-recommended configurations for each. In order to compare expert-recommended vs.\ good configurations, we generated for each workflow, as $C_{\R{pool}}$, 2000 configurations of randomly selected parameter values. Then, for each such configuration, we launched all workflow components at once and recorded each component's end-to-end wall-clock time. We then used the longest component execution time as the configuration's \emph{execution time}, and the product of execution time, number of computing nodes used, and number of cores per node as the configuration's \emph{computer time}. We list in \Table{perfConf} the expert-recommended and best configurations for each workflow and optimization objective, and their achieved performance. The expert recommendations only do well for GP. (Since the unconfigurable G-Plot is the bottleneck in GP, many GP configurations have similar execution times, close to that of G-Plot alone, 97.0 seconds.) \begin{table} \begin{center} \caption{Configurations and performance of benchmarks} \vspace{-3ex} \scriptsize \begin{tabular}{|c|c|c|c|c|} \hline \B{Wf.} & \B{Objective} & \B{Option} & \B{Performance} & \B{Configuration} \\ \hline & Exec. time & Best & 27.2 secs & (430, 23, 1, 300, 88, 10, 4) \\ % \cline{3-5} LV & & Expert & 36.8 secs & (288, 18, 2, 400, 288, 18, 2) \\ % \cline{2-5} & Comp. time & Best & 3.36 core-hrs & (175, 35, 2, 400, 38, 29, 3) \\ % \cline{3-5} & & Expert & 4.15 core-hrs & (18, 18, 2, 400, 18, 18, 2) \\ % \hline & Exec. time & Best & 6.02 secs & (13, 17, 14, 4, 29, 19, 3) \\ \cline{3-5} HS & & Expert & 28.0 secs & (32, 17, 34, 4, 20, 560, 35) \\ % \cline{2-5} & Comp. time & Best & 0.517 core-hrs & (5, 25, 35, 4, 3, 5, 3) \\ % \cline{3-5} & & Expert & 0.894 core-hrs & (8, 4, 32, 4, 20, 35, 35) \\ % \hline & Exec. time & Best & 98.7 secs & (175, 13, 24, 23, 1, 1, 1) \\ % \cline{3-5} GP & & Expert & 102 secs & (525, 35, 525, 35, 1, 1) \\ \cline{2-5} & Comp. time & Best & 6.95 core-hrs & (66, 34, 41, 22, 1, 1) \\ % \cline{3-5} & & Expert & 5.85 core-hrs & (35, 35, 35, 35, 1, 1) \\ \hline \end{tabular} \label{table:perfConf} \vspace{-5ex} \end{center} \end{table} We also measured the execution and computer times of 500 configurations randomly selected from the parameter space of each configurable component application, and used these samples as component measurements, from which CEAL may select training samples for component models. \vspace{-0.05in} \subsection{Evaluation Metrics} \label{section:metrics} \vspace{-0.05in} We use three metrics to evaluate auto-tuning algorithms. \vspace{-0.05in} \subsubsection{Performance of Best Predicted Configuration} \label{section:actPerf} As our goal is to optimize the execution time and computer time of in-situ workflows, the execution and computer time achieved by the best configuration predicted for a workflow is an important evaluation metric. \vspace{-0.05in} \subsubsection{Robustness in Finding Top Configurations} \label{section:recallScore} We use the \B{recall score} to measure the error tolerance of an autotuning algorithm in predicting top configurations. As defined by Marathe~\etal~\cite{Marathe:PerfMdlResConsTransLearn:SC17}, recall score is, for a value $n$, the percentage of configurations as predicted by the algorithm that are actually within the top $n$ configurations. Given a set of configurations \textbf{c} for which we have workflow performance data $\textbf{D}_{\textbf{c}}$, a model \textbf{M} for scoring configurations, and a function top$(n, s)$ for selecting the top $n$ entries from a set of scored configurations $s$, the recall score for $n$ is: \vspace{-1ex} \begin{equation} S_r(n, \textbf{c}, \textbf{M}, \textbf{D}_{\textbf{c}}) = | \textrm{top}(n, \textbf{M}(\textbf{c})) \cap \textrm{top}(n, \textbf{D}_{\textbf{c}})|/n \times 100\%. \end{equation} A higher recall score indicates a more robust auto-tuning algorithm; in general, $S_r(i)$ is more important than $S_r(j)$ ($i < j$). For $n=1$, the recall score also represents the probability of finding the best-performing configuration. \vspace{-0.05in} \subsubsection{Practicality in Performance Optimization} \label{section:netGain} Since the data collection cost is considerable and unignorable for empirical auto-tuning algorithms, we monitor the least number of workflow runs required to pay off the auto-tuning cost, and use that metric to evaluate the practicality of auto-tuning algorithms. The \B{least number of uses} is $N=c/\Delta p$. Here, $\Delta p$ is the actual improvement per workflow execution in the optimization objective (execution time or computer time reduction) achieved by the auto-tuning algorithm relative to an expert recommendation, and $c$ is the training data collection cost incurred in achieving the performance optimization objective, i.e., the sum of the workflow's execution times or computer times over all training samples. \vspace{-0.05in} \subsection{Comparison Targets} \label{section:comparison} \vspace{-0.05in} \begin{figure*} \begin{center} \begin{minipage}[t]{1\linewidth} \begin{subfigure}[t]{.385\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{lmp-vr-top_perf_norm-eps-converted-to.pdf} \vspace{-1ex} \caption{\it LV} \label{figure:topPerf_lv} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{.385\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{ht-sw-top_perf_norm-eps-converted-to.pdf} \vspace{-1ex} \caption{\it HS} \label{figure:topPerf_hs} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{.193\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{gs-pdf-top_perf_norm-eps-converted-to.pdf} \vspace{-1ex} \caption{\it GP} \label{figure:topPerf_gp} \end{subfigure} \vspace{-3ex} \caption{The best configuration auto-tuned w/o historical measurements (dashed lines: the best configuration in the test set)} \label{figure:topPerf} \end{minipage} \end{center} \vspace{-2ex} \end{figure*} \begin{figure*}[!t] \begin{center} \begin{minipage}[t]{.32\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{mdape-eps-converted-to.pdf} \vspace{-5ex} \caption{Prediction accuracy of models in autotuning w/o historical measurements} \label{figure:mdape} \end{minipage} \hspace{0.005\linewidth} \begin{minipage}[t]{.65\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_rs_exec-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing execution time of LV and HS} \label{figure:rs_exec} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_rs_comp-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing computer time of LV and GP} \label{figure:rs_comp} \end{subfigure} \vspace{-2.5ex} \caption{Robustness of autotuning w/o historical measurements} \label{figure:rs} \end{minipage} \end{center} \vspace{-3ex} \end{figure*} Since there exist few auto-tuning algorithms customized for in-situ workflows, we compare CEAL with three auto-tuning algorithms for general HPC applications. % \B{RS} selects training data by random sampling. \B{AL} is a typical AL algorithm that iteratively selects a batch of the best configurations predicted by gradually refined models as training samples~\cite{Mametjanov:AutotunFPGAParaPerfPow:FCCM15, Behzad:OptIOPerfHPCAppAutotun:TOPC19}. \B{GEIST}, a state-of-the-art AL-based auto-tuning algorithm for finding performance-optimizing configurations~\cite{Thiagarajan:BootParaSpacExplFastTun:ICS18} is guided by a parameter graph to choose training samples with the highest possibility of being optimal (defined as in top 5\% configurations) in each iteration. We also report in \S\ref{sec:alph} on comparisons with a variant of CEAL, \B{ALpH} (introduced in \SL{combo}) that uses learning to combine component models. In all algorithms, we use the xgboost.XGBRegressor implementation of extreme gradient boosting regression as the original ML model. We adjust GEIST, AL, ALpH, and CEAL hyperparameters with and without historical measurements, and $I$, $m_0$, and $m_{\R{R}}$ in CEAL, and select the best settings for each algorithm. % Hyperparameter optimization methods~\cite{Xia:BoosDeciTreeApprBayeHypeOptiCredScor:ESA17} are beyond the scope of this paper. In all experiments, we run each algorithm 100 times and report averages. \vspace{-0.05in} \subsection{Autotuning without Historical Measurements} \vspace{-0.05in} \label{section:noHist} \begin{figure*}[!t] \begin{center} \begin{minipage}[t]{.3\linewidth} \includegraphics[height=3cm, width=1\linewidth]{least_use_comp-eps-converted-to.pdf} \vspace{-2ex} \caption{Practicality of autotuning w/o historical measurements} \label{figure:numUse_comp} \end{minipage} \hspace{0.005\linewidth} \begin{minipage}[t]{.67\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_perf_ceal_nexec-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Execution time of predicted best conf.} \label{figure:topPerf_ceal_exec} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_perf_ceal_ncomp-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Computer time of predicted best conf.} \label{figure:topPerf_ceal_comp} \end{subfigure} \vspace{-2.5ex} \caption{Effect of historical measurements on CEAL (dashed lines: best test config.)} \label{figure:topPerf_ceal} \end{minipage} \end{center} \vspace{-3ex} \end{figure*} We first examine the overall performance of our auto-tuner in the absence of historical measurements. We compare the actual performance of workflows auto-tuned by CEAL and others (\SL{NHperf}), and explain CEAL's superiority by experimentally validating its design principle (\SL{actReason}). Also, we investigate CEAL's robustness and practicality (\SL{NHrobust} and \SL{NHpractice}). (When comparing costs, we consider the cost of running an in-situ workflow as being comparable to the total cost of running all of its component applications separately.) \subsubsection{Actual Performance of Auto-tuned Workflows} \label{section:NHperf} We measured the actual execution and computer time of the best configurations of LV, HS, and GP predicted by RS, GEIST, AL, and CEAL, and plot normalized values in~\Figure{topPerf}, with the performance of the best configuration in the test set shown as ``1'' (the same for \TwoFigures{topPerf_ceal}{topPerf_hist}). We test CEAL with different numbers $m$ of training samples by doubling $m$ from 25 until the auto-tuned performance of LV is at most 5\% worse than the best. We show here results for the largest two values of $m$ tested: 100 and 50 for execution time and 50 and 25 for computer time. For consistency, we also select the same $m$ for all workflows in all experiments. \Figure{topPerf} shows that the execution and computer times achieved by CEAL are always better than by RS, GEIST, and AL. For example, CEAL improves both execution and computer time by 14--72\% relative to RS and 12--60\% relative to GEIST---and LV computer time relative to LV by 11.9\% and 6.9\% with 25 and 50 training samples, respectively. CEAL outperforms AL, because performance models trained with the same number of training samples are much more accurate for component applications than in-situ workflows, and our method of determining workflow performance provides relatively accurate configuration ranking over top configurations. \vspace{-0.05in} \subsubsection{Why CEAL Outperforms RS and AL} \label{section:actReason} The absolute percentage error (APE) of a sample $i$ is $|(y_i - y'_i) / y_i|$, where $y_i$ is actual performance and $y'_i$ is predicted performance. The median APE (MdAPE) for a set of samples is a commonly used measure of model prediction quality. To further understand why CEAL beats AL and RS, we plot in \Figure{mdape} the MdAPEs of models generated by RS, AL, and CEAL when used to predict performance over all, and the top 2\%, of test dataset configurations. CEAL MdAPEs are much less than those of RS and AL for the top 2\% of configurations; as a result, CEAL outperforms RS and AL, even though its MdAPEs are comparable to, or a little higher than, those of RS and AL over \emph{all} configurations. This result verifies our intuition that picking higher-performance configurations can improve prediction accuracy for top configurations, and thus make best use of the few training samples allotted. \vspace{-0.05in} \subsubsection{Robustness of Auto-tuning Algorithms} \label{section:NHrobust} We use the recall scores (\SL{recallScore}) of the top $n$ ($n=1, \cdots, 10$) configurations to evaluate the robustness of RS, GEIST, AL, and CEAL in auto-tuning our workflows % for execution time and computer time. We see in \Figure{rs} that CEAL is more robust than RS, GEIST, and AL in most cases. For the top-one configuration recall score (the most important performance measure), CEAL achieves 76\% (or 79\%) when optimizing the computer (or execution) time of LV with 50 training samples, as against 4\% (or 5\%), 12\% (or 6\%), and 51\% (or 32\%) for RS, GEIST, and AL. For instance, although CEAL's recall score is lower than that of AL for the top 4 to 10 configurations for LV, it still obtains a better execution time. \vspace{-0.05in} \subsubsection{Practicality of Auto-tuning Algorithms} \label{section:NHpractice} We examine the practicality of the four auto-tuning algorithms in optimizing the computer time of LV and HS. Since the computer time of LV/HS achieved by RS and GEIST with only 25 and 50 training samples is worse than that at the expert-recommended configuration, the practicality of RS and GEIST is limited. Then, we focus on auto-tuning the computer time of LV and HS by AL and CEAL with 50 training samples, and plot the least number of runs (\SL{netGain}) in~\Figure{numUse_comp}, which reveals that CEAL is superior to AL in terms of practicality. In particular, LV is worth auto-tuning by CEAL if it is expected to run 864 times, 40\% less than the 1444 times required for AL. We attribute CEAL's superiority to its more accurate selection of training samples that take less computer time, as boosted by the combined low-fidelity model. \vspace{-0.05in} \subsection{With Historical Component Measurements} \label{section:evalHist} \vspace{-0.05in} \begin{figure*}[!t] \begin{center} \begin{minipage}[t]{.65\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_perf_hist_nexec-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing execution time} \label{figure:topPerf_hist_exec} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_perf_hist_ncomp-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing computer time} \label{figure:topPerf_hist_comp} \end{subfigure} \vspace{-2.5ex} \caption{Best configuration auto-tuned with histories (dashed lines: best test config.)} \vspace{1ex} \label{figure:topPerf_hist} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_rs_exec_hist-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing execution time of LV and HS} \label{figure:rs_hist_exec} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{.485\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{top_rs_hist-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing computer time of LV and GP} \label{figure:rs_hist_comp} \end{subfigure} \vspace{-2.5ex} \caption{Robustness of autotuning with historical measurements} \label{figure:rs_hist} \end{minipage} \hspace{0.005\linewidth} \begin{minipage}[t]{.32\linewidth} \begin{subfigure}[t]{1\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{least_use_exec_hist-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing execution time} \label{figure:numUse_hist_exec} \end{subfigure} \hspace{0.005\linewidth} \begin{subfigure}[t]{1\linewidth} \includegraphics[height=3.05cm, width=1\linewidth]{least_use_comp_hist-eps-converted-to.pdf} \vspace{-1ex} \caption{\it Optimizing computer time} \label{figure:numUse_hist_comp} \end{subfigure} \vspace{-2.5ex} \caption{Practicality of autotuning with historical measurements} \label{figure:numUse_hist} \end{minipage} \end{center} \vspace{-3ex} \end{figure*} Since component historical measurements are often available, we next examine auto-tuner performance when historical measurements are considered. We show that CEAL can make good use of component measurements to enhance workflow performance (\SL{Hceal}) and auto-tuner practicality (\SL{Hpractice}). We also demonstrate the superiority of CEAL over ALpH's component integration method (\SL{Hperf}, \SL{Hrobust}). \vspace{-0.05in} \subsubsection{Effect of Previous Component Measurements} \label{section:Hceal} If historical performance measurements are available for component applications, then CEAL can use those measurements to train component application models without charge against its training sample budget, and then perform more full workflow runs that would otherwise be possible. In order to explore the benefits that result, we compare workflow performance when optimized by CEAL with and without historical measurements. In the first case, we assume no historical measurements, and thus subtract the $m_R$ component samples used to train component models from CEAL's training sample budget; in the second, we treat those measurements as historical and do not count them toward the cost. We see from \Figure{topPerf_ceal} that historical measurements improve CEAL performance in all cases. In addition, \Figure{topPerf_ceal_comp} shows that historical measurements help CEAL, in the case of 25 training samples, reduce computer time for LV by 10.0\%, HS by 38.9\%, and GP by 4.8\%. We conclude that CEAL can make effective use of historical component measurements. \vspace{-0.05in} \subsubsection{Actual Performance of Auto-tuned Workflows}\label{sec:alph} \label{section:Hperf} Recall from \SL{combo} that ALpH differs from CEAL in using learning rather than functions to combine component model performance predictions. To compare these approaches to combining component models, we measure LV, HS, and GP performance when auto-tuned by ALpH and CEAL with different numbers of training samples. The normalized execution and computer times in \Figure{topPerf_hist} show that CEAL is superior to ALpH in all cases. For example, we see in \Figure{topPerf_hist_comp} that the computer times of LV, HS, and GP when optimized by CEAL with 25 training samples are 15.1\%, 32.6\%, and 6.5\% less than when optimized by ALpH, respectively. We attribute CEAL's outperforming ALpH with the same historical measurements to CEAL's component combination using training samples more efficiently than ALpH's model-based approach. \vspace{-0.05in} \subsubsection{Robustness of Auto-tuning Algorithms} \label{section:Hrobust} We also evaluate the robustness of ALpH and CEAL with historical component measurements in optimizing the execution and computer time of our in-situ workflows. The recall scores (\SL{recallScore}) at top configurations are plotted in~\Figure{rs_hist}; we see that CEAL is always more robust than ALpH. CEAL's best-1 and best-2 configuration recall scores are both above 99\%. \vspace{-0.05in} \subsubsection{Practicality of Auto-tuning Algorithms} \label{section:Hpractice} We examine the practicality of ALpH and CEAL with historical component measurements for auto-tuning LV and HS, and plot the number of runs (\SL{netGain}) in~\Figure{numUse_hist}. It can be observed that when CEAL is used to optimize LV execution time with 50 training samples and LV computer time with 25 training samples, the number of LV runs (\SL{netGain}) required to recoup the auto-tuning cost is only 219 and 269, implying great practicality of CEAL. As to the execution time cost, we consider workflow instances at training configurations to run sequentially, even though the training data collection can sometimes be completed in parallel. \vspace{-0.05in} \subsection{Hyper-parameter Sensitivity Analysis}\label{section:hp} \vspace{-0.05in} \label{section:paraSens} We use LV, when predicting the best computer time with 50 training samples, to study CEAL's sensitivity to hyper-parameter values. \Figure{parameter} shows the actual computer times of the best configurations predicted in various settings. (1) We run CEAL with from 1 to 10 iterations ($I$). We see in~\Figure{num_iter_comp} that LV computer time converges to the best after three iterations. (2) We test CEAL as the number of coupled random samples replaced by component samples ($m_{\R{R}}$) is varied from $5\% \cdot m$ to $(m - m_0)$ at an interval of $5\% \cdot m$. \Figure{prec_init_comp} shows that LV computer time is stable over a large range of $m_{\R{R}}$: from 20\% to 65\% training samples. (3) We run CEAL as we increase the number of random samples ($m_0$) from $5\% \cdot m$ to $(m - m_{\R{R}})$ at an interval of $5\% \cdot m$. \Figure{prec_rand_comp} shows that LV computer time is stable over a large range of $m_0$: from $5\% \cdot m$ to $35\% \cdot m$ for CEAL with historical measurements and from $5\% \cdot m$ to $75\% \cdot m$ for CEAL without historical measurements. We have also performed these studies for our other workflows and optimization metrics, and see similar results, except that in one case we found that an $m_0$ value of around $45\% \cdot m$ was best, indicating that (as discussed in \S\ref{section:actLearn}), the low-fidelity model was not performing well. \begin{figure} \begin{center} \begin{subfigure}{0.325\linewidth} % \includegraphics[height=2.15cm, width=1.\linewidth, trim=2 0 2 2,clip]{lmp-vr-num_iter-top_perf_50-eps-converted-to.pdf} \caption{$I$} \label{figure:num_iter_comp} \end{subfigure} \begin{subfigure}{0.325\linewidth} \includegraphics[height=2.15cm, width=1.\linewidth, trim=2 2 2 2,clip]{lmp-vr-prec_init-top_perf_50-eps-converted-to.pdf} \caption{$m_{\R{R}}$/$m$} \label{figure:prec_init_comp} \end{subfigure} \begin{subfigure}{0.325\linewidth} \includegraphics[height=2.15cm, width=1.\linewidth, trim=2 5 2 0,clip]{lmp-vr-prec_rand-top_perf_50-eps-converted-to.pdf} \caption{$m_0$/$m$} \label{figure:prec_rand_comp} \end{subfigure} \vspace{-3ex} \caption{Impact of parameter settings.} \label{figure:parameter} \end{center} \vspace{-4ex} \end{figure} \section{Introduction} \label{section:introduction} \vspace{-0.05in} Emerging scientific workflows couple simulation tasks with analysis, visualization, learning, and other data processing tasks. It is increasingly infeasible to couple such workflows via file systems due to the performance gap between the computational and I/O components of HPC systems, as well as the negative impacts on other users of the shared infrastructure. In contrast, in-situ workflow solutions use network or shared memory to pass intermediate results~\cite{Ayachit:PerfAnalDesiConsAppExtscalSituInfra:SC16}. Despite their advantages, in-situ workflows raise performance tuning challenges. A single component application running in isolation can be tuned by selecting good configurations with known auto-tuning methods. For example, empirical machine learning (ML) model-based auto-tuners have been widely applied to identify good configuration parameter values~\cite{Marathe:PerfMdlResConsTransLearn:SC17, Yu:DatasizeAwareHighDimenConfAutoTunInMemClusterComp:ASPLOS18, Ding:AutotunAlgoChoiInputSens:PLDI15}. Multiple runs are performed with different parameter values, performance data from these runs are used to train the performance prediction model, and this model is used to identify a (close-to-)optimal configuration. However, in the case of in-situ, multi-component workflows, it is typically insufficient to tune each component independently because components interact frequently and contend for resources during execution. Parameter values that enable optimal performance for a component running in isolation may lead to poor performance when the component is executed in the workflow. Ideally, all parameters from all components should be optimized together, but that approach is rarely realistic with conventional methods, due to the multiplicative increase in potential parameter combinations. A key issue for automated optimization of in-situ workflows is thus how to produce good results at an affordable cost. To this end, we introduce here a new auto-tuning approach. We leverage the workflow structure of the coupled applications and combine the effectiveness of tuning a workflow as a whole and the simplicity of tuning individual components. We first train models on each component separately and then leverage the trained component models to guide the search for optimal parameter values for the workflow. We address two challenging issues. First, the component models of a workflow must be % combined into an integral model, which then can be used to help the search. We address this issue by leveraging high-level knowledge of the workflow structure and how overall performance is affected by that of its components. We couple component models based on this knowledge to create a low-fidelity yet integral performance model of the workflow. Second, the integral model must be applied in the search for good workflow parameter values, even though the model cannot be used directly in the search due to its low fidelity. Thus, we use it to help train a high-fidelity performance model of the workflow, which is then used in the search. Specifically, we use the low-fidelity model within an active learning (AL) algorithm to select good configurations as training samples. The intuition is that the search does not require a performance model with high fidelity in all circumstances. Instead, high fidelity is needed only when examining the parameter values close to the best configuration. In auto-tuning, the dominant cost is that of running a workflow repeatedly with different configurations in order to collect enough data for accurate performance model generation. For conventional methods that treat an in-situ workflow as a whole and train its model in the same way as they do a single application, the huge parameter space results in the workflow being run with many configurations. Our solution substantially reduces costs in two ways. First, each component application has a smaller parameter space than the whole workflow; thus, we can create its low-fidelity model with relatively small training datasets. Second, the use of these low-fidelity models in the active learning algorithm helps us to select whole-workflow training samples that lead to a high-quality model with fewer whole-workflow runs. This paper makes the following contributions: 1) We propose and explore the idea of auto-tuning an in-situ worflow by combining structured performance models trained on component applications. 2) We implement the idea in a new in-situ workflow auto-tuning algorithm, CEAL (\BU{C}omponent-based \BU{E}nsemble \BU{A}ctive \BU{L}earning). 3) We use three in-situ HPC workflows to experimentally verify the superiority of CEAL over other auto-tuning algorithms. With just 25 training samples, CEAL can reduce computer time by 12--48\%. \section*{Acknowledgements} This article reports on activities of the Codesign center for Online Data Analysis and Reduction (CODAR) \citep{foster2017computing}, which is supported by the Exascale Computing Project (17-SC-20-SC), a collaborative effort of the U.S. Department of Energy Office of Science and National Nuclear Security Administration. % % % % % \section{Overview of the CEAL Approach} \label{section:overview} \vspace{-0.05in} We now introduce the methods that CEAL uses to identify well-performing configurations for in-situ workflows, by building surrogate models with limited sampling costs. \vspace{-0.05in} \subsection{Basic Idea} \vspace{-0.05in} As auto-tuning cost is dominated by the collection of training samples, we must select training samples carefully and use them effectively, instead of selecting training samples indiscriminately and extensively (e.g., by random sampling). The general idea of intelligent sampling has been explored in different ways in ML and in auto-tuner designs~\cite{Mametjanov:AutotunFPGAParaPerfPow:FCCM15, Behzad:OptIOPerfHPCAppAutotun:TOPC19, Thiagarajan:BootParaSpacExplFastTun:ICS18, Marathe:PerfMdlResConsTransLearn:SC17}. Our work is distinguished by how we exploit the workflow structure (\S\ref{section:bgworkflows}) to develop special techniques that are particularly effective for auto-tuning in-situ workflows. Our approach leverages the following two characteristics of in-situ workflows: 1) An in-situ workflow consists of multiple components, which can run independently and may be reused across workflows. 2) The interaction among components means that if any component % performs poorly, the workflow is unlikely to achieve high performance. These characteristics suggest that we should avoid collecting samples in which a workflow performs poorly, as such samples are unlikely to help with finding well-performing configurations. But how are we to avoid collecting poor-performing samples in the absence of a performance model, which is why we want those samples in the first place? We employ two ideas. 1) Leveraging the first characteristic, we build performance models for individual component applications. Because the parameter spaces of component applications are much smaller than that of the in-situ workflow, these models can be built at low cost, i.e., with only a few component application runs. (Component reuse across workflows can allow for the reuse of their models, further lowering costs.) 2) Leveraging the second characteristic, plus the component models that we have just developed, we build a simple low-fidelity model that we use to guide our search for well-performing configurations for the whole in-situ workflow, and focus sample collection on these configurations. We also investigated other techniques that improve the selection of training samples and thus may be integrated in our solution. Active learning iteratively uses the model that is being refined to identify configurations that may lead to good performance, and focuses sample collection on those configurations~\cite{Mametjanov:AutotunFPGAParaPerfPow:FCCM15, Behzad:OptIOPerfHPCAppAutotun:TOPC19}. Our approach similarly focuses on well-performing configurations, as we discuss in \SL{actLearn}. We also explored the use of configurations with much smaller inputs (i.e., much lower cost) for model building~\cite{Marathe:PerfMdlResConsTransLearn:SC17}. However, we found that programs often display quite different behaviors if input sizes (and problem sizes) change considerably, as when a reduced working set, corresponding to a smaller input, can fit into memory or cache. Thus, this technique cannot be used in general when auto-tuning in-situ workflows. \begin{figure}[!t] \begin{center} \includegraphics[width=.9\linewidth]{CEAL.pdf} \vspace{-2ex} \caption{Structure of CEAL auto-tuning.} \vspace{-0.4in} \label{figure:CEAL} \end{center} \end{figure} \vspace{-0.05in} \subsection{The CEAL Algorithm Introduced} \label{section:algoDesign} \vspace{-0.05in} To implement these ideas, we design the \BU{C}omponent-based \BU{E}nsemble \BU{A}ctive \BU{L}earning (CEAL) auto-tuning algorithm shown in~\Figure{CEAL}. CEAL consists of two main phases. In the \B{Low-fidelity Model Generation via Component Combination} phase, the red rectangle in~\Figure{CEAL}, we build performance models for a workflow's component applications which we combine to form a simple yet integral workflow model. This simplicity means that the integral model can be obtained at low cost but yields only approximate predictions. % We use this \emph{low-fidelity} workflow model ($M_0$ in \Figure{CEAL}) in the second phase, to evaluate configurations. In the \B{High-fidelity Model Generation via Dynamic Ensemble Active Learning} phase, the orange dashed rectangle in~\Figure{CEAL}, we use a series of samples selected based on low-fidelity model scoring to establish and improve a second, high-fidelity model of the workflow ($M_1$ in \Figure{CEAL}). This is the surrogate model that the searcher will use to predict workflow performance so as to find an ideal configuration. The high-fidelity model is primitive when first established, but keeps evolving as more samples are collected and used in training, and may become a better choice for evaluating configurations than the low-fidelity model. Thus, we use a {\it model switch detection module} to monitor the two models, and switch to using the high-fidelity model to evaluate configurations when it becomes a better choice. We stop evolving the high-fidelity model when the cost budget is reached (i.e., we have tested a preset number of configurations). We introduce these two phases in the next two sections, after which we present the detailed algorithm. \section{Related Work} \label{section:related} \vspace{-0.05in} Sourouri~\etal~\cite{Sourouri:ToFinegrainDynTunHPCAppMultiCoreArch:SC17} integrate fine-grained auto-tuning with user-controllable hardware switches and threads in order to use dynamic voltage and frequency scaling to improve the energy efficiency of a memory-bound HPC application. % However, their application-specific analytical performance model is not directly applicable to other applications. Popov~\etal~\cite{Popov:ThrePageParaAutotunNUMA:ICS19} reduce data collection costs by extracting and running short representative codelets, rather than whole applications, to jointly optimize page and thread mappings for applications in NUMA systems. However, this approach % will not pick the optimal configuration for a whole application when that configuration is not the best of any codelet.% Some auto-tuners target storage systems. Cao~\etal~\cite{Cao:UnderBlackAutoTunCompAnalStorSys:ATC18} apply and analytically compare multiple black-box optimization techiques focusing on storage systems. Li~\etal~\cite{Li:CAPESUnsuperviseStorTunNeuralNetReinforceLearn:SC17} used reinforcement learning to develop a model-less unsupervised storage parameter tuning system, CAPES. However, these studies do not take data collection costs into account. Others have applied active learning to HPC auto-tuning \cite{Ogilvie:MiniCostIterCompilActLearn:CGO17, Duplyakin:ActLearnPerfAnal:CLUSTER16, Balaprakash:ActLearnSurrMdlEmpiPerfTun:CLUSTER13}. GEIST uses semi-supervised learning based on a parameter graph for fast parameter space exploration~\cite{Thiagarajan:BootParaSpacExplFastTun:ICS18}; it can auto-tune HPC applications with configuration parameter spaces in the range of 18000. Our work targets optimizing complex HPC applications with configuration space size of 10$^{10}$ or more at an affordable data collection cost. Marathe~\etal~\cite{Marathe:PerfMdlResConsTransLearn:SC17} proposed an HPC application auto-tuning algorithm that used three fully connected neural networks to capture the relationship between configuration parameters and performance metrics from many cheap and a few expensive training computations. However, the small, cheap samples often have low similarity to the large, expensive samples, failing to provide transferable knowledge.
{'timestamp': '2020-08-18T02:20:28', 'yymm': '2008', 'arxiv_id': '2008.06991', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06991'}
arxiv
\section{Introduction} In \cite{Liu2016}, the authors proposed cooperative non-orthogonal multiple-access (NOMA) scheme where only the near user is an energy harvesting (EH) node that relays information to the far user, however, the work does not take into account securing the communication between the multiple nodes. The work in \cite{Tang19} optimized energy efficiency in non-cooperative NOMA under power budget and data rate constraints without exploiting physical-layer security schemes \cite{Badawy_IWCMC}. Hybrid simultaneous wireless information and power transfer (SWIPT) schemes were proposed in \cite{Shafie17} and \cite{8943160} under the consideration of the harvested energy at the receiving node while securing the legitimate transmissions, however, both works do not take NOMA and/or multiple-access scenarios into consideration. Moreover, \cite{Gao17} investigated physical layer security in large scale NOMA networks, without considering EH at the nodes. \subsection*{Contributions} In this paper, we consider a system operating under non-cooperative NOMA scenario which employs OFDM transmissions. Without knowledge of the eavesdroppers' instantaneous channel state information (CSI) since the eavesdroppers are assumed to be passive, the base station (BS) aims at securing communication between itself and legitimate users with the help of artificial noise (AN). In addition, the scheme transfers energy to the legitimate users. We provide necessary analysis and derivations for the achievable secrecy rates, energy transfer rates and outage probability at the legitimate non-cooperative far NOMA users. Several design parameters play different roles in maximizing the secrecy rates while meeting constraints on minimum outage probability and maximum transferred energy, such as cyclic-prefix (CP) length, time-switching (TS) factor between energy transfer and data transmission, power-splitting factor (PS), power-allocation factor between data signal and AN signal, PS factor between NOMA users under a desired outage probability at the legitimate users, and a desired average energy transfer rate constraints to maximize the secrecy rate between BS and legitimate NOMA users. We find the optimized values for these parameters through an exhaustive grid-based search. \subsection*{Notation} Lower and upper case bold letters denote vectors and matrices, respectively. $(\cdot)^\dagger$, $(\cdot)^*$, $\text{diag}\{\cdot\}$, $\text{Tr}\{\cdot\}$ and $||\cdot||_F$ denote transpose, Hermitian, diagonal, trace and the Frobenius norm of a matrix, respectively. $\boldsymbol{\mathrm{F}}$ is the FFT matrix, $\boldsymbol{\mathrm{F^*}}$ is the IFFT matrix. $\boldsymbol{\mathrm{I}}_N$ is the identity matrix with dimension $N \times N$. $\boldsymbol{\mathrm{0}}_{N_1 \times N_2}$ is the zero matrix with dimensions $N_1 \times N_2$. $\mathbb{R}^{N_1 \times N_2}$ is the set of real numbers with dimensions $N_1 \times N_2$ and $\mathbb{C}^{N_1 \times N_2}$ is the set of complex numbers with dimensions $N_1 \times N_2$. $\mathbb{E}\{.\}$ denotes the expectation. $\bar{\rho} = 1 - \rho$. $[\cdot]^+ = \max\{\cdot, 0\}$. $\mathcal{CN}(\cdot,\star)$ is a Gaussian distribution with `$\cdot$' mean and `$\star$' variance. \section{System Model} \begin{figure} \centering \includegraphics[width=1.65in]{sys_mdl.jpg} \caption{Network Topology.} \label{fig1} \end{figure} In our adopted system model, we assume a BS trying to secure communication between itself and multiple legitimate users in the presence of passive eavesdroppers (Eves), denoted as $e$, as depicted in Fig. \ref{fig1}. To this end, the users are categorized into two groups according to the radius of the disc they are located in and the BS is assumed to lie in the center of the discs. Without loss of generality, we assume two discs only, inner Disc $U$ with radius $r_u$ and Disc $G$ with inner radius $r_{g_1}$ and outer radius $r_{g_2}$. We assume that the spatial topology for both legitimate users and eavesdroppers is modeled according to Poisson point processes (PPP). The legitimate users are assumed to have reliable power supplies. It is also assumed that the legitimate users are EH nodes. Since the energy required for transmission is much higher than that required for processing of the received samples \cite{Nasir13}, to save energy at the near user, a non-cooperative NOMA transmission scheme is adopted between the BS and the legitimate users. The eavesdroppers are assumed to be located at least half wavelength apart from any legitimate user It is assumed that communication is carried out under OFDM scenario. We consider an OFDM symbol with total duration time $T$, which is composed of the CP time duration, denoted by $T_{\rm cp}$, and the time duration of the useful data signal, denoted by $T_s$. To this end, $T = N_t/f_s = N_{\rm cp}/f_s + N_s / f_s$, where $N_t = N_{\rm cp} + N_s$ is the total number of samples within one OFDM symbol, $N_{\rm cp}$ is the number of the samples within the CP, $N_s$ is the number of samples of the transmitted data signal, and $f_s$ is the sampling frequency. Under OFDM scheme, the available bandwidth is divided into $N_s$ orthogonal sub-channels. The wireless channels between BS and users are modeled as block-fading channels, which implies that the channel coefficients do not vary during the channel coherence time. The thermal noise at the receiving nodes is modeled as additive white Gaussian noise with zero mean and power $\sigma^2$. \section{Scheme Design and Analysis} The BS uses $N_s$-point inverse fast Fourier transform (IFFT) to convert the frequency-domain sub-channels into the time-domain. In addition, it appends a CP of length $N_{\rm cp}$ to the beginning of each OFDM symbol to prevent the inter-OFDM-symbol-interference across adjacent OFDM symbols. Along with the transmitted OFDM symbol, the BS transmits a time-domain AN signal by exploiting the temporal dimensions gained by the presence of the CP. As will be shown later, the AN is designed such that it is canceled out at the legitimate receivers prior to signal demodulation and retrieval of the transmitted data message. The BS splits its total available transmit power, $P_t$, between the data and AN signals. The power split factor is denoted by $0\le \rho \le 1$. The allocated power to the data signal is $\rho P_t$ and the allocated power to AN signal is $\bar{\rho} P_t$. BS transmits signals to two NOMA users selected from Discs $U$ and $G$, which are $u_i$ and $g_i$, respectively along with AN signal. Moving forward, we will drop the subscript for the users and use $u$ and $g$ to denote the users. The transmitted signal from BS is \begin{equation} \boldsymbol{\mathrm{x}} =\sqrt{\rho P_t}\boldsymbol{\mathrm{E_{\rm cp}F^*}}\boldsymbol{\mathrm{ S p}} + \sqrt{\bar{\rho}P_t} \boldsymbol{\mathrm{K w}}, \end{equation} \noindent where $\boldsymbol{\mathrm{x}} \in \mathbb{\mathbb{C}} ^{N_t \times 1}$, $\boldsymbol{\mathrm{E_{\rm cp}}} \in \mathbb{\mathbb{R}} ^{N_t \times N_s}$ is the CP insertion matrix, $\boldsymbol{\mathrm{S}}$ $ ~\in \mathbb{C} ^{N_s \times 2}$ contains the messages to be sent to the two NOMA users, $\boldsymbol{\mathrm{p}}= [\sqrt{\theta_u} \hspace{0.1in} \sqrt{\theta_g}]^\dagger$ is the vector that contains the assigned power factors for Users $u$ and $g$, respectively, $\boldsymbol{\mathrm{K}} \in \mathbb{C} ^{N_t \times N_{\rm cp}}$ is the AN precoding matrix and $\boldsymbol{\mathrm{w}} \in \mathbb{C} ^{N_{\rm cp} \times 1}$ is the AN vector. \begin{comment} \subsection{Selection of Active Sub-channels} Assuming that the channel gains of the links between the BS and the legitimate users in the frequency domain are ordered such that the sub-channel with the highest gain is denoted by $|H_1|^2$ and that with the lowest gain is $|H_N|^2$, we use Algorithm \ref{euclid2} below to determine the active OFDM sub-channels. The algorithm is realized using the total power assigned to data transmission given by $\rho P$. Assume the noise power at User $u$ is $\sigma^2_{\rm u}$, the algorithm is given in Algorithm 1. Similar Algorithm is done using channels of User $g$. \begin{algorithm} \caption{Active Sub-channels}\label{euclid2} \begin{algorithmic}[1] \State Initialize $\overline{N}=N_s$. \State Sort the instantaneous gains of all OFDM sub-channels. \State Compute $R=\frac{\rho P}{\overline{N}} +\frac{1}{\overline{N}} \sum_{k=1}^{\overline{N}} \frac{\sigma^2_{\rm u}}{|H_k|^2}$. \State Compute $E_k=R- \frac{\sigma^2_{\rm u}}{ |H_k|^2}$; $k=1,2,\cdots,\overline{N}$. \State If $E_k\le 0$, remove that sub-channel (should be one with highest index since it has lower gain and SNR). \State Set $N_{\rm old}=\overline{N}$. \State Set $N_{\rm new}=\overline{N}-\hbox{number of removed sub-channels}$. \State If $N_{\rm new} \ne N_{\rm old}$, $\overline{N}=N_{\rm new}$ and go back to step $(3)$. \State If $N_{\rm old} = N_{\rm new}$, $|\mathcal{A}|=N_{\rm new}$ and the active set $\mathcal{A}$ has been constructed. \end{algorithmic} \end{algorithm} \end{comment} The entire CP is used in analog domain to transfer energy to two NOMA Users, $u$ and $g$. Prior to processing and in time domain the rest of the OFDM symbol is divided into two portions. During the first portion, which has a duration $T_u = N_u/f_s$ and $T_g= N_g/f_s$ at Users $u$ and $g$, respectively, where $N_u$ and $N_g$ are the number of samples in the first portions at Users $u$ and $g$, respectively, the users use PS scheme, where a fraction of the received samples power is used for EH. For the remaining portion of the OFDM symbol, no PS is used and, hence, the entire second portion is used for data processing. The received signal at User $u$ is \begin{align} y_{i} = \begin{cases} c_u\sqrt{\beta_u \rho P_t}\left[\boldsymbol{\mathrm{ H_{{t}} E_{\rm cp} F^* S p }}\right]_i+ c_u \sqrt{\beta_u \bar{\rho}P_t}\left[\boldsymbol{\rm{H_{t} K w }}\right]_i\\ \quad +n_{u_{i}} \hspace{.75in} \text{for} \hspace{0.1in} i= N_{\rm cp}+1,\ldots, N_{u} +N_{\rm cp}\\ c_u \sqrt{\rho P_t}\left[\boldsymbol{\mathrm{ H_{{t}} E_{\rm cp} F^* S p }}\right]_i+ \sqrt{\bar{\rho} P_t}\hspace{0.in} c_u \left[\boldsymbol{\rm{H_{t} K w }}\right]_i \\ \quad + n_{u_{i}}, \hspace{0.7in} \text{for} \hspace{0.1in} i=N_{\rm cp}+N_u + 1,\ldots, N_s\\ \end{cases} \end{align} \noindent where $\beta_u$ is the power split factor during $T_u$, $c_u = \frac{1}{\sqrt{1+ d_u^\alpha}}$, $d_u$ is the distance between BS and $u$, $\alpha$ is the path loss exponent, $\boldsymbol{\mathrm{ H_t}}$ is the Toeplitz channel matrix between BS and $u$ with the impulse response of the channel as its first column, and $\bold{n}_u$ is noise at receiver $u$. Ditto, the received signal at User $g$ is \begin{equation} z_{i} = \begin{cases} c_g\sqrt{\beta_g \rho P_t}\left[\boldsymbol{\mathrm{ G_{{t}} E_{\rm cp} F^* S p }}\right]_i+ c_g \sqrt{\beta_g \bar{\rho}P_t}\left[\boldsymbol{\rm{G_{t} K w }}\right]_i \\ \quad+ n_{g_{i}} \hspace{.75in} \text{for} \hspace{0.1in} i= N_{\rm cp}+1,\ldots, N_{g}+ N_{\rm cp} \\ c_g \sqrt{\rho P_t}\left[\boldsymbol{\mathrm{ G_{{t}} E_{\rm cp} F^* S p }}\right]_i+ c_g \sqrt{\bar{\rho} P_t} \left[\boldsymbol{\rm{G_{t} K w }}\right]_i \\ \quad + n_{g_{i}}, \hspace{.7in} \text{for} \hspace{0.1in} i=N_{\rm cp}+N_g + 1,\ldots, N_s \end{cases} \end{equation} \noindent where $\beta_g$ is the power split factor during $T_g$, $c_g = \frac{1}{\sqrt{1+ d_g^\alpha}}$, $d_g$ is the distance between BS and $g$, $\boldsymbol{\mathrm{ G_t}}$ is the Toeplitz channel matrix between BS and $g$ and $\bold{n}_g$ is the AWGN at receiver $g$. Before processing the symbols at the receiver side, equalization is needed to remove the impact of power split. The received samples up to sample $N_{\rm cp}+N_u$ are now \begin{align} \tilde{y}_{i}&=y_{i}/\sqrt{\beta_u} \nonumber \\&= c_u \sqrt{\rho P_t} \left[\boldsymbol{\mathrm{ H_{{t}} E_{\rm cp} F^* S p }}\right]_i+ c_u \sqrt{\bar{\rho} P_t} \left[\boldsymbol{\rm{H_{t} K w }}\right]_i \nonumber\\ &\quad \quad \quad \quad + n_{u_{i}}/\sqrt{\beta_u}. \label{y_tilda} \end{align} \noindent Hence, the received vector at User $u$ is $\boldsymbol{\mathrm{y}} = [\tilde{y}_{1}, \tilde{y}_{2}, \ldots, \tilde{y}_{N_u}, y_{N_u+ N_{\rm cp}+ 1}, \ldots, y_{N_s}]^\dagger$. The CP is removed from the received signal at $u$ by multiplying by the CP removal matrix $\boldsymbol{\mathrm{\Phi}} \in \mathbb{\mathbb{R}} ^{N_s\times N_t}$. The outcome is then fed to the FFT block which yields \begin{align} \boldsymbol{\mathrm{ Fy}} \!=\! c_u \sqrt{\rho P_t}\boldsymbol{\mathrm{ F \Phi H_t E_{\rm cp} F^* S p}} &\!+\! c_u \sqrt{\bar{\rho} P_t}\boldsymbol{\mathrm{ F \Phi H_t K w}} \!+\!\bold{F}\boldsymbol{\mathrm{n_u}}, \label{eqn_y_fft} \end{align} \noindent where $\boldsymbol{\mathrm{n_u}} \in \mathbb{C} ^ {N_s \times 1}$ is the AWGN vector after CP removal. We will denote part of the first term in the left hand side of (\ref{eqn_y_fft}) by $\boldsymbol{\mathrm{H = F \Phi H_t E_{\rm cp} F^*}}$. Note that $\boldsymbol{\mathrm{H}} \in \mathbb{C} ^{N_s \times N_s}$ is a diagonal matrix, whose diagonal elements are the frequency domain channel coefficients between the BS and $u$. Similar steps are followed at $g$, which yields \begin{align} \boldsymbol{\mathrm{ Fz}} = c_g \sqrt{\rho P_t}\boldsymbol{\mathrm{ G S p}} +c_g \sqrt{\bar{\rho} P_t} \boldsymbol{\mathrm{ F \Phi G_t K w}} + \bold{F} \boldsymbol{\mathrm{n_g}}, \label{eqn_g_fft} \end{align} \noindent with $\boldsymbol{\mathrm{G = F \Phi G_t E_{\rm cp} F^*}}$ and $\boldsymbol{\mathrm{n_g}} \in \mathbb{C} ^ {N_s \times 1}$ is the AWGN vector after CP removal for User $g$. To remove the impact of AN at both legitimate users, the AN precoding matrix should satisfy \begin{align} \boldsymbol{\mathrm{\Phi \left(H_t + G_t\right) K}}= \boldsymbol{\mathrm{0}}_{N_s \times N_{\rm cp}} \label{eqn_null} \end{align} \noindent Since the rank of the matrix $\boldsymbol{\mathrm{\Phi \left(H_t + G_t\right)}}$ is $N_s$ and its number of columns is $N_t$, (\ref{eqn_null}) has a non-trivial solution and correspondingly $\boldsymbol{\mathrm{\Phi \left(H_t + G_t\right)}}$ has a non-trivial null space. Note that due to the equalization step applied in (\ref{y_tilda}), the noise variance for the first $N_u$ and $N_g$ samples increases. The average noise variance across all samples for Users $u$ and $g$ can be given by \begin{align} \small &\sigma_{a,u}^2 = \sigma^2 \left(\frac{ N_s-N_u +\frac{N_u}{\beta_u} }{N_s}\right), \label{sigma_ave1}\\ &\sigma_{a,g}^2 = \sigma^2 \left(\frac{ N_s-N_g +\frac{N_g}{\beta_g} }{N_s}\right).\label{sigma_ave2} \end{align} \subsection{Secrecy Rates} Both $u$ and $g$ are not impacted by AN signals by design. Under NOMA scheme, $u$ decodes and removes the message sent to User $g$. The achievable rate at $u$ is \begin{align} R_u = \frac{1}{N_t} {\log_2 \det{\left(\boldsymbol{\mathrm I}_{N_s}+{\frac{\rho \theta_u P_t}{N_t}\boldsymbol{\mathrm{H H^* \left(F\Lambda_u F^*\right)^{-1}}}}\right)} }, \label{R_u} \end{align} \noindent where $\boldsymbol{\mathrm \Lambda}_u = \frac{\sigma^2}{c_u^2} \text{diag} \{ \underbrace{{1}/{\beta_u}, {1}/{\beta_u} , \ldots, {1}/{\beta_u}}_{N_{u}}, 1, 1, \ldots, 1\} \in \mathbb{R} ^{N_s \times N_s}$. Under NOMA, User $g$ treats the signal assigned to User $u$ as noise and does not remove it from its received signal. Hence, the achievable rate at $g$ is \begin{align} R_g = \frac{1}{N_t} {\log_2 \det{\left(\boldsymbol{\mathrm I}_{N_s}+{\frac{\rho \theta_g P_t}{N_t}\boldsymbol{\mathrm{G G^* \left(F\Lambda_g F^*\right)^{-1}}}}\right)} }, \label{R_g} \end{align} \noindent where $\boldsymbol{\mathrm \Lambda}_g \in \mathbb{R} ^{N_s \times N_s}$ is given by $\boldsymbol{\mathrm \Lambda}_g \!=\! \left(\frac{\sigma^2}{c_g^2} \boldsymbol{\mathrm I}_{N_s} \!+\!\frac{ \rho \theta_u P_t \boldsymbol{\mathrm G} \boldsymbol{\mathrm G} ^ *}{N_t}\right) \text{diag} \{\! \underbrace{{1}/{\beta_g}, \cdots, {1}/{\beta_g}}_{N_{g}}, 1, \cdots, 1\!\}.$ There are few cases for the the achievable rate at Eve. First if Eve is interested in decoding either of the messages sent to $u$ or $g$. In this case, Eve considers the signal that she is not interested in as noise. If Eve is interested in decoding $u$'s message only, Eve's achievable rate in this case is given by \begin{equation} \begin{split} &R_{E,u} = \frac{1}{N_t} \log_2 \det \bigg( \boldsymbol{\mathrm I}_{N_s}+ \\& \frac{\rho \theta_u P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2 }{c_e^2} \boldsymbol{\mathrm I}_{N_s} +\frac{\rho \theta_g P_t \boldsymbol{\mathrm{VV^*}} }{N_t \right) ^{-1} \bigg), \end{split} \end{equation} \noindent where $\boldsymbol{\mathrm{V}}$ is a diagonal matrix with the frequency domain channel coefficients between BS and Eve as its diagonal and $\boldsymbol{\mathrm{D = F \Phi V_t K}}$, with $\boldsymbol{\mathrm{V_t}}$ being the Toeplitz channel matrix between BS and Eve. Note that the term $\frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}}$, which is the AN covariance matrix, represents the impact of AN at Eve. If Eve is interested in decoding $g$'s message only, Eve's achievable rate in this case is given by \begin{equation} \begin{split} &R_{E,g} = \frac{1}{N_t} \log_2 \det \bigg( \boldsymbol{\mathrm I}_{N_s}+ \\& \frac{\rho \theta_g P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2 }{c_e^2}\boldsymbol{\mathrm I}_{N_s} +\frac{\rho \theta_u P_t \boldsymbol{\mathrm{V V^*}}}{N_t \right) ^{-1} \bigg). \end{split} \end{equation} If Eve is interested in decoding both signals and employs a joint-typicality receiver, the secrecy rate can be given by \begin{equation} \begin{split} R_E = &\frac{1}{N_t} \log_2 \det \bigg( \boldsymbol{\mathrm I}_{N_s}+ \\& \frac{\rho P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2}{c_e^2} \boldsymbol{\mathrm I_{N_s}} \right) ^{-1} \bigg). \end{split} \end{equation} The secure transmission rate between BS and $u$ and $g$ following the previous cases can now be given by \begin{align} &R_{s,u} \leq [R_u-R_{E,u}]^+, \label{Rs1_u}\\ &R_{s,g} \leq [R_g-R_{E,g}]^+. \label{Rs1_g} \end{align} \begin{comment} \begin{equation} \begin{split} &R_{s,u} = [R_u-R_{E,u}]^+ \nonumber\\ &= \frac{1}{N_t} \bigg[{\log_2 \det{\left(\boldsymbol{\mathrm I_{N_s}}+{\frac{\rho \theta_u P_t}{N_t}\boldsymbol{\mathrm{H H^* \left(F\Lambda_u F^*\right)^{-1}}}}\right)} } - \nonumber \\ & \log_2 \det \bigg( \boldsymbol{\mathrm I}_{N_s}+ \\& \frac{\rho P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2 }{c_e^2} \boldsymbol{\mathrm I}_{N_s} +\frac{\rho \theta_g P_t \boldsymbol{\mathrm{VV^*}} }{N_t \right) ^{-1} \bigg) \bigg]^+.\label{Rs1_u} \end{split} \end{equation} \end{comment} \begin{comment} \begin{align} &R_{s_2,u} = [R_u-R_E]^+ \nonumber\\ &= \frac{1}{N_t} \bigg[{\log_2 \det{\left(\boldsymbol{\mathrm I_{N_s}}+{\frac{\rho \theta_u P_t}{N_t}\boldsymbol{\mathrm{H H^* \left(F\Lambda_u F^*\right)^{-1}}}}\right)} } - \nonumber \\ &\log_2 \det \left( \boldsymbol{\mathrm I_{N_s}}+ \frac{\rho P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2}{c_e} \boldsymbol{\mathrm I_{N_s}} \right) ^{-1} \right) \bigg]^+. \end{align} \begin{align} &R_{s_1,g} = [R_g-R_{E,g}]^+ \nonumber\\ &= \frac{1}{N_t}\bigg[ {\log_2 \det{\left(\boldsymbol{\mathrm I_{N_s}}+{\frac{\rho \theta_g P_t}{N_t}\boldsymbol{\mathrm{G G^* \left(F\Lambda_g F^*\right)^{-1}}}}\right)} } - \nonumber \\ &\log_2 \det \bigg( \boldsymbol{\mathrm I}_{N_s}+ \nonumber\\& \frac{\rho P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2 }{c_e^2}\boldsymbol{\mathrm I}_{N_s} +\frac{\rho \theta_u P_t \boldsymbol{\mathrm{V V^*}}}{N_t \right) ^{-1} \bigg) \bigg]^+. \label{Rs1_g} \end{align} \begin{align} &R_{s_2,g} = [R_g-R_E]^+ \nonumber\\ &= \frac{1}{N_t} \bigg[{\log_2 \det{\left(\boldsymbol{\mathrm I_{N_s}}+{\frac{\rho \theta_g P_t}{N_t}\boldsymbol{\mathrm{G G^* \left(F\Lambda_g F^*\right)^{-1}}}}\right)} } - \nonumber \\ & \log_2 \det \left( \boldsymbol{\mathrm I_{N_s}}+ \frac{\rho P_t}{N_t}\boldsymbol{\mathrm{V V^*}} \left( \frac{\bar{\rho} P_t}{N_{\rm cp}}\boldsymbol{\mathrm {D D^*}} + \frac{\sigma^2}{c_e^2} \boldsymbol{\mathrm I_{N_s}} \right) ^{-1} \right) \bigg]^+. \end{align} \end{comment} \noindent The sum secrecy rate is upper-bounded by \cite{Tekin08} \begin{align} R_{s,u} + R_{s,g} \leq \left[R_u + R_g - R_E\right]^+. \label{R_sum} \end{align} The rate pair ($R_{s,u} ,~ R_{s,g}$) should satisfy (\ref{Rs1_u}), (\ref{Rs1_g}) and (\ref{R_sum}). \subsection{Outage Probability} The outage probability for $u$, $P_{o,u}$, comprises the probability that $u$ cannot detect the signal sent to $g$ and the probability that $u$ can detect the message sent to $g$ but cannot detect the message sent to itself. This is given as \begin{align} \small P_{o,u} =& \Pr\left\{c_u^2||\boldsymbol{\mathrm{H}}||_F^2 < \vartheta_{\{g,u\}} \right\} \nonumber \\ &+ \Pr\left\{c_u^2||\boldsymbol{\mathrm{H}}||_F^2 > \vartheta_{\{g,u\}}, \vartheta_{\{g,u\}} < \vartheta_{\{u,u\}} \right\}, \end{align} \noindent where $\vartheta_{\{g,u\}} = \frac{\delta_1 \sigma_{a,u}^2}{ \rho P_t \left( \theta_g - \theta_u \delta_1 \right)}$, $\vartheta_{\{u,u\}} = \frac{\delta_2 \sigma_{a,u}^2}{ \rho \theta_u P_t}$, with $\delta_1$ satisfies $\theta_g - \delta_1 \theta_u > 0$ \cite{Ding2014} and $\delta_2 = 2^{(2\delta_3)} - 1$, where $\delta_3$ is the desired rate at which $u$ can detect the message sent to itself. Hence, with the help of the results provided in \cite{Liu2016} under the assumption that the spatial topology for the users is modeled through PPP, the approximate outage probability at User $u$ per sub-channel can be given by \begin{equation} \small P_{o,u} \approx \begin{cases} \begin{split} &\frac{\pi}{2L} \sum_{l=1}^{L}\sqrt{1-\cos^2{\left(\frac{2 l - 1}{2L} \pi\right)}} \times \\ &\left( 1 - \exp\left(- n_l \vartheta_{\{g,u\}} \right)\right) \times \left(1+ \cos{\left(\frac{2 l - 1}{2L} \pi\right)}\right), \\& \hspace{1.72in} \text{for} \quad \vartheta_{\{g,u\}} \geq \vartheta_{\{u,u\}} \end{split} \\ 1 \hspace{1.65in} \text{for} \quad \vartheta_{\{g,u\}} < \vartheta_{\{u,u\}} \end{cases} \end{equation} \noindent where $n_l = 1 + \left(\frac{r_u}{2}\left(1+\cos{\left(\frac{2 l - 1}{2L} \pi\right)}\right)\right)^\alpha$, and $L$ is a design parameter used for complexity-accuracy tradeoff. The outage probability for $g$, denoted by $P_{o,g}$, can be given by \begin{align} P_{o,g} = \Pr\left\{c_g^2||\boldsymbol{\mathrm{G}}||_F^2 < \vartheta_{\{g,g\}}\right\}, \end{align} \noindent where $\vartheta_{\{g,g\}} = \frac{\delta_1 \sigma_{a,g}^2}{\rho P_t \left(\theta_g - \theta_u \delta_1\right)}$. We extend the derivation provided in \cite{Liu2016} for cooperative NOMA to our non-cooperative NOMA model and, hence, the approximate outage probability for User $g$ per sub-channel can be given by \begin{equation} \begin{split} P_{o,g}& \approx \frac{\pi}{M\left(r_{g_2}+r_{g_1}\right)} \sum_{m=1}^{M}\sqrt{1-\cos^2{\left(\frac{2 m - 1}{2M} \pi\right)}}\\ &n_m \times \left( 1 - \exp\left(- \left( 1 + n_m^\alpha \right)\vartheta_{\{g,g\}} \right)\right) \\ \end{split} \end{equation} \noindent where $n_m = \frac{\Delta_{r_g}}{2}\left(1+ \cos{\left(\frac{2 m - 1}{2M} \pi\right)}\right) +r_{g_1}$, $\Delta_{r_g} = r_{g_2} - r_{g_1}$ and $M$ is a design parameter used for complexity-accuracy tradeoff. \subsection{Harvested Energy}The energy harvested at both users comprises of two portions. The first portion is from the CP signal, which is \begin{equation} \boldsymbol{\mathrm{\upsilon }}_u=c_u \boldsymbol{\mathrm{A_{\rm cp} H_t }}\left(\sqrt{\rho P_t}\boldsymbol{\mathrm{E_{\rm cp}F^*}}\boldsymbol{\mathrm{ S p}} + \sqrt{\bar{\rho} P_t}\boldsymbol{\mathrm{K w}}\right), \end{equation} \noindent for User $u$ and defined similarly for User $g$ as \begin{equation} \boldsymbol{\mathrm{\upsilon }}_g= c_g\boldsymbol{\mathrm{A_{\rm cp} G_t}}\left(\sqrt{\rho P_t}\boldsymbol{\mathrm{E_{\rm cp}F^*}}\boldsymbol{\mathrm{ S p}} + \sqrt{\bar{\rho} P_t}\boldsymbol{\mathrm{K w}}\right), \end{equation} \noindent where $\boldsymbol{\mathrm{A_{\rm cp}}} = \left[\boldsymbol{\mathrm{I}}_{N_{\rm cp}} \quad \boldsymbol{\mathrm{0}}_{N_{\rm cp} \times N_s}\right] \in \mathbb{R} ^{N_{\rm cp} \times N}$ is the CP extraction matrix. The harvested energy during CP is then \begin{align} \small E_{1,u} &= \nonumber\\ & \eta P_t T_{\rm cp} c_u^2 \text{Tr} \bigg\{\boldsymbol{\mathrm{A_{\rm cp} H_t}}\bigg( \frac{\rho\boldsymbol{\mathrm{E_{\rm cp} E_{\rm cp}^*}}}{N_t} + \frac{\bar{\rho}\boldsymbol{\mathrm{K K^*}}}{N_{\rm cp}}\bigg)\boldsymbol{\mathrm{H_t^* A^*_{\rm cp}}} \bigg\}, \end{align} \begin{align} \small E_{1,g} &= \nonumber \\& \eta P_t T_{\rm cp} c_g^2 \text{Tr} \left\{\boldsymbol{\mathrm{A_{\rm cp} G_t}}\left( \frac{\rho\boldsymbol{\mathrm{E_{\rm cp} E_{\rm cp}^*}}}{N_t} + \frac{\bar{\rho}\boldsymbol{\mathrm{K K^*}}}{N_{\rm cp}}\right)\boldsymbol{\mathrm{G_t^* A^*_{\rm cp}}} \right\}, \end{align} \noindent where $0\le \eta \le 1$ is the efficiency factor of the RF energy conversion process at the energy harvester circuit. The second portion of the energy is harvested from $N_u$ and $N_g$ samples after CP and can be given by \begin{equation} \small E_{2,u} = \frac{\eta c_u^2 \rho \bar{\beta_u} P_t N_u T_s }{N_t} \text{Tr}\bigg\{ \boldsymbol{\mathrm{A_{N_u}\Phi H_t E_{\rm cp}}} \left( \boldsymbol{\mathrm{A_{N_u}\Phi H_t E_{\rm cp}}} \right)^*\bigg\} \end{equation} \begin{equation} \small E_{2,g} = \frac{\eta c_g^2\rho \bar{\beta_g} P_t N_g T_s }{N_t} \text{Tr}\bigg\{ \boldsymbol{\mathrm{A_{N_g}\Phi G_t E_{\rm cp}}} \left( \boldsymbol{\mathrm{A_{N_g}\Phi G_t E_{\rm cp}}} \right)^*\bigg\} \end{equation} where $\boldsymbol{\mathrm{A_{N_u}}} = \left[\boldsymbol{\mathrm{I}}_{N_{u}} \quad \boldsymbol{\mathrm{0}}_{N_{u} \times (N_s - N_u)}\right] \in \mathbb{R} ^{N_{u} \times N_s}$ is the $N_u$ samples extraction matrix and $\boldsymbol{\mathrm{A_{N_g}}} = \left[\boldsymbol{\mathrm{I}}_{N_{g}} \quad \boldsymbol{\mathrm{0}}_{N_{g} \times (N_s - N_g)}\right] \in \mathbb{R} ^{N_{g} \times N_s}$ is the $N_g$ samples extraction matrix. The total energy at $u$ and $g$ can be given by \begin{align} E_u = E_{1,u} + E_{2,u}, \ E_g = E_{1,g} + E_{2,g}. \end{align} \subsection{Optimization Problem} We optimize the minimum average secrecy rate of Users $u$ and $g$ according to \begin{equation} \begin{split} \max_{\beta_u, \beta_g, \rho, \theta_u, \theta_g, N_u, N_g, N_{\rm cp}}: \min \left\{\mathbb{E} \left\{R_{s,u} \right\}, \mathbb{E} \left\{R_{s,g} \right\}\right\},\\ \text{s.t.} \quad \mathbb{E} \left\{E_u\right\} \geq \mu_u, \quad \mathbb{E} \left\{E_g\right\} \geq \mu_g, \\ P_{o,u} \leq \epsilon_u, \quad P_{o,g} \leq \epsilon_g, \\ 0 \leq \beta_u, \beta_g, \rho, \theta_u, \theta_g \leq 1, \\ N_u, N_g \in \left\{0, 1, 2, \ldots, N_s \right\}, \\ \tau \leq N_{\rm cp}/f_s \leq N_s/f_s, \end{split} \label{eqn_opt} \end{equation} \noindent where $\mu_u \geq 0$ and $\mu_g \geq$ are the desired average energy harvested rates at Users $u$ and $g$, respectively, $0\leq \delta_u \leq 1$ and $0\leq \delta_g \leq 1$ are the desired outage probability at Users $u$ and $g$, respectively, and $\tau = \max \{\tau_u,\tau_g\}$ with $\tau_u$, $\tau_g$ are the delay spreads between BS and Users $u$ and $g$, respectively. \noindent \textbf{Some Remarks on Eqn. (\ref{eqn_opt}):} There are some tradeoffs in (\ref{eqn_opt}) as follows \begin{itemize} \item As $N_u$ and $N_g$ increase, the harvested energy at Users $u$ and $g$ increase. However, as can be seen from Eqns. (\ref{sigma_ave1}) and (\ref{sigma_ave2}), $\sigma_{a,u}^2, \sigma_{a,g} ^2 \geq \sigma^2$, i.e., the average noise variance increases as $N_u$ and $N_g$ increase, which implies lower SNR at users. Each user can adjust its split samples, i.e., $N_u$ or $N_g$, based on its needs. Similar remarks can be stated for $\beta_u$ and $\beta_g$. \item As $\rho$ increases, SNR at the users increases. However, this means that less power is dedicated to AN which will also increase the SNR at the eavesdropper and, hence, reduce the secrecy rate. \item The NOMA power split factor should satisfy $\theta_u < \theta_g$ and $\theta_u +\theta_g = 1$ while as $\theta_u$ increases, the SNR and hence the rate at User $u$ increases, however, the SINR and hence the rate at User $g$ decreases as can be seen from Eqns. (\ref{R_u}) and (\ref{R_g}). \end{itemize} Due to the non-convexity of the objective function and the constraints, the optimization problem in (\ref{eqn_opt}) is not convex and hence it can solved offline using Matlab’s fmincon function or multi-dimensional grid-based search over the optimization variables and then the feasible set optimal values get communicated to both NOMA Users $u$ and $g$ before operation. The optimization problem is solved through an exhaustive grid-based search at the BS, which is also known as brute force solution\footnote{The associated complexity can be reduced by using alternative computationally-efficient methods such as the interior-point methods \cite[Chapter 11]{resp8} which are used by the fmincon function in Matlab. Devising a more efficient method to solve the non-convex optimization problem in (\ref{eqn_opt}) is out of the scope of this paper. We shall investigate that in our future work.}. Under the transmission parameters such as $N_t$ and $N_{cp}$, the BS calculates $R_{s,u}$, $R_{s,g}$ ,$P_{o,u}$, $P_{o,g}$, for all feasible sets of the optimization parameters. The BS then selects the values that maximize the minimum secrecy rates between itself and $u$ and $g$, while meeting constraints on $E_u$, $E_g$, $P_{o,u}$ and $P_{o,g}$. The calculated optimal values should remain the same as long as the system’s average parameters including required $\mathbb{E} \left\{E_u\right\}$, $\mathbb{E} \left\{E_g\right\}$, $\mathbb{E} \{P_{o,u}\}$, $\mathbb{E} \{P_{o,g}\}$ and average channel gains remain the same. The optimization problem does not require knowledge of eavesdroppers' instantaneous CSI. Only statistics are required to be estimated. \section{Simulation Results} We conduct our OFDM-based NOMA SWIPT system simulation using Rayleigh fading channel realizations that follow $\mathcal{CN}(0,1)$. Independent channel realizations are generated for each user and for the eavesdropper. The rest of the simulation parameters are $\sigma^2 = 1$ Watt, $N_t = 64$, $N_{\rm cp} = 16$, $f_s = 2$ MHz, $r_u = 8$ meters, $r_{g_1} = 10$ meters, $r_{g_2} = 14$ meters, $d_u = 4$ meters, $d_g = 12$ meters, $d_e = 10$ meters, $\eta = 0.75$, and $\alpha = 2$. The calculated ranges for SNR at $g$ and $u$ across all variations of $N_g$, $\beta_g$, $\theta_g$, $\theta_u$, $\rho$ are $\in[0:13]$ dB and $\in[27:45]$ dB, respectively. Due to limited available space, we present more results for $g$ since it is the far user operating under non-cooperative NOMA. Moreover, we simulate for fixed $N_u = 16$ and $\beta_u = 0.5$, however, similar conclusions for varying these two parameters are analogous to varying $N_g$ and $\beta_g$. The optimized values are estimated through an exhaustive grid-based search operation at the BS. We present these values at the end of the section. In the following figures, we show the impact of varying the optimization parameters on the performance of the system. Fig. \ref{sec_rates} presents the simulated average secrecy rates. Fig. \ref{outage_probs} presents the simulated outage probabilities. Fig. \ref{harvested_energy} presents the simulated harvested energy. In Figs. \ref{sec_rates} to \ref{harvested_energy}, we have (a) average parameter for $u$ versus $\rho$ for different $\theta_g$ values (b) average parameter for $g$ versus $\rho$ for different $\theta_g$ values, $N_g = 24$ and $\beta_g= 0.5$ (c) average parameter for $g$ versus $\beta_g$ for different $\rho$ values, $N_g = 24$ and $\theta_g= 0.75$ and (d) average parameter for $g$ versus $N_g$ for different $\rho$ values, $\theta_g = 0.75$ and $\beta_g= 0.5$. Note that changing $\theta_g$ changes $\theta_u$ since $\theta_u = 1-\theta_g$. As shown in Fig. \ref{sec_rates} (a) as $\rho$ increases or $\theta_g$ decreases, the SNR at $u$ increases and hence $\mathbb{E}\{R_{s,u}\}$ increases. However since $g$ considers $u$'s signal as noise, as $\rho$ increases, the noise variance increases and hence $\mathbb{E}\{R_{s,g}\}$ decreases as shown in Fig. \ref{sec_rates} (b). Unlike $u$ as $\theta_g$ increases, the desired signal power at $g$ increases, which improves SNR and consequently $\mathbb{E}\{R_{s,g}\}$. As shown in Fig. \ref{sec_rates} (c) as $\beta_g$ increases, higher power factor is allocated for signal decoding rather than energy harvesting, which improves SNR as follows from the definition of $\Lambda_g$ and, hence, improves $\mathbb{E}\{R_{s,g}\}$. $N_g$ does not have much impact on $\mathbb{E}\{R_{s,g}\}$. Note that the upper bound (UB) in (\ref{R_sum}) is satisfied. \begin{figure} \centering \includegraphics[width=3.8in]{sec_rates2.pdf} \caption{Average secrecy rates: (a) $\mathbb{E}\{R_{s,u}\}$ and UBs, (b) $\mathbb{E}\{R_{s,g}\}$ vs. $\rho$, (c) $\mathbb{E}\{R_{s,g}\}$ vs. $\beta_g$ and (d) $\mathbb{E}\{R_{s,g}\}$ vs. $N_g$.} \label{sec_rates} \end{figure} One key finding in Fig. \ref{outage_probs} (a) is that very low values of $\theta_u$, for example $0.05$, i.e., when $\theta_g= 0.95$, might lead to $P_{o,u} =1$. To achieve a desired $\epsilon_u \leq 10^{-4}$, $\rho$ can be $\in[0.05:0.95]$ and $\theta_g \in [0.55 : 0.9]$. As can be inferred from Fig. \ref{outage_probs} (b) to (d) to achieve a desired $\epsilon_g \leq 10^{-4}$, $\rho$ can be $\in[0.2:0.95]$, $\theta_g \in [0.55 : 0.9]$, $\beta_g \in [0.05 : 0.95]$, and $N_g \in[12:N_s]$. As expected, the harvested energy at $u$ is much higher than that at the far User $g$. To achieve a desired $\mu_u \geq 10$ joules, $\rho$ should be $\in[0.5:0.95]$ as shown in Fig. \ref{harvested_energy} (a). Note that since the energy is harvested at $u$ before cancelling User $g$'s signal, changing $\theta_g$ does not have an impact on $\mathbb{E}\{E_u\}$. As can be seen in Fig. \ref{harvested_energy} (b) to (d), to achieve $\mu_g \geq 1$ joule, $\rho$ should be $\in[0.65:0.95]$, $\beta_g$ should be $\in[0.55:0.95]$ and $N_g$ should be $\in [16:N_s]$. $N_g$ has the most impact on the harvested energy at $g$. \begin{figure} \centering \includegraphics[width=3.8in]{Outage_prob.pdf} \caption{Outage probabilities: (a) $P_{o,u}$ vs. $\rho$, (b) $P_{o,g}$ vs. $\rho$, (c) $P_{o,g}$ vs. $\beta_g$ and (d) $P_{o,g}$ vs. $N_g$.} \label{outage_probs} \end{figure} Following the exhaustive grid-based search operation, the optimal results under our simulation parameters are $\rho = 0.75$, $\theta_g = 0.75$, $\beta_g = 0.85$ and $N_g = 32$. The reader can infer these values from and the explanatory plots in Figs. \ref{sec_rates} to \ref{harvested_energy}. The achieved maximized $\mathbb{E}\{R_{s,u}\} = 4 $ bits/sec/Hz and $\mathbb{E}\{R_{s,g}\} = 0.7$ bits/sec/Hz while meeting the constraints on $P_{o,u} \leq 10^{-4}$, $P_{o,g} \leq 10^{-4}$, $\mathbb{E}\{E_{u}\} \geq 10$ joules and $\mathbb{E}\{E_{g}\} \geq 1$ joule. \begin{figure} \centering \includegraphics[width=3.8in]{harvested_energy.pdf} \caption{Average harvested energy: (a) $\mathbb{E}\{E_{u}\}$ vs. $\rho$, (b) $\mathbb{E}\{E_{g}\}$ vs. $\rho$, (c) $\mathbb{E}\{E_{g}\}$ vs. $\beta_g$ and (d) $\mathbb{E}\{E_{g}\}$ vs. $N_g$.} \label{harvested_energy} \end{figure} \section{Conclusion} We presented an AN aided physical-layer security scheme for energy harvesting nodes operating under OFDM-based non-cooperative NOMA scheme. We showed that, with optimal choice of design parameters, it is possible to secure the considered system while transferring energy to multiple nodes under minimum outage probability constraints at legitimate users. \bibliographystyle{IEEEtran}
{'timestamp': '2020-08-18T02:21:46', 'yymm': '2008', 'arxiv_id': '2008.07039', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07039'}
arxiv
\section{Introduction} Many engineering and scientific applications involve making design choices to optimize multiple objectives. A representative example includes designing new materials to optimize strength, elasticity, and durability. There are three challenges in solving these kind of optimization problems: {\bf 1)} The objective functions are unknown and we need to perform expensive experiments to evaluate each candidate design. For example, performing physical lab experiments for material design application. {\bf 2)} The objectives are conflicting in nature and all of them cannot be optimized simultaneously. {\bf 3)} The designs that are part of the solution should satisfy a set of constraints. Therefore, we need to find the {\em Pareto optimal} set of solutions satisfying the constraints. A solution is called Pareto optimal if it cannot be improved in any of the objectives without compromising some other objective. The overall goal is to approximate the true Pareto set satisfying the constraints while minimizing the number of function evaluations. Bayesian Optimization (BO) (\cite{shahriari2016taking}) is an effective framework to solve blackbox optimization problems with expensive function evaluations. The key idea behind BO is to build a cheap surrogate model (e.g., Gaussian Process (\cite{williams2006gaussian})) using the real experimental evaluations; and employ it to intelligently select the sequence of function evaluations using an acquisition function, e.g., expected improvement (EI). There is a large body of literature on single-objective BO algorithms (\cite{shahriari2016taking,BOCS,PSR,DBO}) and their applications including hyper-parameter tuning of machine learning methods (\cite{snoek2012practical,kotthoff2017auto}). However, there is relatively less work on the more challenging problem of BO for multiple objectives (\cite{knowles2006parego,emmerich2008computation,hernandez2016predictive,MESMO,USEMO}) and very limited prior methods to address constrained MO problems (\cite{garrido2019predictive,feliot2017bayesian}). PESMOC (\cite{garrido2019predictive}) is a state-of-the-art approach that relies on the principle of input space entropy search. However, it is computationally expensive to optimize the acquisition function behind PESMOC. A series of approximations are performed to improve the efficiency potentially at the expense of accuracy. In this paper, we propose a novel {\bf U}ncertainty-aware {\bf Se}arch framework for {\bf M}ultiple {\bf O}bjectives optimizing with {\bf C}onstraints (USeMOC) to overcome the drawbacks of prior methods. The key insight is to improve uncertainty management via a two-stage search procedure to select candidate inputs for evaluation. First, it solves a cheap constrained MO optimization problem defined in terms of the acquisition functions (one for each unknown objective) to identify a list of promising candidates. Second, it selects the best candidate from this list based on a measure of uncertainty. We demonstrate the efficacy of USeMOC over prior methods using a real-world application from the domain of analog circuit design via expensive simulations. \section{Background and Problem Setup} \noindent {\bf Bayesian Optimization Framework.} Let $\mathcal{X} \subseteq \Re^d$ be an input space. We assume an unknown real-valued objective function $F: \mathcal{X} \mapsto \Re$, which can evaluate each input $x \in \mathcal{X}$ to produce an evaluation $y$ = $F(x)$. Each evaluation $F(x)$ is expensive in terms of the consumed resources. The main goal is to find an input $x^* \in \mathcal{X}$ that approximately optimizes $F$ via a limited number of function evaluations. BO algorithms learn a cheap surrogate model from training data obtained from past function evaluations. They intelligently select the next input for evaluation by trading-off exploration and exploitation to quickly direct the search towards optimal inputs. The three key elements of BO framework are: {\bf 1) Statistical Model} of $F(x)$. {\em Gaussian Process (GP)} (\cite{williams2006gaussian}) is the most commonly used model. A GP over a space $\mathcal{X}$ is a random process from $\mathcal{X}$ to $\Re$. It is characterized by a mean function $\mu : \mathcal{X} \times \mathcal{X} \mapsto \Re$ and a covariance or kernel function $\kappa$. If a function $F$ is sampled from GP($\mu$, $\kappa$), then $F(x)$ is distributed normally $\mathcal{N}(\mu(x), \kappa(x,x))$ for a finite set of inputs from $x \in \mathcal{X}$. {\bf 2) Acquisition Function} (\textsc{Af}) to score the utility of evaluating a candidate input $x \in \mathcal{X}$ based on the statistical model. Some popular acquisition functions include expected improvement (EI), upper confidence bound (UCB) and lower confidence bound (LCB). For the sake of completeness, we formally define the acquisition functions employed in this work noting that any other acquisition function can be employed within USeMOC. \begin{align} & UCB(x)=\mu(x)+\beta^{1/2} \sigma(x) \\\label{ucbeq} & LCB(x)=\mu(x)-\beta^{1/2} \sigma(x)\\\label{lcbeq} & EI(x)= \sigma(x)(\alpha\Phi(\alpha)+\phi(\alpha)) , ~ \alpha=\frac{\tau-\mu(x)}{\sigma(x)} \end{align} where $\mu(x)$ and $\sigma(x)$ correspond to the mean and standard deviation of the prediction from statistical model, $\beta$ is a parameter that balances exploration and exploitation; $\tau$ is the best uncovered input; and $\Phi$ and $\phi$ are the CDF and PDF of normal distribution respectively. {\bf 3) Optimization Procedure} to select the best scoring candidate input according to \textsc{Af} via statistical model, e.g., DIRECT (\cite{jones1993lipschitzian}). \vspace{1.0ex} \noindent {\bf Multi-Objective Optimization (MOO) Problem with Constraints.} Without loss of generality, our goal is to minimize $k \geq 2$ real-valued objective functions $F_1(x), F_2(x),\cdots,F_k(x)$ while satisfying $L$ constraints $C_1(x), C_2(x),\cdots,C_L(x)$ over continuous space $X \subseteq \Re^d$. Each evaluation of an input $x \in \mathcal{X}$ produces a vector of objective values $Y$ = $(y_1, y_2,\cdots,y_k)$ where $y_i$ = $F_i(x)$ for all $i \in \{1,2, \cdots, k\}$ and a vector of constraints values $C$ = $(c_1, c_2,\cdots,c_L)$ where $c_i$ = $C_i(x)$ for all $i \in \{1,2, \cdots, L\}$. Constraints in real world problems usually take one of the following three forms: \textbf{[Type 1]} $C_i$ is a function of the input $x$ and can be expressed declaratively (i.e., white-box constraint); \textbf{[Type 2]} $C_i$ is black-box constraint; and \textbf{[Type 3]} $C_i$ is a function of both the input $x$ and a combination of the black-box objective functions. We say that a point $x$ {\em Pareto-dominates} another point $x'$ if $F_i(x) \leq F_i(x') \hspace{1mm} \forall{i}$ and there exists some $j \in \{1, 2, \cdots,k\}$ such that $F_j(x) < F_j(x')$. The optimal solution of constrained MOO problem is a set of points $\mathcal{X}^* \subset \mathcal{X}$ such that no point $x' \in \mathcal{X} \setminus \mathcal{X}^*$ Pareto-dominates a point $x \in \mathcal{X}^*$ and all points in $\mathcal{X}^*$ satisfies the problem constraints. The solution set $\mathcal{X}^*$ is called the Pareto set and the corresponding set of function values is called the Pareto front. Our goal is to approximate $\mathcal{X}^*$ while minimizing the number of function evaluations. \section{Uncertainty-Aware Search Framework} \label{section4} In this section, we provide the details of USeMOC framework for solving constrained multi-objective optimization problems. First, we provide an overview of USeMOC followed by the details of its two main components. \subsection{Overview of USeMOC Framework} USeMOC is an iterative algorithm that involves four key steps. First, We build statistical models $\mathcal{M}_1, \mathcal{M}_2,\cdots,\mathcal{M}_k$ for each of the $k$ objective functions from the training data in the form of past function evaluations. Second, we select a set of promising candidate inputs $\mathcal{X}_p$ by solving a constrained cheap MO optimization problem defined using the statistical models. Specifically, multiple objectives of the cheap MO problem correspond to $\textsc{Af}(\mathcal{M}_1,x), \textsc{Af}(\mathcal{M}_2,x),\cdots, \textsc{Af}(\mathcal{M}_k,x)$ respectively. Any standard acquisition function \textsc{Af} from single-objective BO (e.g., EI, LCB) can be used for this purpose. Additionally, if the constraint is black-box, it is modeled by a GP $\mathcal{M}_{c_i}$ and its predictive mean $\mu_{c_i}(x)$ is used instead for reasoning. If the value of a constraint $C_i$ depends on the evaluation of one (or more) objectives $F_i(x)$, we employ the predictive mean $\mu_i(x)$. The Pareto set $\mathcal{X}_p$ corresponds to the inputs with different trade-offs in the utility space for $k$ unknown functions satisfying the constraints. Third, we select the best candidate input $x_s \in \mathcal{X}_p$ from the Pareto set that maximizes some form of uncertainty measure for evaluation. Fourth, the selected input $x_s$ is used for evaluation to get the corresponding function evaluations: $y_1$=$F_1(x_s)$, $y_2$=$F_2(x_s)$,$\cdots$,$y_k$=$F_k(x_s)$. Algorithm~\ref{alg:USeMO} provides the algorithmic pseudocode for USeMOC. \begin{algorithm}[h] \caption{USeMOC Framework} \label{alg:USeMO} \textbf{Input}: $\mathcal{X}$, input space; $F_1(x), F_2(x),\cdots,F_k(x)$, $k$ blackbox objective functions; \textsc{Af}, acquisition function; and $T_{max}$, maximum no. of iterations \begin{algorithmic}[1] \STATE Initialize training data of function evaluations $\mathcal{D}$ \STATE Initialize statistical models $\mathcal{M}_1, \cdots, \mathcal{M}_k,,\mathcal{M}_{C_0},\cdots, \mathcal{M}_{C_{m}}$ from $\mathcal{D}$ \FOR{each iteration $t$=1 to $T_{max}$} \STATE // Solve constrained cheap MO problem with objectives \textsc{Af}$(\mathcal{M}_1,x),\cdots, \textsc{Af}(\mathcal{M}_k,x)$ to get candidate inputs \STATE $\mathcal{X}_{p} \leftarrow \arg min_{x \in \mathcal{X}} (\textsc{Af}(\mathcal{M}_1,x),\cdots, \textsc{Af}(\mathcal{M}_k,x))$ \\ \qquad \qquad \textbf{s.t} $\mu_{c_0},\cdots,\mu_{c_m},C_{m+1}\cdots, C_L$ \STATE // Pick the candidate input with maximum uncertainty \STATE Select $x_{t+1} \leftarrow \arg max_{x\in \mathcal{X}_{p}} \; U_{\beta_t}(x)$ \STATE Evaluate $x_{t+1}$: $Y_{t+1} \leftarrow (F_1(x_{t+1}),\cdots,F_k(x_{t+1}))$, $C_{t+1} \leftarrow (C_0(x_{t+1}),\cdots,C_L(x_{t+1}))$ \STATE Aggregate data: $\mathcal{D} \leftarrow \mathcal{D} \cup \{(x_{t+1}, Y_{t+1}, C_{t+1})\}$ \STATE Update models $\mathcal{M}_1,\cdots, \mathcal{M}_k,\mathcal{M}_{C_0},\cdots, \mathcal{M}_{C_{m}}$ using $\mathcal{D}$ \STATE $t \leftarrow t+1$ \ENDFOR \STATE \textbf{return} Pareto set and Pareto front of $\mathcal{D}$ \end{algorithmic} \end{algorithm} \vspace{0.8ex} \noindent {\bf Advantages.} USeMOC has many advantages over prior methods. {\bf 1)} Provides flexibility to plug-in any acquisition function for single-objective BO. This allows us to leverage existing acquisition functions including EI and LCB. {\bf 2)} Computationally-efficient to solve constrained MO problems with many objectives. {\bf 3)} Can handle all three types of constraints (i.e., type 1, type 2, and type 3). \subsection{Key Algorithmic Components of USeMOC} The two main algorithmic components of USeMOC framework are: selecting most promising candidate inputs by solving a cheap constrained MO problem and picking the best candidate via uncertainty maximization. We describe their details below. \vspace{0.8ex} \noindent {\bf Selection of promising candidates.} We employ the statistical models $\mathcal{M}_1, \mathcal{M}_2,\cdots, \mathcal{M}_k$ towards the goal of selecting promising candidate inputs as follows. Given an acquisition function \textsc{Af} (e.g., EI), we construct a constrained cheap multi-objective optimization problem with objectives $\textsc{Af}(\mathcal{M}_1,x), \textsc{Af}(\mathcal{M}_2,x),\cdots, \textsc{Af}(\mathcal{M}_k,x)$, where $\mathcal{M}_i$ is the statistical model for unknown function $F_i$ and $C_1, C_2,\cdots, C_L$ are the problem constraints. Generally, there are three types of constraints: \begin{itemize} \item \textbf{[Type 1]} $C_i$ is a function of the input $x$ and can be expressed declaratively (white-box constraint). Such a constraint will take the same form as in the cheap MO problem. \item \textbf{[Type 2]} $C_i$ is black-box constraint. In this case, it will be modeled by an independent GP $\mathcal{M}_{c_i}$ and predictive mean of its model $\mu_{c_i}$ can be used in the optimization process. \item \textbf{[Type 3]} $C_i$ is a function of both the input $x$ and a combination of the black-box objective functions. Since verifying constraint $C_i$ depends on the evaluation of one (or more) objectives $F_j$, we employ the predictive mean(s) $\mu_i(x)$ instead. \end{itemize} Without loss of generality and for the sake of notation in Algorithm \ref{alg:USeMO}, we suppose that the first $m$ constraints with $0\leq m \leq L$ are black-box. Since we present the framework as minimization, all AFs will be minimized. The Pareto set $\mathcal{X}_p$ obtained by solving this cheap constrained MO problem represents the most promising candidate inputs for evaluation. \begin{align} \label{eq2} \mathcal{X}_p\leftarrow \arg min_{x \in \mathcal{X}} \; &(\textsc{Af}(\mathcal{M}_1,x),\cdots, \textsc{Af}(\mathcal{M}_k,x))\\ & \textbf{s.t } \mu_{c_0},\cdots,\mu_{c_m},C_{m+1}\cdots, C_L \nonumber \end{align} Each acquisition function \textsc{Af}($\mathcal{M}_i,x$) is dependent on the corresponding surrogate model $\mathcal{M}_i$ of the unknown objective function $F_i$. Hence, each acquisition function will carry the information of its associated objective function. As iterations progress, using more training data, the models $\mathcal{M}_1, \mathcal{M}_2,\cdots, \mathcal{M}_k$ will better mimic the true objective functions $F_1, F_2,\cdots,F_k$. Therefore, the Pareto set of the acquisition function space (solution of Equation~\ref{eq2}) becomes closer to the Pareto set of the true functions $\mathcal{X}^*$ with increasing iterations. Intuitively, the acquisition function \textsc{Af}($\mathcal{M}_i,x$) corresponding to unknown objective function $F_i$ tells us the utility of a point $x$ for optimizing $F_i$. The input minimizing \textsc{Af}($\mathcal{M}_i,x$) has the highest utility for $F_i$, but may have a lower utility for a different function $F_j$ ($j \neq i$). The utility of inputs for evaluation of $F_j$ is captured by its own acquisition function \textsc{Af}($\mathcal{M}_j,x$). Therefore, there is a trade-off in the utility space for all $k$ different functions. The Pareto set $\mathcal{X}_p$ obtained by simultaneously optimizing acquisition functions for all $k$ unknown functions will capture this utility trade-off. As a result, each input $x \in \mathcal{X}_p$ is a promising candidate for evaluation towards the goal of solving MOO problem. USeMOC employs the same acquisition function for all $k$ objectives. The main reason is to give equivalent evaluation for all functions in the Pareto front (PF) at each iteration. If we use different AFs for different objectives, the sampling procedure would be different. Additionally, the values of various AFs can have considerably different ranges. Thus, this can result in an unbalanced trade-off between functions in the cheap PF leading to the same unbalance in our final PF. \vspace{1.0ex} \noindent{\bf Cheap constrained MO solver.} We employ the constrained version of the popular NSGA-II algorithm (\cite{deb2002nsga,deb2002fast}) to solve the MO problem with cheap objective functions and cheap constraints noting that any other algorithm can be used. \vspace{1.0ex} \noindent {\bf Picking the best candidate input.} We need to select the best input from the Pareto set $\mathcal{X}_p$ obtained by solving the cheap MO problem. All inputs in $\mathcal{X}_p$ are promising in the sense that they represent the trade-offs in the utility space corresponding to different unknown functions. It is critical to select the input that will guide the overall search towards the goal of quickly approximating the true Pareto set $\mathcal{X}^*$. We employ a uncertainty measure defined in terms of the statistical models $\mathcal{M}_1, \mathcal{M}_2,\cdots, \mathcal{M}_k$ to select the most promising candidate input for evaluation. In single-objective optimization case, the learned model's uncertainty for an input can be defined in terms of the variance of the statistical model. For multi-objective optimization case, we define the uncertainty measure as the volume of the uncertainty hyper-rectangle. \begin{align} \label{eq1} U_{\beta_t}(x) =& VOL( \{(LCB(\mathcal{M}_i, x), UCB(\mathcal{M}_i, x) \}_{i=1}^{k} ) \end{align} where LCB$(\mathcal{M}_i, x)$ and UCB$(\mathcal{M}_i, x)$ represent the lower confidence bound and upper confidence bound of the statistical model $\mathcal{M}_i$ for an input $x$ as defined in equations ~\ref{ucbeq} and \ref{lcbeq}; and $\beta_t$ is the parameter value to trade-off exploitation and exploration at iteration $t$. We employ the adaptive rate recommended by (\cite{gp-ucb}) to set the $\beta_t$ value depending on the iteration number $t$. We measure the uncertainty volume measure for all inputs $x \in \mathcal{X}_p$ and select the input with maximum uncertainty for function evaluation. \begin{align} x_{t+1}=\arg max_{x\in \mathcal{X}_p} \; U_{\beta_t}(x) \end{align} \section{Experiments and Results} In this section, we discuss the experimental evaluation of USeMOC and prior methods on a real-world analog circuit design optimization task. The code for USeMOC is available in github repository: github.com/belakaria/USEMOC. \vspace{1.0ex} \noindent {\bf Analog circuit optimization domain.} We consider optimizing the design of a multi-output switched-capacitor voltage regulator via Cadence circuit simulator that imitates the real hardware \cite{DATE-2020}. Each candidate circuit design is defined by 32 input variables ($d$=32). The first 24 variables are the width, length, and unit of the eight capacitors of the circuit $W_i,L_i,M_i ~ \forall i \in 1\cdots 8$. The remaining input variables are four output voltage references $V_{ref_i}~ \forall i \in 1\cdots 4$ and four resistances $R_i ~ \forall i \in 1\cdots 4$. We optimize nine objectives: maximize efficiency $Eff$, maximize four output voltages $V_{o_1} \cdots V_{o_4}$, and minimize four output ripples $OR_{1} \cdots OR_{4}$. Our problem has a total of nine constraints: \begin{align} &{C}_0: Cp_{total} \simeq 20 nF ~ with ~ Cp_{total}= \sum_{i=1}^8 (1.955W_iL_i+0.54(W_i+L_i))M_i \nonumber\\ &{C}_1~ to~ {C}_4: V_{o_i}\geq V_{ref_i} ~ \forall \in{1\cdots4} \nonumber\\ &{C}_5\ to\ {C}_{8\ }:\ \ OR_{lb}\le OR_i\le OR_{ub} ~ \forall i\ \in{1\cdots4} \nonumber\\ &{C}_9:Eff \le 100\%\nonumber \end{align} where $OR_{lb}$ and $OR_{ub}$ are the predefined lower-bound and upper-bound of $OR_i$ respectively. $Cp_{total}$ is the total capacitance of the circuit. In this problem, $C_0$ is a white-box constraint (Type 1), while remaining constraints are combinations of black-box objectives (Type 3). \vspace{0.8ex} \noindent {\bf Multi-objective BO algorithms.} We compare USeMOC with the existing BO method PESMOC. Due to lack of BO approaches for constrained MO, we compare to known genetic algorithms (NSGA-II and MOEAD). However, they require large number of function evaluations to converge which is not practical for optimization of expensive functions. \vspace{0.8ex} \noindent {\bf Evaluation Metrics.} To measure the performance of baselines and USeMOC, we employ two different metrics, one measuring the accuracy of solutions and another one measuring the efficiency in terms of the number of simulations. 1) Pareto hypervolume (PHV) is a commonly employed metric to measure the quality of a given Pareto front \cite{zitzler1999evolutionary}. After each iteration $t$ (or number of simulations), we measure the PHV for all algorithms. We evaluate all algorithms for 100 circuit simulations. 2) Percentage gain in simulations is the fraction of simulations our BO algorithm USeMOC is saving to reach the PHV accuracy of solutions at the convergence point of baseline algorithm employed for comparison. \vspace{1.0ex} \noindent {\bf Results and Discussion.} We evaluate the performance of USeMOC with two different acquisition functions (EI and LCB) to show the generality and robustness of our approach. We also provide results for the percentage gain in simulations achieved by USeMOC when compared to each baseline method. Figure \ref{fig:hv} shows the PHV metric achieved by different multi-objective methods including USeMOC as a function of the number of circuit simulations. We make the following observations: 1) USeMOC with both EI and LCB acquisition functions perform significantly better than all baseline methods. 2) USeMOC is able to uncover a better Pareto solutions than baselines using significantly less number of circuit simulations. This result shows the efficiency of our approach. Table \ref{tab:costreduction} shows that USeMOC achieves percentage gain in simulations w.r.t baseline methods ranging from 90 to 93\%.\\ \noindent The analog circuit is implemented in the industry-provided process design kit (PDK) and shows better efficiency and output ripples. Since MOEAD is the best performing baseline optimization method, we use it for the rest of the experimental analysis. Table \ref{fig:table} illustrates the simulated performance of circuit optimized by MOEAD (best baseline) and USeMOC-EI (best variant of our proposed algorithm). Results of both algorithms meet the voltage reference and ripple requirements (100mV) . Compared to MOEAD, the optimized circuit with USeMOC-EI can achieve a higher conversion efficiency of 76.2 \% (5.25 \% higher than MOEAD, highlighted in red color) with similar output ripples. The optimized circuits can generate the target output voltages within the range of 0.52V-0.61V (1/3x ratio) and 1.07V-1.12V (2/3x ratio) under the loads varying from 14 Ohms to 1697 Ohms (highlighted in black and green colors). Thus, the capability of USeMOC to optimize the parameters of circuit under different output voltage/current conditions is clearly validated. Future work includes improving USeMOC to solve more challenging problems \cite{belakaria2020PSD}. \begin{table}[ht!] \centering \resizebox{0.6\linewidth}{!}{ \begin{tabular}{lllllll} \toprule Method & MOEAD & NSGA-II & PESMOC \\ \midrule Gain in simulations & 90.7\% & 93.3\% &92.5\% \\ \bottomrule \end{tabular}} \caption{Percentage gain in simulations achieved by our USeMOC compared to baselines.} \label{tab:costreduction} \end{table} \begin{figure} [h!] \centering \includegraphics[width=0.5\linewidth]{phv.png} \caption{Results of different multi-objective algorithms including USeMOC. The hypervolume metric is shown as a function of the number of circuit design simulations.}\label{fig:hv} \end{figure} \begin{figure}[h!] \centering \includegraphics[width=.55\linewidth]{table.pdf} \caption{Comparison table of optimized circuit parameters obtained by MOEAD and USeMOC-EI (designs are selected from the Pareto set prioritized by efficiency)} \label{fig:table} \end{figure} \newpage \input{ref.bbl} \end{document}
{'timestamp': '2020-09-02T02:08:57', 'yymm': '2008', 'arxiv_id': '2008.07029', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07029'}
arxiv
\section{Introduction} For autonomous robots to operate effectively in the world they must be able to handle objects safely. When grasping an object, the robot must find the \textit{Goldilocks} zone between gripping too tightly and damaging the object, and too loosely and dropping the object; both of which could result catastrophic damage to the object. The ability of a tactile sensor to detect object slippage can set a lower bound on the safe gripping force, as once slip is detected the grasp can be tightened and the object prevented from falling. One key focus of slip-detection research in robotics is to find when parts of the sensor begin to slip whilst other parts remain in static contact. This phenomenon of slippage of part, but not all, of the contact surface(s) between the sensor and object is termed incipient slip \cite{Chen2018}. Incipient slip is also observed in the skin of the human finger pad. Due to the non-uniform distribution pressure (and hence local normal forces) across the finger pad, some regions may slip before others, where the traction (proportional to normal force) is smaller \cite{Francomano2013ArtificialReview, Tada2004AnFingertip}. On the mechanoreceptor level, this provides significant stimulation of the FA-1 and SA-1 afferents, and has been observed to trigger an increase in grip force \cite{Johansson1987SignalsGrip}, although the exact biomechanical and neural mechanisms underpinning this response have yet to be definitively identified. Detecting incipient slip is useful because corrective action can be taken before slippage occurs across the entire contact area, hence significantly reducing the likelihood of the object being dropped. The aim of this study is to develop a sensor which displays incipient slip by mimicking the biomechanical behaviours of the human finger pad. We modify an existing biomimetic optical tactile sensor - the TacTip \cite{ward2018tactip} - which has previously been effective at slip detection, yet does not exhibit incipient slip behavior \cite{James2018SlipSensor}. The TacTip has an internal pins structure which is inspired by the protrusions of the dermal papillae into the epidermis. Here, we extend this mimicry to include ridges on the external surface to facilitate the shear deformation required for incipient slip to occur (Fig. \ref{fig:cads}), as occurs on the human finger pad, facilitated by the fingerprint ridges. \textcolor{black}{This builds upon prior work applying fingerprint mimicry to the TacTip \cite{Cramphorn2017AdditionAcuity} by targeting a specific phenomenon - incipient slip - and designing the sensor such that it provides the necessary physical conditions to induce incipient slip.} \begin{figure}[t] \centering \begin{subfigure}[b]{0.23\textwidth} \centering \begin{overpic}[height=4.3cm]{figures/tip_cad_nb.PNG} \put(0,90){(a)} \end{overpic} \end{subfigure} \begin{subfigure}[b]{0.23\textwidth} \centering \begin{overpic}[height=4.3cm]{figures/tip_top_cad_nb.PNG} \put(0,90){(b)} \end{overpic} \end{subfigure} \begin{subfigure}[b]{0.47\textwidth} \centering \begin{overpic}[trim={0 1cm 0 0}, clip=true, width=\textwidth]{figures/cutaway.PNG} \put(0,40){(c)} \end{overpic} \end{subfigure} \caption{(a) \& (b) CAD renderings of new sensor showing the concentric ring pattern of the fingerprint-inspired ridges to facilitate the shear deformation of incipient slip. The ridges extend 2 mm above the surface of the sensor. (c) Cutaway showing how the pins are embedded in the skin.}\label{fig:cads} \end{figure} There are significant barriers that make the elicitation and detection of incipient slip challenging. Primarily, when a sensor is deformed by a shear force - as is experienced when holding an object - the surface must have sufficient elasticity to allow parts of the sensor to slip while other parts remain stuck, which requires shear deformation between the slipping and stuck parts of the external sensor surface. Additionally, this must be detectable from the sensor output, in this case the camera inside the sensor. We demonstrate that the modified TacTip presented here displays incipient slip for a substantial duration preceding gross slip, and that the sensor can detect this signal with high accuracy when using a convolutional neural network to interpret the movement of internal pins as measured by the internal sensor camera. \section{Background} Slip detection research can be split into three distinct categories: \textbf{gross} slip, where the entire sensor surface is slipping; \textbf{incipient} slip (investigated here), where parts of the sensor contact with the object is slipping, but not all of it; and slip \textbf{prediction}, where other features of the sensor data can be used to predict when slip is about to occur \cite{Chen2018}. There are many excellent studies involving slip detection; for an in-depth presentation of these methods, we direct the interested reader to reviews by Chen et al. (2018) \cite{Chen2018} and Kappasov et al. (2015) \cite{Kappassov2015TactileReview}. In the following, our focus is limited to prior art relating to incipient slip. \begin{figure}[t] \centering \begin{subfigure}[b]{0.23\textwidth} \begin{overpic}[width=\textwidth, trim={0 0 0 -1cm}, clip=true]{figures/tip_side.png} \put(50,97){\makebox(0,0){New Sensor (fingerprint)}} \put(96,-100){\color{black}\rule{1pt}{235pt}} \end{overpic} \end{subfigure} \begin{subfigure}[b]{0.23\textwidth} \begin{overpic}[width=\textwidth, trim={0 0 0 -1.2cm}, clip=true]{figures/old_tip_side.png} \put(50,98){\makebox(0,0){Previous Sensor (smooth)}} \end{overpic} \end{subfigure} \begin{subfigure}[b]{0.23\textwidth} \includegraphics[width=\textwidth]{figures/tip_pins.png} \end{subfigure} \begin{subfigure}[b]{0.23\textwidth} \includegraphics[width=\textwidth]{figures/old_tip_pins.png} \end{subfigure} \caption{Comparison of new sensor (left column) and previous TacTip design (right column). The added ridges distort the otherwise uniform surface to facilitate incipient slip. The new sensor also has a smaller pin density.}\label{fig:tips_compare} \end{figure} Dong et al. (2019) were able to detect incipient slip using the GelSlim sensor by observing the movement of markers on the periphery of the contact surface when grasping various objects in a pinch grasp \cite{Dong2019MaintainingSlip}. Su et al. (2015) observed vibration in BioTac sensors to predict slip was going to occur 30 ms before it was detected by an inertial measurement unit atop an object \cite{su2015force}; however, the authors show no evidence that the mechanism allowing them to achieve this detection was indeed incipient slip. Fujimoto et al. (2003) use a PVDF sensor in a ridged skin to detect incipient slip but, again, do not definitively prove that the sensor signal is incipient slip \cite{Fujimoto}. Rigi et al. (2018) used a DAVIS event-based neuromorphic camera to detect incipient slip by reconstructing the surface contact area and detecting when parts of it moved \cite{Rigi2018ADAVIS}. A novel sensor for detecting incipient slip was presented by Khamis et al. (2018) \cite{Khamis2018PapillArray:Validation}. The PapillArray consists of a 3x3 array of silicone pillars of differing heights. When compressed and a shear force applied, the pillars further from the centre - which are shorter and therefore under a smaller normal force loading are encouraged to slip before the central pillars. Measuring differing pillar deflection is sufficient to detect incipient slip. The PapillArray pillars can also be used to estimate the coefficient of friction and force, and are highly sensitive to vibration \cite{Khamis2019ASensor}. \begin{figure}[t] \centering \begin{overpic}[trim={0cm 3.5cm 0cm 3cm},clip=true, width=\linewidth]{figures/rig.jpg} \put(60,80){\large Sensor} \put(60,80){\linethickness{0.4mm}\vector(-5,-7){9}} \put(55,64){\parbox{6em}{\centering\large Transparent Stimulus}} \put(64,60){\linethickness{0.4mm}\vector(-5,-5){10}} \put(84,22){\large Camera} \put(83,24){\linethickness{0.4mm}\vector(-2,1){18}} \end{overpic} \caption{Rig for collecting incipient slip data. Modified TacTip attached to an ABB IRB120 six-axis robotic arm; external camera held in a clamp and the transparent acrylic sheet - black tape added for clarity - moving in a low friction rail.} \label{fig:rig} \end{figure} This work introduces a modified version of an existing sensor, the TacTip biomimetic optical tactile sensor~\cite{ward2018tactip}. Prior work performed with the TacTip includes gross slip detection using a support vector machine (SVM) \cite{James2018SlipSensor}: objects were allowed to undergo gross slip which had to be detected and the sensor moved forward (increasing the normal force applied) to prevent the object being dropped, catching the objects after slipping by as little as 15 mm. \textcolor{black}{In other work, Cramphorn et al. (2017) explored the effect of a adding protrusions to the outer TacTip surface; however, the aim of that work was to enhance spatial acuity~\cite{Cramphorn2017AdditionAcuity}} not enhance incipient slip. The protrusions also do not resemble a fingerprint so the focus greatly differs from that of this work. \begin{figure*}[t] \centering \begin{subfigure}[b]{0.49\textwidth} \begin{overpic}[trim={4cm 0cm 4cm 0cm}, clip=true, width=\textwidth]{figures/0s500ms.jpg} \put(0,31.5){\color{white}\rule{84pt}{1pt}} \put(0,47.5){\color{orange}\rule{125pt}{1pt}} \put(90,43){\color{red}\rule{24pt}{1pt}} \end{overpic} \caption{Prior to incipient slip} \label{fig:run_start} \end{subfigure} \centering \begin{subfigure}[b]{0.49\textwidth} \begin{overpic}[trim={4cm 0cm 4cm 0cm},clip=true, width=\textwidth]{figures/11s.jpg} \put(0,31.5){\color{white}\rule{84pt}{1pt}} \put(0,47.5){\color{orange}\rule{125pt}{1pt}} \put(90,43){\color{red}\rule{24pt}{1pt}} \put(51,45){\color{orange} Static} \put(30,28){\color{white}Slip} \end{overpic} \caption{Prior to gross slip} \label{fig:run_incipient} \end{subfigure} \caption{External camera view of sensor with markers attached to track fixed points on the surface. (a) Frame from the start of the data collection. (b) Frame taken close to gross slip occurring. For reference, the coloured lines are in the same locations in both images. The marker closest to the white line shows clear movement, however, the marker near the orange line and the ArUco optical marker do not move. Therefore, we see incipient slip: slip of part but not all of the contact surface.}\label{fig:tips_side} \end{figure*} \section{Materials and Methods} \subsection{Modified Sensor Design} The sensor presented in this work is a modification of the TacTip, a biomimetic optical tactile sensor \cite{ward2018tactip,chorley2009development}. The TacTip contains 127 pins arranged in a hexagonal pattern on the inside of a hemisphere constructed from TangoBlack+, a rubber-like material. The tip is filled with silicone gel (RTV27905) and sealed with a clear acrylic lens. This makes it compliant but allows it to quickly reform its shape and reduces hysteresis. A camera (model ELP-USBFHD01M-L21) is focused on the inside of the sensor and can be used to record the positions of the pins or capture the raw images \cite{Lepora2019FromSensor} as a method of transducing deformation of the external skin surface. The key functional requirements for the modification are to introduce a traction differential (i.e. different normal force in different places) and an ability for shear displacement to apply to the parts of the sensor (the ridges) that make contact with the object surface, as occurs in the human finger pad \cite{Tada2004AnFingertip} such that some of the contact area slips and some does not. Previously, when an object slipped across the TacTip, there was no discernible incipient slip \cite{James2018SlipSensor}; the pins all moved together in a linear fashion when gross slip occurred. To solve this, we have added five rings of increasing radius, from a central ring of zero radius (in effect an external pin). In the TacTip, the pins consist of heads of VeroWhite material atop small pillars of TangoBlack+. Here, we extend the pin-heads such that they protrude through the pillars and into the ridges (Fig \ref{fig:cads}(c)). The pins act as mechanical transducers so any motion of the ridges results in visible motion of the pins from inside the sensor. \textcolor{black}{Cramphorn et al. (2017) utilised this transduction principle to improve the spatial acuity of the sensor by adding small (0.5mm) protrusions to the surface of the TacTip, however their focus was purely on perception not slip \cite{Cramphorn2017AdditionAcuity}}. Here we modify the TacTip with the express aim of allowing it to experience and subsequently transduce incipient slip (Table \ref{tab:problems}). Firstly, we have added raised ridges which mimic the friction ridges in the dermis of the human fingertip. Under the Coulomb model of friction, the maximum frictional force is proportional to the normal force. Therefore, the addition of raised ridges results in the neighbouring contact areas being spaced apart and subject to notably different normal forces, aided by the curvature of the TacTip exterior. Previously, the smooth hemispherical surface meant that neighbouring regions of contact were subject to very similar normal forces. Secondly, we have reduced the thickness of the skin between rings from 1 mm to 0.5 mm, to facilitate shear deformation of the sensor contact surface. Even though the ridges will lead to differing normal forces, the rings are still linked by the interstitial skin. The thicker the skin the higher the coefficient of elasticity, which hinders shear deformation (skin stretch) and hence diminishes the associated incipient slip phenomenon. It should be noted that the added ridges will also bend, which further allows parts of the skin to move independently, and therefore reduces the dependency on the skin stretch for incipient slip to occur. Finally, as the pins are set in gel, when one pin moves in the TacTip it causes neighbouring pins to move. One consequence of this is that if a single region of the sensor surface was to move it would cause many adjacent pins to move due to this mechanical coupling. To minimise this effect we increase the spacing of the pins such that the projected radius of each ring of pins is 4 mm greater than the ring inside (Fig. \ref{fig:tips_compare} compares the two designs). Previously the spacing was 3 mm between all adjacent pins laid out in a hexagonal pattern. We also increased the thickness of the pins to reduce the potential for damage when removing support material after 3D printing. \begin{table}[b] \centering \begin{tabular}{l l p{4.5cm}} \hline \hline & Modification & Benefit \\ \hline \hline 1 & Add raised ridges & Adjacent contact regions have differing normal forces to create traction differential \\ \hline 2 & Reduce skin thickness & Skin stretchier to facilitate incipient slip\\ \hline 3 & Reduce pin density & Decrease coupling of internal pins to facilitate detection of incipient slip\\ \hline \hline \end{tabular} \caption{The key modifications to TacTip design to facilitated occurrence and detection of incipient slip.} \label{tab:problems} \end{table} \begin{figure}[t] \centering \begin{subfigure}[b]{0.49\textwidth} \centering \includegraphics[width=\textwidth]{figures/external_view_change.png} \end{subfigure} \begin{subfigure}[b]{0.49\textwidth} \centering \includegraphics[width=\textwidth]{figures/internal_view_change.png} \end{subfigure} \caption{Top - External markers from newly designed sensor. Blue lines indicate where incipient slip begins (left vertical line) and when the object begins to fall (right vertical line). Bottom - Corresponding internal pin positions from the same experiment as above. Inset in top left of each subfigure shows external tracking markers.} \label{fig:pins} \end{figure} \begin{figure}[h] \centering \includegraphics[width=0.49\textwidth]{figures/external_old_change.png} \caption{No incipient slip signal from external markers attached to smooth TacTip.} \label{fig:pins_old} \end{figure} \subsection{Data Collection Rig} \label{sec:rig} To collect data and perform a reliable comparison to the previous TacTip design we reuse the data collection rig from James et al. (2018) \cite{James2018SlipSensor}. The apparatus utilised a low friction rail system with a slider, to which objects can be attached (Fig. \ref{fig:rig}). This provides several advantages, including allowing: (i) objects to fall under gravity with minimal friction; (ii) experiments to be repeatable with high precision, and; (iii) experiments to be performed entirely without human input after initial setup. Here, we augment the apparatus by adding an external camera to measure movement of the external surface of the sensor and the acrylic sheet. James et al. (2018) used various shapes made from ABS plastic; however, this is unsuitable here as we need to use a transparent object to make reference recordings of movements on the sensor's surface. We therefore use a sheet of 10 mm thick transparent acrylic. Additionally, we apply markers in a cross pattern to the surface of the sensor so that fixed points on the surface can be easily tracked by the external camera (Fig. \ref{fig:tips_side}). Both the external markers and the internal pins are identified and segmented using the Python OpenCV library function \textit{SimpleBlobDetection} which provides a list of blob $(x,y)$ coordinates for each frame. The order of the pins is not necessarily consistent between frames. However, by setting a threshold on the maximum distance a pin or marker can move between frames we can reorder the list of pins thus tracking them from frame to frame. To annotate when gross slip occurs, we attach an ArUco optical marker to the acrylic so its height can be measured by the external camera. When the height of the acrylic sheet changes significantly, we assert that gross slip is occurring. To collect data the sensor is pressed against the acrylic, which is then lifted 50 mm. At this point, the cameras start to record and the arm retracts slowly (moving normal to the acrylic sheet) until the object has completely fallen. Different retraction speeds between $0.1$-$0.5$ mm.s$^{-1}$ at $0.1$ mm.s$^{-1}$ intervals are used. \subsection{Change Point Detection} \label{sec:change_point} To label when incipient slip begins, we use the Pruned Exact Linear Time (PELT) algorithm \cite{Killick2012OptimalCost} applied to the internal pins. PELT is an example of a \textbf{change point} algorithm, the purpose of which is to calculate when the distribution of a data set changes. When the markers are static, the distribution of the detected positions will mostly consist of noise coming from the error inherent in the detection algorithm. When incipient slip occurs, we expect this distribution to shift and use change point detection to determine when this started. We choose PELT as it is known to be more accurate than other methods such as Binary Segmentation, and far more computationally efficient, executing in $\mathcal{O}(n)$ time. \subsection{Deep Learning Architecture} \label{sec:dl} To attempt the classification of incipient slip, we utilise a convolutional neural network (CNN). CNNs have shown strong performance in classification and regression using the TacTip, including estimating the orientation of edges \cite{Lepora2019FromSensor} and classifying objects \cite{Church2019TactileHand}. Using raw image data from the sensor has been shown to outperform using pin positions, as the network can learn from whichever features it deems are most informative rather than hand-crafted features. Here, we use a binary CNN to infer the presence of incipient slip on the \textbf{external} surface simply by observing the \textbf{internal} raw camera footage. Being a time-dependent phenomenon, incipient slip can only be detected by observing multiple frames of data. Therefore, we provide the network with multiple samples such that the differences in sensor data caused by incipient slip can be learned. We follow a similar image processing pipeline from previous work using the TacTip \cite{Lepora2019FromSensor, Church2019TactileHand, lepora2020optimal} which also reduces processing time: (i) Convert to grayscale; (ii) Apply Gaussian adaptive threshold using OpenCV function; (iii) Downsample image from (640$\times$480) to (55$\times$48) pixels to reduce input size to network; (iv) Sum the pixel values from ten consecutive frames to add a temporal dimension to the data; (v) Rescale the pixel values onto the domain [0,1] to reduce error gradients when training \cite{Bishop1995NeuralRecognition}. The network architecture consists of three convolutional layers with 32, 64 and 64 filters and max pooling between the first two layers, followed by a fully connected layer and an output layer. \begin{figure}[t] \centering \begin{subfigure}[b]{0.48\textwidth} \includegraphics[trim={0 6cm 0 8cm}, clip=true, width=\textwidth]{figures/rig_object_side.jpg} \label{fig:rig_flat_obj} \end{subfigure} \begin{subfigure}[b]{0.48\textwidth} \includegraphics[trim={0 1cm 0 0}, clip=true,width=\textwidth]{figures/stimuli.JPG} \label{fig:stimuli} \end{subfigure} \caption{Top: Flat stimulus held by the tip for real time testing. Bottom: Experiment stimuli with differing radii of curvature.}\label{fig:exp_online} \end{figure} \section{Results} \subsection{Incipient Slip} \subsubsection{External View Analysis} Using the slip detection rig from Sec.\ref{sec:rig}, we performed 20 repeats at each retraction speed and recorded both the internal and external camera data. Following this, we detected the external markers and internal pins to determine whether incipient slip was present. Despite applying markers to the three innermost ridges, as well as the central pin, the third ring loses contact with the surface before gross slip occurs. Therefore, from here on, we ignored these four markers, leaving nine markers to be tracked, which were in contact for the duration of each trial. The external camera video showed a clear presence of incipient slip (Fig. \ref{fig:tips_side}). The markers on the second ring displayed the most obvious movement however the marker atop this ring and the ArUco did not move. This means that parts of the contact surface were slipping when others were not and, crucially, before the object showed any sign of falling. This incipient slip pattern becomes clearer when looking at the data after the markers have been tracked. Again, it is clear that the farthest left and right markers begin to move after \textasciitilde2.5 s before any others (Fig.~\ref{fig:pins}). The markers inside the two markers on each extreme begin to move next. Throughout the experiment, the two topmost markers remain static until gross slip occurs and the object falls after \textasciitilde6.5 s. The pattern seen here is broadly in line with predictions made by the Coulomb model of friction, which states that maximum static frictional force is proportional to the normal force on the surface. The domed shape means that the greater the radius of the ring, the lower the normal force, and therefore we would expect the markers further from the centre to slip first. When considering the line of markers placed horizontally across the middle of the sensor this is exactly what we see: the markers on the far left and far right slip first, followed by those markers closer to the centre. When considering the line of markers placed vertically up the middle of the sensor, the picture becomes more complicated. The top two markers show almost no motion, whereas the bottom two markers show noticeable movement. As the sensor is bearing the weight of the acrylic, this causes a large shear force to be applied to the sensor, which most likely causes the normal force distribution across the vertically-aligned markers to become asymmetric. \subsubsection{Internal View Analysis} There are two distinct types of sensor surface movement that cause the majority of the pin movement inside the sensor: translation and pivot. Translation occurs when an external ridge of the TacTip slips and the pin embedded within also translates in the same direction, but perhaps not to the same extent. Pivoting occurs when the ring surface remains static on the object but the parts of the skin spanning the ridges moves. As the pins protrude equal distances normal to the skin internally and externally, the effect of pivoting is quite pronounced. This effect somewhat confounds our ability to easily observe movement of the external surface of the ridge against the object (i.e. to detect slip). To detect incipient slip on the inside we want to see examples of translational pin movement; however, it appears that the pivoting is the dominant effect resulting in pin movement. Thus, it is difficult to determine whether relative translation between pins relates to the occurrence of incipient slip on the external surface (Fig. \ref{fig:pins}), or whether this movement is due to pin pivoting. This does not mean that the effect is not detectable in the pin movement patterns, but rather that it is more challenging to extract. Fundamentally, this is a complex pattern recognition problem; thus, we are motivated to utilise a deep learning approach directly on the tactile images. \subsubsection{TacTip Marker Analysis} To confirm that incipient slip is not visible in the previous smooth TacTip design used in previous work~\cite{James2018SlipSensor}, we attached markers in the same pattern on the surface of that smooth TacTip and performed the same experiment. As expected, the movement of markers does not display the characteristic incipient slip pattern that is present in the new design (Fig. \ref{fig:pins_old}). Instead, all markers remain static until gross slip occurs, when they all move in unison. This bulk motion of the surface contributed to making that smooth design of TacTip so effective at detecting gross slip \cite{James2018SlipSensor}. \subsection{Online Testing} \subsubsection{Data Labelling} To detect the time that incipient slip commences we use the change point detection algorithm PELT (Sec. \ref{sec:change_point}). Since PELT requires the entire time series of data to determine the change points, it cannot be used in real time to detect changes. We use it to detect the onset of incipient slip by providing the data from the two external markers which exhibit the strongest incipient slip signal (Fig. \ref{fig:tips_side}). The detected change point is used as the label to define when incipient slip begins. We use the ArUco marker recording to determine when gross slip begins. As the classifier is binary labels are either \textit{incipient slip} or \textit{not}. \begin{table}[b] \begin{center} \begin{tabular} {p{1.5cm } p{1.4cm} p{3.2cm}} \hline \hline RoC (mm) & Success (\%) & Incipient Slip Margin (mm) \\ \hline \hline \(\infty\) (Flat) & 100 & 0.9 \\ \hline 80 & 100 & 0.9 \\ \hline 40 & 100 & 1.0 \\ \hline 20 & 100 & 0.7 \\ \hline \hline \end{tabular} \end{center} \caption{The success of incipient slip detection with objects with varying radii of curvature (RoC). Twenty tests were performed per object.} \label{tab:online} \end{table} \subsubsection{Convolutional Neural Network} We use 50\% of the labelled data for training the CNN, withholding 25\% for each of the validation and testing sets to judge performance. We ensure that an equal proportion of experiments from each retraction speed is contained within each data set to avoid training bias. Additionally, we augment the training data set by performing random shifting of the image by 20\% in $x$ and $y$ and randomly zooming in on the image by up to 20\%. This was performed to help the network generalise to changes in shear and normal forces caused by varying objects. We trained for ten epochs, after which the validation error began to increase, thus avoiding overfitting the data. After training we quantify how successful the model is at detecting incipient slip on the unseen test data set. The model predicted whether incipient slip was present or not with over 98\% accuracy. This suggests that the model has not overfitted to the training data and is highly successful at identifying the presence of incipient slip using the internal camera. However, the real test of the model's ability to detect incipient slip is to use it in real time on different objects. \subsubsection{Experiment Description} To test incipient slip detection in real time, we reuse four tactile stimuli from James et al. (2018) (Fig. \ref{fig:exp_online}). Each has a different radius of curvature that will provide a different normal force distribution across the sensor surface. They are also opaque so the contact surface cannot be observed. When testing online we want to challenge the incipient slip CNN by varying the conditions under which incipient slip occurs. As these stimuli change the object weight, texture (which in turn can alter the frictional properties by affecting real contact area between the sensor and object), and normal force distribution, they provide an indication of how well the model has generalised. \begin{figure}[t] \centering \includegraphics[trim={0 0.2cm 0 0}, clip=true, width=0.85\linewidth]{figures/flow.pdf} \caption{Experiment flowchart.} \label{fig:flow} \end{figure} In the specific experiment shown in Fig.~\ref{fig:pins}, the sensor was retracted at 0.2 mm.s$^{-1}$, and incipient slip commences approximately four seconds prior to gross slip. This means that we have a buffer zone of nearly $0.8$ mm of movement where the sensor indicates that the object is at risk of experiencing gross slip. To test how far prior to gross slip our model can detect incipient slip, we follow the procedure in Fig. \ref{fig:flow}. After incipient slip is detected, we can count how many additional 0.2 mm retractions occur before the object falls, and determine how far in advance of gross slip we are detecting incipient slip. We repeated the experiment twenty times per stimulus with a randomly chosen retraction speed between 0.1-0.5 mm.s$^{-1}$. Results are presented in Table \ref{tab:online}. In all trials for each stimulus, incipient slip was detected before the object fell. The most curved stimulus (20mm radius of curvature) had the smallest incipient slip margin (0.7 mm), meaning that it was closest to slipping when incipient slip was detected. The remaining three stimuli had broadly similar margins between 0.9-1.0 mm. Therefore in all cases, incipient slip was detected considerably before the object fell, with a known zone of safety, which could be used to proactively prevent slippage of a held object. \section{Discussion} In this paper, we presented a modified TacTip biomimetic optical tactile sensor that can facilitate and detect incipient slip, as confirmed by recording the movement of markers on the external surface of the sensor. This is significant as we conclusively show the presence of incipient slip whereas many prior studies assert its existence from data \cite{su2015force,Fujimoto,Veiga2015StabilizingSlip}. Several changes to the TacTip design were made based on the physical conditions which facilitate incipient slip. The most significant change involved the addition of ridges - structurally analogous to human the fingerprint - in a concentric ring pattern which allowed for localised shear deformation to occur on the sensor surface for a significant duration prior to the onset of gross slip. When testing on unseen objects, the detection of incipient slip indicated that gross slippage of the object would occur were the sensor to be retracted normally from the test object between 0.6 and 1.0 mm. These results are in accordance with another experiment considered here where we directly observed the movement of external markers indicating incipient slip, with 0.8mm of retraction distance before gross slip occurs (Fig.\ref{fig:pins}). Using incipient slip as an indicator that one's grasp on an object is insecure is a far more effective strategy than waiting for gross slip to occur and then attempting regrasp the object and arrest the gross slip, as previously performed with the TacTip \cite{James2018SlipSensor}. In practice, this could give a sizeable time window of at least 1.2s, when moving at 0.5 mm.s$^{-1}$, during which to take corrective action to prevent gross slip. This is larger than the slip prediction windows of 30 ms achieved by Su et al. (2015) \cite{su2015force} and 20 ms reported by Veiga et al. \cite{Veiga2015StabilizingSlip}. However, here we are using a very limited set of objects, so further work is needed for a complete comparison. Additionally, it may not be necessary to react immediately upon incipient slip onset so providing a metric of proximity to gross slip onset would be useful. A limitation of the new design is that the incipient slip signal pattern contained in the movement of pins on the inside of the tactile sensor is not amenable to straightforward human interpretation. This meant that we resorted to utilising deep learning methods to detect the internal incipient slip signal, from which we obtained over 98\% classification accuracy. Further work with a more diverse training set and testing on a wider array of objects will be needed to determine how well the CNN can detect incipient slip. In addition, future work will involve further modifications of the design such that the internal pins movements more directly correspond to movements on the external surface, thereby clearly exhibiting the relative shear displacements associated with incipient slip. This could include adding ridges to the inside of the skin and making the pins shorter to reduce pivoting. Other future work could be to vary the size and density of rings so that they more closely resemble the human fingerprint although we are limited by 3D printing resolution and ability to resolve markers in the rings with a camera. To summarise, we have developed a tactile sensor which can reliably detect and facilitate incipient slip. This is of direct practical utility to robotic hand research on dexterous manipulation of a grasped objects, as it would greatly reduces the chance of manipulated objects being dropped. \section*{Acknowledgements} The authors thank members of the BRL Tactile Robotics Group for their help and insights throughout this work. \bibliographystyle{IEEEtran}
{'timestamp': '2020-08-18T02:17:26', 'yymm': '2008', 'arxiv_id': '2008.06904', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06904'}
arxiv
\section{Conclusion} \label{sec:conclusion} In this work, we have analyzed learning and generalization of symmetric functions through the lens of neural networks defined over probability measures, which formalizes the learning of symmetric function families across varying input size. Our experimental data confirms the theoretical insights distinguishing tiers of non-linear learning, and suggests that symmetries in the input might be a natural device to study the functional spaces defined by deeper neural networks. Specifically, and by focusing on shallow architectures, our analysis extends the fundamental separation between adaptive and non-adaptive neural networks from \textcite{bach2017breaking} to symmetric functions, leading to a hierarchy of functional spaces $\mathcal{S}_3 \subset \mathcal{S}_2 \subset \mathcal{S}_1$, in which nonlinear learning is added into the parametrization of the network weights ($\mathcal{S}_2$), and into the parametrization of test functions ($\mathcal{S}_1$) respectively. A crucial aspect we have not addressed, though, is the computational cost of learning in $\mathcal{S}_1$ through gradient-based algorithms. An important direction of future work is to build on recent advances in mean-field theory for learning shallow neural networks \parencite{chizat2020implicit, ma2019barron, ma2020quenching,de2020sparsity}. \paragraph{Acknowledgements:} We thank Raghav Singhal for helpful discussions regarding the proof of Theorem~\ref{thm:inclusion}. This work has been partially supported by the Alfred P. Sloan Foundation, NSF RI-1816753, NSF CAREER CIF-1845360, and NSF CCF-1814524. \section{Experiments}\label{sec:experiments} \begin{figure*}[ht] \centering \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/maximum_flip_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/softmax_flip_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/mean_flip_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/median_flip_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/second_flip_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.33\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/potential_Wide_10_False_True_True.png} \end{subfigure}% \caption{\small{Test Error for $d = 10$ on the neural architectures of Section \ref{sec:neural_functional_spaces}}} \vspace{-0.4cm} \label{fig:plots} \end{figure*} \subsection{Symmetric Function Approximation} We consider the task of learning several common symmetric functions (see Figure~\ref{fig:plots}). Our aim is to practically understand the approximation bounds of Theorem~\ref{thm:inclusion}, as well as the generalization result of Proposition~\ref{prop:rad}. Furthermore, by training and testing on sets of different sizes, we may consider how the models perform on out-of-distribution generalization across input size. \paragraph{Experimental Setup:} We instantiate our three function classes in the finite network setting, as outlined in Table~\ref{tab:freeze}. We use input dimension $d = 10$. For the finite realization of $\mathcal{S}_1$, we use first hidden layer size $m = 100$ and second hidden layer size $h = 100$. Crucially, after fixing the finite architecture representing $\mathcal{S}_1$, we scale up the width by 10 for the models with frozen weights. That is, the first hidden layer in $\mathcal{S}_2$, and both hidden layers in $\mathcal{S}_3$, have width equal to 1000. Increasing the width makes the $\mathcal{S}_2$ and $\mathcal{S}_3$ models strictly more powerful, and this setup allows us to inspect whether a larger number of random kernel features can compensate for a smaller, trained weight in approximation. For each model, we use its associated functional norm for regularization. Each network is trained on a batch of 100 input sets. For our data distribution we consider the base domain $\mathbb{I} = [-3, 3]^d$, and the distribution over input measures $\xi$ places all its mass on the uniform measure $U([-3,3]^d)$. We choose to train with $N = 4$, i.e. all networks train on input sets of size 4, and test on sets of varying size. From the results we can measure out-of-distribution generalization of finite sets. The one-dimensional symmetric functions are defined on sets of vectors by first applying inverse norms, i.e. $f_N(x) = \max_{1\leq i \leq N} \|x_i\|_2^{-1}$. The potential function calculates the normalized gravitational potential among equal masses, i.e. $f_N(x) = \frac{2}{N(N-1)} \sum_{i < j} \frac{1}{\|x_i - x_j\|_2}$. The planted neuron and smooth neuron are given as single-neuron networks, where following from the proof of Theorem~\ref{thm:inclusion}, the planted neuron weight initialization is distinct from the model weight initialization. Further details are given in the Appendix. We additionally consider an applied experiment on a variant of MNIST to observe how the finite-width implementations perform on real-world data, by first mapping images to point clouds. Due to space limitations, details and results are given in the Appendix. \begin{figure*}[h] \centering \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/neuron_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/neuron_Wide_10_True_True_True.png} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/smooth_neuron_Wide_10_False_True_True.png} \end{subfigure}% \begin{subfigure}{.32\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/smooth_neuron_Wide_10_True_True_True.png} \end{subfigure}% \caption{\small{Planted neurons for $m = 100$ (left two) and $m = 200$ (right two). The smooth neuron has weights sampled consistently with $\mathcal{F}_2$ while the regular neuron has weights sampled distinctly from the network initialization.}} \label{fig:neurons} \end{figure*} \paragraph{Discussion:} We observe in Figure~\ref{fig:plots} that $\mathcal{S}_3$ performs substantially worse in several cases, consistent with this function class being the smallest of those considered. The classes $\mathcal{S}_2$ and $\mathcal{S}_1$ are competitive for some functions, although we observe a trend where $\mathcal{S}_1$ still has better generalization performance. Therefore, the larger number of random kernel features doesn't compensate for training a smaller weight matrix in $\mathcal{S}_1$, empirically confirming Theorem~\ref{thm:inclusion}. The test error on sets of larger size than the training data corroborates the conclusion of Proposition~\ref{prop:extension}. The second-largest-element function generalizes extremely poorly, consistent with the observation in Section~\ref{sec:examples} that this function family cannot be approximated without constant error. In particular, all function classes more effectively generalize across different $N$ on the softmax than the max, seeing as the latter lacks uniform continuity in measure space. The other essential takeaway is the performance of the three models on the planted neurons in Figure~\ref{fig:neurons}. By using a distinct weight initialization for the neuron, its first layer will have very little mass under $\kappa$, and its first two layers will have little mass under $\tau$, and therefore random features will not suffice to approximate this neuron. This is true even with the scaling of $\mathcal{S}_2$ and $\mathcal{S}_3$ to enable more random kernel features, reiterating that these single neuron functions realize a meaningful separation between the classes. We observe a more similar performance of $\mathcal{S}_1$ and $\mathcal{S}_2$ on the smooth\_neuron, as this function is chosen to be exactly representable with the random kernel features sampled by $\mathcal{S}_2$. According to the function class inclusion it is still representable by $\mathcal{S}_1$, but from Theorem~\ref{thm:inclusion} not efficiently representable by $\mathcal{S}_3$, which is consistent with the results. \begin{wrapfigure}{r}{0.5\textwidth} \includegraphics[width=0.9\linewidth]{plots_extra/deepsets.png} \caption{Test error for $\mathcal{S}_1$ versus unnormalized DeepSets architecture.} \label{fig:deepsets} \end{wrapfigure} On increasing $m$, the standard deviations of $\mathcal{S}_2$ and $\mathcal{S}_3$ shrink with more random kernel features, but $\mathcal{S}_1$ still achieves the best approximation on the neuron. For the smooth neuron, $\mathcal{S}_1$ and $\mathcal{S}_2$ perform comparably, but $\mathcal{S}_3$ performs worse even for larger $m$. In Figure~\ref{fig:deepsets} we confirm the need for taking averages rather than sums in the DeepSets architecture, as the unnormalized model cannot generalize outside of the value of $N = 4$ where it was trained. \subsection{Robust Mean Estimation}\label{sec:robust_mean} Symmetric functions naturally arise in the context of empirical estimators. We consider specifically the task of robust mean estimation~\cite{diakonikolas2017being}, where one seeks to estimate $\mathbb{E}_{X \sim P}[X]$ given samples drawn from the mixture distribution $(1-\epsilon) P + \epsilon Q$. For simplicity, we consider an oblivious contamination model where the true distribution $P$ and the noise distribution $Q$ have similar mean vectors. Explicitly, each input set is derived as follows: we sample $m \sim \mathcal{N}(0, \sigma_m^2 I)$, $m' \sim \mathcal{N}(m, \sigma_{m'}^2 I)$, and define $P = \mathcal{N}(m, \sigma_P^2 I)$ and $Q = \mathcal{N}(m', \sigma_Q^2 I)$. Then each input sets consist of $N$ samples $(X_1, \dots, X_N)$ where $X_i \overset{iid}{\sim} (1-\epsilon) P + \epsilon Q$. Note that each input set is a corrupted sample with a different true mean vector $m$. \begin{table*}[ht!] \centering \begin{tabular}{p{5pt}c|c|c|c|c} & & $N = 10$ & $\color{blue}N = 20$ & $N = 30$ & $N = 40$ \\ \hline & $\mathcal{S}_1$ & $0.335 \pm 0.153$ & $\color{blue}0.131 \pm 0.018$ & $0.091 \pm 0.011$ & $0.076 \pm 0.011$ \\ & $\mathcal{S}_2$ & $0.342 \pm 0.153$ & $\color{blue}0.137 \pm 0.019$ & $0.098 \pm 0.012$ & $0.082 \pm 0.011$ \\ & $\mathcal{S}_3$ & $0.361 \pm 0.162$ & $\color{blue}0.144 \pm 0.020$ & $0.103 \pm 0.013$ & $0.087 \pm 0.013$ \\ \hline \hline & Sample Mean & $0.385 \pm 0.172$ & $\color{blue}0.153 \pm 0.068$ & $0.093 \pm 0.042$ & $0.096 \pm 0.043$\\ & Geometric Median & $0.321 \pm 0.144$ & $\color{blue}0.138 \pm 0.062$ & $0.087 \pm 0.039$ & $0.077 \pm 0.034$ \\ & Adversarial Estimator & $0.612 \pm 0.495$ & $\color{blue}0.469 \pm 0.550$ & $0.417 \pm 0.549$ & $0.420 \pm 0.564$\\ \end{tabular} \caption{Mean squared test error for robust mean estimation among the finite model instantiations and baselines.} \label{tab:robust} \end{table*} \paragraph{Experimental Setup:} The network architecture is the same as above, with $d=10$. We use $\sigma_m = 1$, $\sigma_{m'} = 2$, $\sigma_{P} = \sigma_{Q} = 1.5$, and $\epsilon = 0.2$. All networks train on sets of size $N = 20$, and test on sets of varying size, with mean squared error as the objective. As baselines we consider the naive sample mean, the geometric median, and the adversarially robust mean estimator proposed in~\cite{diakonikolas2017being}. The results are given in Table~\ref{tab:robust}. \paragraph{Discussion:} Although the variance is quite high due to the sampling procedure, performance in this setting confirms that robust mean estimation also realizes the class separation, and that for this simple corruption model learning is competitive and in some cases superior to fixed estimators. In particular, the advantage of $\mathcal{S}_1$ over the baselines is most clear for $N = 20$, the setting where it was trained. Although the dependence of the fixed estimators on $\sigma_P$ and $\sigma_Q$ vanishes as $N \rightarrow \infty$, the dependence on these parameters is non-negligible in the regime where $N$ is small, and therefore the robust mean may not generalize in the sense of Proposition~\ref{prop:extension}. We explore training on different $N$ sizes further in the Appendix. The poor performance of the adversarial estimator can mainly be attributed to the fact that the number of samples is considerably smaller than the setting studied in~\cite{diakonikolas2017being}, weakening the concentration of the empirical covariance matrix on which this estimator relies. \section{Approximation and Function Class Separation} \label{sec:approx} \subsection{Approximation of single `neurons'} In the same spirit as the ``separations'' between $\FF_1$ and $\FF_2$, we characterise prototypical functions that belong to $\mathcal{S}_i$ but have poor approximation rates in $\mathcal{S}_{i+1}$ for $i=\{1,2\}$ in terms of the relevant parameters of the problem, the input dimensionality $d$ and the bandwidth parameter $m$. Such functions are given by single neurons in a spherical input regime (details for this setting are given in the Appendix). For the remainder of this work, we consider $\widetilde{\sigma} = \sigma$ as the ReLU activation, and choose $\alpha = 2$ such that $\sigma_2(t) = \sigma(t)^2$ is the squared ReLU. \begin{theorem}[informal]\label{thm:inclusion} Assume $m = \infty$. For appropriate choices of the kernel base measures $\kappa$ and $\tau$, there exist $f_1$ with $\|f_1\|_{\mathcal{S}_1} \leq 1$ and $f_2$ with $\|f_2\|_{\mathcal{S}_2} \leq 1$ such that: \begin{align*} \inf_{\|f\|_{\mathcal{S}_3} \leq \delta} \|f - f_2\|_\infty & \gtrsim d^{-2} \delta^{-5/d}~,\\ \inf_{ \|f \|_{\mathcal{S}_2} \leq \delta} \| f - f_1 \|_\infty & \gtrsim |d^{-11} - d^{-d/3}\delta|~. \end{align*} \end{theorem} The choice of the squared ReLU activation in the parameterization of the test functions is required in the proof separating $\mathcal{S}_1$ and $\mathcal{S}_2$. This follows from some properties of spherical harmonic parity and the decomposition of signed measures into probability measures. These separations use the infinity norm rather than an appropriate $L_2$ norm, and therefore hold in a weaker norm than separation between $\FF_1$ and $\FF_2$. Nevertheless, these separations confirm that symmetric network expressiveness is \emph{graded} by the degree of non-linear learning. Both results hold in the domain $m = \infty$, so from the concentration of the empirical kernel $k_m \rightarrow k$, with high probability these approximation lower bounds will still hold for sufficiently large $m$. In finite-width implementations, however, $m$ may be sufficiently small that the random kernel more explicitly determines the expressiveness of $\mathcal{S}_{i,m}$. We experimentally test the presence of these depth separations with finite $m$ in Section~\ref{sec:experiments}. \subsection{Approximation of variational symmetric function via Laplace method} Consider any symmetric family $f_N(x) = \argmin_{t \in T} \langle \hat\mu_x, \phi_t \rangle$ where $\hat\mu_x$ is the empirical measure of $x$, ie, $\hat\mu_x = \frac{1}{N} \sum_i \delta_{x_i}$, $T$ is a Euclidean subset, and $t \mapsto \phi_t$ is measurable. For example $T = \mathbb{R}$ and $\phi_t(x) = |t-x|$ yields $f_N$ as the median. Although this function family isn't necessarily uniformly continuous in the weak topology, we highlight the option of a Laplace approximation. Define $E_\mu(t) := \langle \mu, \phi_t \rangle $ and introduce the density $p_\beta(t) = \frac{1}{Z} e^{-\beta E_\mu(t)}$ where $Z = \int_T e^{-\beta E_\mu(t)} dt$ is the partition function. Then consider the Gibbs approximation $g_\beta(\mu) := \mathbb{E}_{p_\beta}[t] = \frac{1}{Z} \int_T t e^{-\beta E_\mu(t)} dt$. One can verify (e.g. \parencite{raginsky2017non}) that $g_\beta \to g$ pointwise at a rate $\sim \frac{d \log(\beta + 1)}{\beta}$. As $g_\beta$ is continuous, by universality it can be represented in $\mathcal{S}_i$ for all $i=\{1,2,3\}$. An approximation of $g_\beta$ is given as a ratio of two shallow networks $g_\beta(\mu) = \frac{\int_T t \sigma_1(\langle \mu, \phi_t \rangle ) dt }{\int_T \sigma_1(\langle \mu, \phi_t \rangle ) dt}$, with $\sigma_1(u) = e^{-\beta u}$. However, the approximation rates blow-up as $\beta \to \infty$ with an exponential dependency on the dimension of $T$. \section{Generalization and Concentration} \label{sec:gen} \subsection{Generalization Bounds} Despite being a larger function class than $\FF_2$, the class $\FF_1$ enjoys a nice generalization bound \parencite{bach2017breaking}. Crucially, this property is inherited when we lift to functions on measures, controlling the generalization of functions in $\mathcal{S}_1$: \begin{proposition}\label{prop:rad} Assume for given $\delta$, for all $y$ the loss function $\ell(y, \cdot)$ is $G$-Lipschitz on $B_0(2R^2\delta)$, and $l(y, 0) \leq RG\delta$. Then with probability at least $1-t$, $$\sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left| \mathbb{E}_{\mu \sim \mathcal{D}} \ell(f^*(\mu), f(\mu)) - \frac{1}{n} \sum_{i=1}^n \ell(f^*(\mu_i), f(\mu_i)) \right| \\ \leq \frac{2RG\delta + 16R^4G\delta}{\sqrt{n}} + (4R^2G\delta + 2RG\delta)\sqrt{\frac{\log 1/t}{2n}}~.$$ \end{proposition} This proposition demonstrates that learning in $\mathcal{S}_1$ is not cursed by the dimension of the underlying input space $\mathbb{I}$. In other words, the main price for learning in $\mathcal{S}_1$ is not in generalization, despite the size of this class relative to $\mathcal{S}_2$ and $\mathcal{S}_3$. In the absence of a lower bound on generalization error for the RKHS function classes, our experiments investigate the generalization of these models in practice. Although $d$ and $N$ do not appear in this bound, these parameters nevertheless impact the generalization of our function classes $\mathcal{S}_i$. The input dimension controls the separation of the classes according to Theorem~\ref{thm:inclusion}, and therefore larger $d$ weakens the generalization of $\mathcal{S}_2$ and $\mathcal{S}_3$; compare Figure~\ref{fig:plots} and Figure~\ref{fig:plots_extra} (in the Appendix) for how RKHS methods suffer in higher dimensions. Whereas large $N$ and a natural choice of $\mathcal{D}$ make generalization for $\mathcal{S}_1$, and hence all three classes, nearly trivial, as discussed in section~\ref{sec:conc}. \subsection{Concentration across Input Size}\label{sec:conc} Consider the data distribution from which we sample, namely a measure from $ \mathcal{P}\left(\bar{\mathbb{I}} \right)$ to sample finite sets. A natural way to draw data is to consider the following sampling procedure: given $\xi \in \mathcal{P}(\mathcal{P}(\mathbb{I}))$ and $\Omega \in \mathcal{P}(\mathbb{N})$, draw $\mu \sim \xi$ and $N \sim \Omega$, sample $N$ independent points $x_i \sim \mu$, and return $\{x_1, \dots, x_N\}$. If $\xi$ is too peaked, this sampling process will concentrate very rapidly: \begin{proposition}\label{prop:concentration} For $\xi = \delta_{\mu^*}$, then $\mathbb{E} \sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left|\frac{1}{n} \sum_{i=1}^n \epsilon_i f(\mu_i) \right| \lesssim \delta R^2( n^{-1/2} + \mathbb{E}_{N \sim \Omega}[N^{-1/d}])$. \end{proposition} Hence, the question of generalization across differently sized sets becomes trivial if $N$ is large and $d$ is small. In our experiments, $N \approx d$, so we will nevertheless choose $\xi = \delta_{\mu}$ for some $\mu \in \mathcal{P}(\mathbb{I})$. We consider more exotic data distributions over measures in the experiments on robust mean estimation in Section~\ref{sec:robust_mean}. \section{Experimental Details and Additional Data} \paragraph{Synthetic Details:} For all experiments we use the same architecture. Namely, for an input set $x = (x_1, \dots, x_N)$, the network is defined as $f_N(x) = w_3^T\sigma(W_2 \frac{1}{N}\sum_{i=1}^N \sigma(W_1 \tilde{x}_i))$, where we choose the architecture as $W_1 \in \mathbb{R}^{h_1 \times d}$, $W_2 \in \mathbb{R}^{h_2 \times h_1}$, and $w_3 \in \mathbb{R}^{h_2}$. Here, $h_1, h_2 = 100$ for $\mathcal{S}_1$, $h_1 = 100$ and $h_2 = 1000$ for $\mathcal{S}_2$, and $h_1 = h_2 = 1000$ for $\mathcal{S}_3$. The weights are initialized with the uniform Kaiming initialization~\parencite{he2015delving} and frozen as described in Table~\ref{tab:freeze}. We relax the functional norm constraints to penalties, by introducing regularizers of the form $\lambda \|f_N\|_{\mathcal{S}_i}$ for $\lambda$ a hyperparameter. Let $K(\cdot)$ map a matrix to the vector of row-wise squared norms, and let $|\cdot|$ denote the element-wise absolute value of a matrix. Then we calculate the functional norms via the path norm as follows: \begin{itemize} \item For $\mathcal{S}_1$, $\|f_N\|_{\mathcal{S}_1} = |w_3|^T|W_2|K(W_1)$ \item For $\mathcal{S}_2$, we explicitly normalize the frozen matrix $W_1$ to have all row-wise norms equal to 1, then $\|f_N\|_{\mathcal{S}_2} = |w_3|^TK(W_2)$ \item For $\mathcal{S}_3$, we normalize the rows of $W_1$ and $W_2$, which simply implies $\|f_N\|_{\mathcal{S}_3} = \|w_3\|_2$ \end{itemize} We optimized via Adam~\parencite{kingma2014adam} with an initial learning rate of 0.0005, for 5000 iterations. Under this architecture, all $\mathcal{S}_1$, $\mathcal{S}_2$ and $\mathcal{S}_3$ functions achieved less than $10^{-15}$ training error without regularization on all objective functions (listed below) on training sets of 100 samples. We use the following symmetric functions for our experiments: \begin{itemize} \item $f_N^*(x) = \mathrm{max}_i(\|x_i\|_2^{-1})$ \item $f_N^*(x) = \lambda \log \left(\sum_{i=1}^N \exp(\|x_i\|_2^{-1} / \lambda) \right)$ for $\lambda = 0.1$ \item $f_N^*(x) = \mathrm{median}(\{\|x_i\|_2^{-1}\}_{i=1}^N)$ \item $f_N^*(x) = \mathrm{second}_i(\|x_i\|_2^{-1})$ i.e. the second largest value in a given set \item $f_N^*(x) = \frac{1}{N} \sum_{i=1}^N (\|x_i\|_2^{-1})$ \item $f_N^*(x) = \frac{2}{N(N-1)} \sum_{i < j} \frac{1}{\|x_i - x_j\|_2}$ \item $f_N^*(x)$ is an individual neuron, parameterized the same as $f_N$ but with different hidden layer sizes. For the neuron, $h_1 = h_2 = 1$, for the smooth\_neuron, $h_1 = 100$ and $h_2 = 1$. Additionally, the proof of Theorem~\ref{thm:s1s2} dictates that we must choose the neuron's test function to have large kernel norm, so we initialize $W_1$ elementwise from the Gaussian mixture with density $0.5 * \mathcal{N}(1, 0.5) + 0.5 * \mathcal{N}(-1, 0.5)$. \end{itemize} Note that in order to guarantee the ``smooth\_neuron" is representable by our finite-width networks, we explicitly set $W_1$ in the $\mathcal{S}_2$ and $\mathcal{S}_3$ models to equal the $W_1$ matrix of the ``smooth\_neuron". For each model in each experiment, $\lambda$ was determined through cross validation over $\lambda \in [0, 10^{-6}, 10^{-4}, 10^{-2}]$ using fresh samples of training data, and choosing the value of $\lambda$ with lowest generalization error, which was calculated from another 1000 sampled points. Then, with determined $\lambda$, each model was trained from scratch over 10 runs with independent random initializations. The mean and standard deviation of the generalization error, testing on varying values of $N$, are plotted in Figure~\ref{fig:plots}. \paragraph{Application Details:} For the MNIST experiment with results given in Table~\ref{tab:mnist}, we follow a similar setup to~\textcite{de2019stochastic}. From an image in $\mathbb{R}^{28 \times 28}$, we produce a point cloud by considering a set of tuples of the form $(r, c, t)$, which are the row, column and intensity respectively for each pixel. We restrict to pixels where $t > 0.5$, and select the pixels with the top 200 intensities to comprise the point cloud (if there are fewer than 200 pixels remaining after thresholding, we resample among them). Furthermore, we normalize the row and column values among all the points in the cloud. This process maps an image to a set $S \subseteq \mathbb{R}^3$ such that $|S| = 200$. For this dataset we consider $h_1 = 500$ and $h_2 = 500$ for our $\mathcal{S}_i$ finite-width architectures. We perform cross-validation by setting aside $10\%$ of the data as a validation set, and calculate the mean and standard deviation of the generalization error over five runs. In order to study generalization in this setting, we test on point clouds of different size, $100$ and $200$, and show the results in Table~\ref{tab:mnist}. The starting learning rate is $0.001$. Otherwise, all other experimental details are the same as above. \paragraph{Robust Mean Details:} We use the regular ReLU activation in the first layer for training stability. Each network is trained on a batch of 5000 input sets sampled as above, as the task of robust estimation appears more susceptible to overfitting than the simpler symmetric objectives learned in the previous section. All networks are trained for 30000 iterations, and all other details of training are kept consistent with the previous section (including the larger number of random kernel features). The hyperparameters required for the adversarial estimator in~\cite{diakonikolas2017being} are $\tau$ and ``cher", which both control the thresholding of which vectors are discarded according to the projection on the maximal eigenvector of the empirical covariance. Cross validation over the sets $[0.1, 0.15, 0.2]$ and $[1.5, 1.8, 2.0, 2.3]$ yielded the choices $\tau = 0.1$ and ``cher" $= 1.5$. \paragraph{Additional Experiments} In Figure~\ref{fig:plots_extra} we consider higher dimensional vectors for our set inputs to the symmetric models. In Figure~\ref{fig:plots_multi} we consider training over multiple set sizes as well, with the input size sampled uniformly from ${4, 5, 6}$. \begin{figure} \centering \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/maximum_flip_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/softmax_flip_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/mean_flip_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/median_flip_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/second_flip_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/potential_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/neuron_Wide_20_False_True_True.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/smooth_neuron_Wide_20_False_True_True.png} \end{subfigure}% \caption{Test Error for $d = 20$} \label{fig:plots_extra} \end{figure} \begin{figure} \centering \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/maximum_flip_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/softmax_flip_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/mean_flip_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/median_flip_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/second_flip_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/potential_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/neuron_Wide_10_False_True_True_multi.png} \end{subfigure}% \begin{subfigure}{.4\textwidth} \centering \includegraphics[width=1.\linewidth]{plots_revised/smooth_neuron_Wide_10_False_True_True_multi.png} \end{subfigure}% \caption{Test Error for varied input size training} \label{fig:plots_multi} \end{figure} We consider the Pointcloud MNIST dataset, after mapping our image to sets. This dataset is substantially more difficult than regular MNIST, as the induced sets obfuscate the geometric structure of the original images. The results on Pointcloud MNIST, across differently-sized set representations of images, are given in Table~\ref{tab:mnist}. The fact that we only consider three-layer networks limits the ability of the model to reconstruct the original image representation and perform comparably to a model acting on regular MNIST. Nevertheless, we still observe the expected ordering of our functional spaces. When testing on smaller sets than training, the generalization error increases faster for $\mathcal{S}_3$ than for $\mathcal{S}_1$ and $\mathcal{S}_2$. \begin{table} \centering \begin{tabular}{p{5pt}c|c|c} & & Error ($N = 100$) & Error ($N = 200$) \\ \hline & $\mathcal{S}_1$ & $8.03$ & $5.62$ \\ & $\mathcal{S}_2$ & $8.25$ & $5.78$ \\ & $\mathcal{S}_3$ & $14.45$ & $10.80$ \\ \end{tabular} \caption{Classification test error on Pointcloud MNIST in percent, after images are compressed into sets of size $N$, trained with $N = 200$.} \label{tab:mnist} \end{table} In Table~\ref{tab:robust_big_n} we consider the robust mean experiment, using the same hyperparameters except training on sets of larger size ($N = 60$) and plotting MSE on sets of varying size. As with the smaller scale experiment, we observe that $\mathcal{S}_1$ enjoys a slight advantage over the other methods when restricting attention to the in-distribution generalization setting of $N = 60$, but outside that range the performance is comparable to the naive sample mean, suggesting that out-of-distribution generalization for the robust mean is not easily attainable for these networks. \begin{table*}[h] \centering \begin{tabular}{p{5pt}c|c|c|c|c|c} & & $N = 20$ & $N = 40$ & $N = 60$ & $N = 80$ & $N = 100$ \\ \hline & $\mathcal{S}_1$ & $0.149 \pm 0.039$ & $0.073 \pm 0.023$ & $0.043 \pm 0.004$ & $0.034 \pm 0.004$ & $0.028 \pm 0.003$ \\ & $\mathcal{S}_2$ & $0.151 \pm 0.039$ & $0.076 \pm 0.023$ & $0.045 \pm 0.004$ & $0.036 \pm 0.004$ & $0.030 \pm 0.003$ \\ & $\mathcal{S}_3$ & $0.159 \pm 0.039$ & $0.081 \pm 0.023$ & $0.050 \pm 0.004$ & $0.040 \pm 0.004$ & $0.034 \pm 0.003$ \\ \hline \hline & Sample Mean & $0.152 \pm 0.069$ & $0.066 \pm 0.029$ & $0.055 \pm 0.025$ & $0.034 \pm 0.015$ & $0.026 \pm 0.012$\\ & Geometric Median & $0.137 \pm 0.062$ & $0.063 \pm 0.028$ & $0.047 \pm 0.021$ & $0.032 \pm 0.014$ & $0.025 \pm 0.011$ \\ & Adversarial Estimator & $0.472 \pm 0.545$ & $0.386 \pm 0.555$ & $0.346 \pm 0.546$ & $0.282 \pm 0.521$ & $0.206 \pm 0.455$\\ \end{tabular} \caption{Mean squared test error for robust mean estimation among the finite model instantiations and baselines.} \label{tab:robust_big_n} \end{table*} \section{Introduction} Deep learning becomes far more efficient with prior knowledge of function invariants. This knowledge underlies architectural choices that enforce the invariance or equivariance in the network, including Convolutional Neural Networks \parencite{lecun1998gradient} which encode translation symmetries, and Graph Neural Networks \parencite{scarselli2008graph} which encode conjugate permutation symmetries. For functions with invariance to permutation of the input elements, several universal architectures encode this invariance by treating the input as a set~\parencite{zaheer2017deep, qi2017pointnet}. However, these formulations assume a constant input size, which precludes learning an entire family of symmetric functions. Such symmetric functions appear naturally across several domains, including particle physics, computer graphics, population statistics and cosmology. Yet, in most of these applications, the input size corresponds to a sampling parameter that is independent of the underlying symmetric function of interest. As a motivating example, consider the function family induced by the max function, where for varying $N$, $f_N(\{x_1\dots x_N\}) = \max_{i\leq N} x_i$. It is natural to ask if a network can simultaneously learn all these functions. In this work, we interpret input sets as an empirical measure defined over the base space $\mathbb{I}$, and develop families of neural networks defined over the space of probability measures \emph{probability measures of $\mathbb{I}$}, as initially suggested in \textcite{pevny2019approximation,de2019stochastic}. We identify functional spaces characterized by neural architectures and provide generalization bounds that showcase a natural hierarchy among spaces of symmetric functions. In particular, our framework allows us to understand the question of generalizing across input sizes as a corollary. Our constructions rely on the theory of infinitely wide neural networks \parencite{bengio2006convex, rosset2007,bach2017breaking}, and provide a novel instance of \emph{depth separation} leveraging the symmetric structure of the input. \paragraph{Summary of Contributions:} We consider the infinite-width limit of neural networks taking as domain the space of probability measures in order to formalize learning of symmetric function families. We prove a necessary and sufficient condition for which symmetric functions can be learned. By controlling the amount of non-linear learning, we partition the space of networks on measures into several function classes, proving a separation result among the classes as well as proving a generalization result and empirically studying the performance of these classes to learn symmetric functions on synthetic and real-world data. \section*{Broader Impact} \printbibliography \newpage \section{Omitted Proofs} \begin{table \centering \caption{Summary of Notation} \label{tab:notation} \begin{tabular}{lp{11cm}} \toprule \textbf{Notation} & \textbf{Definition}\\ \midrule $\mathbb{I}$ & Input domain, subset of $\mathbb{R}^d$\\ $\overline{\mathbb{I}}$ & $\bigcup_{N=1}^\infty \mathbb{I}^N$\\ $\A_i$ & Classes of test functions $\mathbb{I} \rightarrow \mathbb{R}$\\ $\gamma_i$ & Test function norm\\ $\mathcal{S}_i$ & Class of functions mapping $\mathcal{P}(\mathbb{I}) \rightarrow \mathbb{R}$\\ $\|\cdot\|_{\mathcal{S}_i}$ & Measure network norm\\ $D$ & Map from vectors to empirical measures s.t. $D(x_1 \dots x_n) = \sum_{i=1}^n \delta_{x_i}$\\ $\hat{\mathcal{P}}(\mathbb{I})$ & $\bigcup_{N=1}^\infty D(\mathbb{I}^N)$\\ $\kappa$ & Fixed probability measure over $\mathbb{S}^d$ in first layer\\ $\nu$ & Signed measure over $\mathbb{S}^d$ in first layer\\ $\tau$ & Fixed probability measure over $\A_i$ in second layer\\ $\chi$ & Signed measure over $\A_i$ in second layer\\ $Y_{k,j}$ & Orthogonal basis polynomial of degree $k$ and index $j$ on $\mathbb{S}^d$\\ $P_k$ & Legendre polynomial of degree $k$\\ $g_k$ & the $k$th spherical harmonic of a function $g: \mathbb{S}^d \rightarrow \mathbb{R}$\\ \bottomrule \end{tabular} \end{table} \subsection{Proof of Proposition \ref{prop:extension}} \begin{proof} We remind our notation. Given $f: \mathbb{I} \rightarrow \mathbb{R}$, the empirical extension $\hat{f}: \hat{\mathcal{P}}(\mathbb{I}) \rightarrow \mathbb{R}$ is defined as $\hat{f}(\mu) := f(x_\mu)$ where $x_\mu \in D^{-1}(\mu)$ and $\|x_\mu\|_0 = \min_{x \in D^{-1}(\mu)} \|x\|_0$. And for $\bar{f}: \mathcal{P}(\overline{\mathbb{I}}) \rightarrow \mathbb{R}$, we say this is a continuous extension of $f$ if $\bar{f}$ is continuous in under the Wasserstein metric, and $f(x) = \bar{f}(D(x))$ for every real, finite-dimensional vector $x$. For the forward implication, if $\bar{f}$ is a continuous extension, then clearly $\bar{f} = \hat{f}$ restricted to $\hat{\mathcal{P}}(\mathbb{I})$. Furthermore, continuity of $\bar{f}$ and compactness of $\mathcal{P}(\mathbb{I})$ implies $\bar{f}$ is uniformly continuous, and therefore $\hat{f}$ is as well. For the backward implication, we introduce $\hat{f}_\epsilon(\mu) = \sup_{\nu \in B_\epsilon(\mu) \cap \hat{\mathcal{P}}(\mathbb{I})} \hat{f}(\nu)$ where the ball $B_\epsilon(\mu)$ is defined with the Wasserstein metric. Note that $\hat{f}_\epsilon$ is defined over arbitrary probability measures, not just discrete measures. Now, we introduce $\bar{f}(\mu) = \inf_{\epsilon > 0} \hat{f}_\epsilon(\mu)$, where density of the discrete measures and uniform continuity of $\hat{f}$ guarantees that $\bar{f}$ is well-defined and finite. Uniform continuity implies if $\mu \in \hat{\mathcal{P}}(\mathbb{I})$ then $\bar{f}(\mu) = \hat{f}(\mu)$. Consider any $y \in \mathbb{I}^M$ such that $\mu = D(y)$, and define a sequence of vectors $y^i = (z_i, y_2, \dots, y_M)$ where $z_i \rightarrow y_1$ and all $z_i$ are distinct from elements of $y$. Every point $y^i \in \mathbb{I}^M$ has a unique coordinate and therefore $\hat{f}(D(y^i)) = f_M(y^i)$. Because $D(y^i) \rightharpoonup D(y)$, continuity implies $\hat{f}(D(y)) = f_M(y)$. Thus, for any $y \in \mathbb{I}^M$, $\bar{f}(D(y)) = f_M(y)$, which implies $\bar{f}$ is an extension. Now, suppose we have an arbitrary convergent sequence of probability measures $\mu_n \rightharpoonup \mu$. By the density of discrete measures, we can define sequences $\mu_n^m \rightharpoonup \mu_n$ where $\mu_n^m \in \hat{\mathcal{P}}(\mathbb{I})$. In particular, we may choose these sequences such that for all $n$, $W_1(\mu_n^m, \mu_n) \leq \frac{1}{m}$. Then for any $\epsilon > 0$, \begin{align*} |\bar{f}(\mu) - \bar{f}(\mu_n)| \leq |\bar{f}(\mu) - \hat{f}_\epsilon(\mu)| + |\hat{f}_\epsilon(\mu) - \hat{f}(\mu_n^n)| + |\hat{f}(\mu_n^n) - \hat{f}_\epsilon(\mu_n)| + |\hat{f}_\epsilon(\mu_n) - \bar{f}(\mu_n)|~. \end{align*} Consider the simultaneous limit as $n \rightarrow \infty$ and $\epsilon \rightarrow 0$. On the RHS, the first term vanishes by definition, and the fourth by uniform continuity. For any $\nu \in B_\epsilon(\mu) \cap \hat{\mathcal{P}}(\mathbb{I})$, $W_1(\nu, \mu_n^n) \leq W_1(\nu, \mu) + W_1(\mu, \mu_n) + W_1(\mu_n, \mu_n^n) \rightarrow 0$ in the limit. So the second term vanishes as well by uniform continuity of $\hat{f}$. Similarly, for any $\nu \in B_\epsilon(\mu_n) \cap \hat{\mathcal{P}}(\mathbb{I})$, $W_1(\nu, \mu_n^n) \leq W_1(\nu, \mu_n) + W_1(\mu_n, \mu_n^n) \rightarrow 0$, and the third term vanishes by uniform continuity. This proves continuity of $\bar{f}$. \end{proof} \subsection{Proof of Proposition \ref{prop:rad}} \begin{proof} We can decompose the generalization error: \begin{align*} \mathbb{E} & \sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left| \mathbb{E}_{\mu \sim \mathcal{D}} \ell(f^*(\mu), f(\mu)) - \frac{1}{n} \sum_{i=1}^n \ell(f^*(\mu_i), f(\mu_i)) \right| \\ & \leq 2\mathbb{E} \sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left|\frac{1}{n} \sum_{i=1}^n \epsilon_i \ell(f^*(\mu_i), f(\mu_i)) \right| \\ & \leq 2\mathbb{E} \sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left|\frac{1}{n} \sum_{i=1}^n \epsilon_i \ell(f^*(\mu_i), 0) \right| + 2\mathbb{E} \sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left|\frac{1}{n} \sum_{i=1}^n \epsilon_i (\ell(f^*(\mu_i), 0) - \ell(f^*(\mu_i), f(\mu_i))) \right| \\ & \leq \frac{2RG\delta}{\sqrt{n}} + 4R^2G\mathbb{E} \sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \left|\frac{1}{n} \sum_{i=1}^n \epsilon_i f(\mu_i) \right| ~, \end{align*} where the second step uses symmetrization through the Rademacher random variable $\epsilon$, and the fourth is by assumption on the loss function $\ell$, from the fact that $\|f\|_{\mathcal{S}_1} \leq \delta$ implies $\|f\|_\infty \leq 2R^2\delta$. We decompose the Rademacher complexity (removing the absolute value by symmetry): \begin{align*}\label{eq:rademacher_start} \mathbb{E} \left[\sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \frac{1}{n} \sum_{i=1}^n \epsilon_i f(\mu_i) \right] & = \mathbb{E} \left[\sup_{\substack{\chi \in \mathcal{M}(\mathcal{A}) \\ \|\chi\|_{TV} \leq \delta}} \frac{1}{n} \sum_{i=1}^n \epsilon_i \int \sigma(\langle \phi, \mu_i \rangle) \chi(d \phi) \right] \\ & = \delta \mathbb{E} \left[\sup_{\gamma_1(\phi) \leq 1} \frac{1}{n} \sum_{i=1}^n \epsilon_i \sigma(\langle \phi, \mu_i \rangle) \right] \\ & \leq \delta \mathbb{E} \left[\sup_{\gamma_1(\phi) \leq 1} \frac{1}{n} \sum_{i=1}^n \epsilon_i \langle \phi, \mu_i \rangle \right]~, \end{align*} where the last step uses the contraction lemma and that $\sigma$ is 1-Lipschitz. Now, using the neural network representation of $\phi$: \begin{align*} \mathbb{E} \left[\sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \frac{1}{n} \sum_{i=1}^n \epsilon_i f(\mu_i) \right] & \leq \delta \mathbb{E} \left[\sup_{\|\nu\|_{TV} \leq 1} \frac{1}{n} \sum_{i=1}^n \epsilon_i \int_{\mathbb{R}^d} \int_{\mathbb{S}^{d}} \sigma(\langle w, \tilde{x}_i \rangle)^2 \nu(dw) \mu_i(dx_i) \right] \\ & \leq \delta \mathbb{E} \left[\sup_{\|w\|_2 \leq 1} \frac{1}{n} \sum_{i=1}^n \epsilon_i \mathbb{E}_{\mu_i}[\sigma(\langle w, \tilde{x}_i \rangle)^2] \right] \\ & \leq \delta \mathbb{E}_{\mu_1, \dots, \mu_n} \left[ \mathbb{E} \left[\sup_{\|w\|_2 \leq 1} \frac{1}{n} \sum_{i=1}^n \epsilon_i \sigma(\langle w, \tilde{x}_i \rangle)^2 \middle| x_1, \dots, x_n \right] \right]~, \\ \end{align*} where the last step uses Jensen's inequality and Fubini's theorem. The conditional expectation is itself a Rademacher complexity, so we may apply the contraction lemma again as the $\sigma(\langle w, \tilde{x}_i \rangle)^2$ activation is $2\sqrt{2}R$-Lipschitz for the domain $\mathbb{I}$ of $\tilde{x}_i$. Using the variational definition of the $l_2$ norm we have the bound: \begin{align*} \mathbb{E} \left[\sup_{\|f\|_{\mathcal{S}_1} \leq \delta} \frac{1}{n} \sum_{i=1}^n \epsilon_i f(\mu_i) \right] \leq \frac{ 4R^2\delta}{\sqrt{n}}~. \end{align*} The high probability bound then follows from McDiarmid's inequality. \end{proof} \subsection{Proof of Proposition~\ref{prop:concentration}} \begin{proof} We appeal to the following concentration inequality for empirical measures under the Wasserstein metric: \begin{theorem}[Theorem 1 in~\textcite{fournier2015rate}] Let $\hat{\mu}_N = \frac{1}{N} \sum_{j=1}^N \delta_{X_j}$ where $X_i \sim \mu \in \mathcal{P}(\mathbb{I})$ iid. Then $\mathbb{E}[W_1(\hat{\mu}_N, \mu)] \lesssim N^{-1/d}$ where $d > 2$ is the dimension of $\mathbb{I}$. \end{theorem} It's easy to see that any $\phi \in \A_2$ has Lipschitz constant bounded above by $2\sqrt{2}R$, and therefore $\sup_{\phi \in \A_2}|\langle \phi, \mu - \mu^* \rangle| \leq 2\sqrt{2}R W_1(\mu, \mu^*)$. Therefore \begin{align*} \mathbb{E} \left[\sup_{\phi \in \mathcal{A}} \frac{1}{n} \sum_{i=1}^n \epsilon_i \left \langle \phi, \mu_i \right\rangle \right] & \leq \mathbb{E} \left[\sup_{\phi \in \mathcal{A}} \frac{1}{n} \sum_{i=1}^n \epsilon_i\left\langle \phi, \mu^* \right\rangle \right] + \mathbb{E} \left[\sup_{\phi \in \mathcal{A}} \frac{1}{n} \sum_{i=1}^n \epsilon_i \left\langle \phi, (\mu^* - \mu_i) \right\rangle \right] \\ & \leq 2R^2 \mathbb{E} \left[\left|\frac{1}{n} \sum_{i=1}^n \epsilon_i \right| \right] + 2\sqrt{2}R \mathbb{E}[W_1(\mu_i, \mu^*)] \\ & \lesssim R^2(n^{-1/2} + \mathbb{E}_{N \sim \Omega}[N^{-1/d}])~. \end{align*} The conclusion then follows from the same Rademacher decomposition as in Proposition~\ref{prop:rad}. \end{proof} \subsection{Proof of Theorem \ref{thm:inclusion}} For simplicity, we consider spherical inputs rather than Euclidean inputs, and so we may consider $k(x,y) = \int_{\mathbb{S}^d} \sigma(\langle w, x \rangle) \sigma(\langle w, y \rangle) \kappa(d w)$ without the $\tilde{x}$ bias terms, and assume $x \in \mathbb{S}^d$. Note that the Euclidean inputs may be seen as a restriction of the spherical inputs to an appropriate spherical cap, see~\textcite{bach2017breaking} for details of this construction. \subsubsection{Spherical Harmonics and Kernel Norm Background} We'll use $\simeq$ to denote equality up to universal constants. To understand functions in $\A_2$, we require the following details of spherical harmonics~\cite{efthimiou2014spherical}. A basis on $\mathbb{S}^d$ is given by the orthogonal polynomials $Y_{k,j}$, where $k \geq 0$ and $ 1 \leq j \leq N(d,k)$ where \begin{align*} N(d,k) &\simeq \frac{k+d}{k} \frac{\Gamma(k+d-1)}{\Gamma(d)\Gamma(k)}\\ &\simeq \frac{k+d}{k} \frac{(k+d)^{k+d - 3/2}}{d^{d-1/2}k^{k-1/2}} \end{align*} The Legendre polynomials $P_k(t)$ act on one dimensional real inputs and satisfy the addition formula \begin{align*} \sum_{j=1}^{N(d,k)} Y_{k,j}(x) Y_{k,j}(y) = N(d,k) P_k(\langle x, y \rangle) \end{align*} Finally, given a function $g: \mathbb{S}^d \rightarrow \mathbb{R}$, the $k$th spherical harmonic of $g$ is the degree $k$ component of $g$ in the orthogonal basis, equivalently written as \begin{align*} g_k(x) = \int_{\mathbb{S}^d} g(y) P_k(\langle x, y \rangle) \kappa(dy) \end{align*} We also require several calculations on functions with bounded functional norm and projections~\cite{bach2017breaking}, where we remind that we're using the activation $\sigma(x)^2$. For $g \in \A_2$ or $g(x) = \sigma(\langle w, x \rangle)^2$ for any $w \in \mathbb{S}^d$, we have that $g_{2k} = 0$ for all $k \geq 2$. For $g \in \A_2$, the norm of each harmonic satisfies $\|g_k\|_2^2 = \lambda_k^2 N(d,k)$, and the kernel norm can be calculated explicitly as \begin{align*} \gamma_2(g)^2 = \sum_{k=0, \lambda_k \neq 0}^\infty \lambda_k^{-2} \|g_k\|_{L_2}^2 \end{align*} We have that $\lambda_1 \simeq d^{-1}$, $\lambda_k = 0$ for $k \geq 3$ and $k$ even, and for $k \geq 3$ and $k$ odd: \begin{equation} \lambda_k \simeq \pm \frac{d^{d/2 + 1/2} k^{k/2 - 3/2}}{(d+k)^{k/2 + d/2 + 1}} \end{equation} \subsubsection{Separation of $\mathcal{S}_1$ and $\mathcal{S}_2$} Let $g(x) = \sigma(\langle x, w \rangle)^2$ for an arbitrary $w \in \mathbb{S}^d$, we have that $\|g_k\|_2^2 = \lambda_k^2 N(d,k)$. Define $\tilde{g} = g - \sum_{i=0}^{d^2-1} g_i$. The following lemmas capture that $\tilde{g}$ has high correlation with $g$ and exponentially small correlation with functions in $\A_2$. \begin{lemma}\label{lem:correlation-lower-bound} The correlation lower bound $\langle g, \tilde{g} \rangle \gtrsim d^{-21/2}$ holds. \end{lemma} \begin{proof} Note that \begin{equation} \langle g, \tilde{g} \rangle = \sum_{k=d^2} \|g_k\|_2^2 = \sum_{k=d^2} \lambda_k^2 N(d,k) \end{equation} We can calculate, because $k+d \leq 2k$: \begin{align*} \lambda_k^2 N(d,k) & \simeq \frac{d^{d + 1} k^{k - 3}}{(d+k)^{k + d + 2}} \cdot \frac{k+d}{k} \frac{(k+d)^{k+d - 3/2}}{d^{d-1/2}k^{k-1/2}} \\ & \simeq d^{3/2} k^{-7/2} (k+d)^{-7/2}\\ & \gtrsim d^{3/2} k^{-7} \end{align*} And therefore \begin{align*} \langle g, \tilde{g} \rangle \gtrsim \sum_{k=d^2}^\infty d^{3/2} k^{-7} \geq d^{3/2} \int_{d^2}^\infty k^{-7} dk \simeq d^{3/2} (d^2)^{-6} \end{align*} which yields the desired lower bound. \end{proof} \begin{lemma}\label{lem:correlation-upper-bound} The value of the optimization problem \begin{equation*} \begin{aligned} \max_{\phi} \quad & \langle \phi, \tilde{g} \rangle_{L_2}\\ \textrm{s.t.} \quad & \gamma_2(\phi)^2 \leq \delta^2 \end{aligned} \end{equation*} is upper bounded by $\delta \cdot d^{1/2-d/3}$ \end{lemma} \begin{proof} By orthogonality we may assume $\phi_k = \alpha_k \tilde{g}_k = \alpha_k g_k$, where $\alpha_k = 0$ for $k < d^2$. Then the problem is equivalently \begin{equation*} \begin{aligned} \min_{\alpha} \quad & - \sum_{k=d^2}^\infty \alpha_k \|g_k\|_2^2 \\ \textrm{s.t.} \quad & \sum_{k=d^2}^\infty \alpha_k^2 \lambda_k^{-2} \|g_k\|_2^2 \leq \delta^2 \end{aligned} \end{equation*} Taking $\lambda$ as a Lagrangian multiplier yields the optimality condition $\alpha_k = (2\lambda)^{-1} \lambda_k^2$. Plugging this into the constraint and introducing notation $S$ yields \begin{align*} (2\lambda)^{-2} S : = (2\lambda)^{-2} \sum_{k=d^2}^\infty \lambda_k^2 \|g_k\|_2^2 \leq \delta^2 \end{align*} Then the objective (returned to a maximum) obeys the bound \begin{align*} \sum_{k=d^2} (2\lambda)^{-1} \lambda_k^2 \|g_k\|_2^2 & = (2\lambda)^{-1} S\\ & \leq \delta \sqrt{S} \end{align*} So it remains to calculate $S$. Plugging in the value of $\|g_k\|_2^2$ gives \begin{equation*} S = \sum_{k=d^2}^\infty \lambda_k^4 N(d,k) \end{equation*} We can give the form of each term, using that $k \geq d^2$: \begin{align*} \lambda_k^4 N(d,k) & \lesssim d^{3/2} k^{-7} \frac{d^{d + 1} k^{k - 3}}{(d+k)^{k + d + 2}}\\ & \lesssim d^{3/2} k^{-7} \frac{d^{d + 1} k^{k - 3}}{k^{k + d + 2}}\\ & \lesssim d^{5/2} k^{-12} \left(\frac{d}{k} \right)^d\\ & \lesssim d^{5/2} k^{-12} \left(\frac{d}{k^{1/2}} \cdot \frac{1}{k^{1/2}}\right)^d\\ & \lesssim d^{5/2} k^{-12} k^{-d/2}\\ \end{align*} For sufficiently large $d$, we may ignore the lower terms and reduce the exponential term to $k^{-d/3}$, then: \begin{align*} S \lesssim \sum_{k=d^2}^\infty k^{-d/3} \simeq \int_{d^2}^\infty k^{-d/3} \simeq d^{-1}(d^2)^{1-d/3} \end{align*} The bound follows. \end{proof} Let $h = g - g_0 - g_2$, and define $f_1(\mu) = d^{-1}\sigma(\langle h, \mu \rangle)$, remembering that we're using the regular ReLU for the measure network activation. \begin{lemma} $\|f_1\|_{\mathcal{S}_1} \lesssim 1$. \end{lemma} \begin{proof} It suffices to bound $\gamma_1(h)$, remembering that our test functions are defined using networks with the squared ReLU activation. Clearly $\gamma_1(g) \leq 1$ as it itself a single neuron. For the other terms, we can write the harmonics explicitly, using the fact that $P_0(t) = 1$ and $P_2(t) = \frac{(d+1)t^2 - 1}{d}$. Starting with the constant term $g_0$: \begin{align*} g_0(x) &= \int_{\mathbb{S}^d} g(y) \kappa(dy)\\ & = \int_{\mathbb{S}^d} \sigma(\langle w, y \rangle)^2 \kappa(dy)\\ & = \int_{\mathbb{S}^d} \sigma(y_1)^2 \kappa(dy)\\ & = \frac{1}{2(d+1)} \end{align*} Note that $\sigma(z)^2 + \sigma(-z)^2 = z^2$, so we can represent a constant function as a neural network via: \begin{align*} \sum_{i=1}^{d+1} \sigma(\langle e_i, x\rangle)^2 + \sigma(\langle -e_i, x\rangle)^2 & = \sum_{i=1}^{d+1} \langle e_i, x \rangle^2\\ & = \|x\|_2 = 1 \end{align*} So we have $\gamma_1(g_0) \leq 1$. The second spherical harmonic is given as: \begin{align*} g_2(x) &= N(d,2) \int_{\mathbb{S}^d} g(y) \frac{(d+1)\langle x, y \rangle^2 - 1}{d} \kappa(dy)\\ &= \frac{N(d,2)}{d} \left((d+1)\int_{\mathbb{S}^d} g(y) \langle x, y \rangle^2 \kappa(dy) - \int_{\mathbb{S}^d} g(y) \kappa(dy) \right) \end{align*} We can represent the constant term as above, and the first integral as \begin{align*} \int_{\mathbb{S}^d} \sigma(\langle w, y \rangle)^2 \langle x, y \rangle^2 \kappa(dy) & = \int_{\mathbb{S}^d} \sigma(\langle w, y \rangle)^2 (\sigma(\langle x, y \rangle)^2 + \sigma(\langle x, -y \rangle)^2) \kappa(dy) \\ & = \int_{\mathbb{S}^d} \sigma(\langle x, y \rangle)^2 (\sigma(\langle w, y \rangle)^2 + \sigma(\langle w, -y \rangle)^2 ) \kappa(dy) \\ & = \int_{\mathbb{S}^d} \sigma(\langle x, y \rangle)^2 \langle w, y \rangle^2 \kappa(dy) \end{align*} This last line is a convex neural network representation using the squared ReLU activation, and thus we have $\gamma_1\left(\int_{\mathbb{S}^d} g(y) \langle x, y \rangle^2 \kappa(dy)\right) \leq \int_{\mathbb{S}^d} \langle w, y \rangle^2 \kappa(dy) = \frac{1}{d+1}$. Thus, $\gamma_1(g_2) \leq \frac{N(d,2)}{d} \left(1 + 1\right) \lesssim d$. And all together, $\gamma_1(h) \leq \gamma_1(g) + \gamma_1(g_0) + \gamma(g_2) \lesssim d$. So by homogeniety the bound on $\|f\|_{\mathcal{S}_1}$ follows. \end{proof} Our choice of $f_1$ induces a separation between $S_1$ and $S_2$. \begin{theorem}\label{thm:s1s2} We have that $\|f_1\|_{\mathcal{S}_1} \lesssim 1$, and \begin{equation} \inf_{\|f\|_{\mathcal{S}_2} \leq \delta} \|f - f_1\|_\infty \gtrsim |d^{-11} - d^{-d/3}\delta| \end{equation} \end{theorem} \begin{proof} Because we've subtracted out the $0$th and $2$nd harmonics, and all other even harmonics are zero, $\tilde{g}$ and $h$ are odd functions. Consider the signed measure $\nu(dx) := \frac{2\tilde{g}(x)}{\|\tilde{g}\|_{L_1}} \kappa(dx)$, with Jordan decomposition $\nu = \nu^+ - \nu^-$ with the positive measures $\nu^+(dx) := \frac{2\sigma(\tilde{g}(x))}{\|\tilde{g}\|_{L_1}} \kappa(dx)$ and $\nu^-(dx) := \frac{2\sigma(-\tilde{g}(x))}{\|\tilde{g}\|_{L_1}} \kappa(dx)$. Note that from the oddness of $\tilde{g}$ and symmetry of $\kappa$: \begin{align*} TV(\nu^-) & = \frac{2}{\|\tilde{g}\|_{L_1}}\int_{\mathbb{S}^d} \sigma(-\tilde{g}(x)) \kappa(dx)\\ & = \frac{2}{\|\tilde{g}\|_{L_1}}\int_{\mathbb{S}^d} \sigma(\tilde{g}(-x)) \kappa(dx)\\ & = \frac{2}{\|\tilde{g}\|_{L_1}}\int_{\mathbb{S}^d} \sigma(\tilde{g}(x)) \kappa(dx)\\ & = TV(\nu^+) \end{align*} Because $TV(\nu^+) + TV(\nu^-) = TV(\nu) = 2$, we conclude $\nu^+$ and $\nu^-$ are both probability measures. We'll use these measures to separate $f$ and $f_1$. By Lipschitz continuity of $\sigma$: \begin{align*} |f(\nu^+) - f(\nu^-)| & = \left|\int_{\mathbb{S}^d} \sigma(\langle \phi, \nu^+ \rangle) - \sigma(\langle \phi, \nu^- \rangle) \chi(d \phi) \right|\\ & \leq \int_{\mathbb{S}^d} |\sigma(\langle \phi, \nu + \nu^- \rangle) - \sigma(\langle \phi, \nu^- \rangle)| \chi(d \phi)\\ & \leq \sup_{\gamma_2(\phi) \leq 1} |\langle \phi, \nu \rangle| \|f\|_{\mathcal{S}_2} \\ & \leq \frac{2}{\|\tilde{g}\|_{L_1}} \sup_{\gamma_2(\phi) \leq 1} |\langle \phi, \tilde{g} \rangle| \|f\|_{\mathcal{S}_2} \\ & \lesssim \frac{2}{\|\tilde{g}\|_{L_1}} d^{1/2-d/3} \delta \end{align*} where in the last line we use Lemma~\ref{lem:correlation-upper-bound}. Concerning the function $f_1$, we first use oddness again to notice: \begin{align*} \langle h, \nu^- \rangle & = \frac{2}{\|\tilde{g}\|_{L_1}} \int_{\mathbb{S}^d} h(x) \sigma(-\tilde{g}(x)) \kappa(dx)\\ & = \frac{2}{\|\tilde{g}\|_{L_1}} \int_{\mathbb{S}^d} h(x) \sigma(\tilde{g}(-x)) \kappa(dx)\\ & = \frac{2}{\|\tilde{g}\|_{L_1}} \int_{\mathbb{S}^d} h(-x) \sigma(\tilde{g}(x)) \kappa(dx)\\ & = -\langle h, \nu^+ \rangle \end{align*} So $\langle h, \nu \rangle = \langle h, \nu^+ - \nu^-\rangle = 2 \langle h, \nu^+ \rangle$, and therefore from Lemma~\ref{lem:correlation-lower-bound} with $\alpha = 2$, \begin{align*} d^{-21/2} \lesssim \langle g, \tilde{g} \rangle & = \langle h, \tilde{g} \rangle\\ & = \frac{\|\tilde{g}\|_{L_1}}{2} \langle h, \nu \rangle\\ & = \|\tilde{g}\|_{L_1} \langle h, \nu^+ \rangle \end{align*} So $\langle h, \nu^+ \rangle \gtrsim \frac{d^{-21/2}}{\|\tilde{g}\|_{L_1}} $, and we conclude \begin{align*} |f_1(\nu^+) - f_1(\nu^-)| & = d^{-1}|\sigma(\langle h, \nu^+ \rangle) - \sigma(\langle h, \nu^- \rangle)|\\ &= d^{-1}\sigma(\langle h, \nu^+\rangle)\\ & \gtrsim \frac{d^{-23/2}}{\|\tilde{g}\|_{L_1}} \end{align*} Now, suppose $\|f-f_1\|_\infty \leq \epsilon$. Then \begin{align*} \frac{d^{-23/2}}{\|\tilde{g}\|_{L_1}} & \lesssim |f_1(\nu^+) - f_1(\nu^-)|\\ & \leq |f_1(\nu^+) - f(\nu^+)| + |f(\nu^+) - f(\nu^-)| + |f(\nu^-) - f_1(\nu^-)|\\ & \lesssim \epsilon + \frac{2}{\|\tilde{g}\|_{L_1}} d^{1/2-d/3} \delta + \epsilon \end{align*} So for sufficiently large $d$, we have $\frac{|d^{-23/2} - d^{1/2-d/3}\delta|}{\|\tilde{g}\|_{L_1}} \lesssim \epsilon$. Finally, note by Jensen's inequality and spherical harmonic orthogonality that $\|\tilde{g}\|_{L_1} \leq \|\tilde{g}\|_{L_2} \leq \|g\|_{L_2} \lesssim d^{-1/2}$. \end{proof} \subsubsection{Separation of $\mathcal{S}_2$ and $\mathcal{S}_3$} In order to instantiate the class $\mathcal{S}_3$, we must fix $\tau$, the base probability measure over test functions in $\A_2$. Consider some probability distribution $\zeta$ over the square-summable sequences $l_2(\mathbb{R^+})$ such that for $c \in supp(\zeta)$, $\sum_{k=0}^\infty c_k^2 = 1$. Furthermore, we will make the simplyfing assumption that $c_0 = 0$. For each $k$ let $\kappa_k$ be uniform over $\mathbb{S}^{N(d,k)-1}$, and note that $N(d,1) = d+1$ so $\kappa = \kappa_1$. Then we sample $\phi \sim \tau$ as $\phi = \sum_{k=1}^\infty \sum_{j=0}^{N(d,k)} \lambda_k c_k \alpha_{kj} Y_{kj}$ where $c \sim \zeta$ and $\alpha_k \sim \kappa_k$. Observe that $$\gamma_2(\phi)^2 = \sum_{k=1, \lambda_k \neq 0}^\infty \sum_{j=1}^{N(d,k)} \lambda_k^{-2} \lambda_k^2 c_k^2 \alpha_{kj}^2 = 1$$ so $\tau$ indeed samples functions from $\A_2$. We define $f_2(\mu) = \sigma(\langle g, \mu \rangle)$ where $g = \lambda_{1} Y_{1,1}$. Clearly $\gamma_2(g)^2 = \lambda_{1}^{-2} \lambda_{1}^2 \|Y_{1,1}\|_{L_2}^2 = 1$, so $\|f_2\|_{\mathcal{S}_2} \leq 1$. \begin{theorem}\label{thm:s2s3} We have that $\|f_2\|_{\mathcal{S}_2} \leq 1$, and \begin{equation} \inf_{\|f\|_{\mathcal{S}_3} \leq \delta} \|f - f_2\|_\infty \gtrsim d^{-2} \delta^{-5/d} \end{equation} \end{theorem} \begin{proof} Consider the function $h(x) = \sum_{j=1}^{N(d,1)} \beta_{1,j} Y_{1,j}$ and probability measure $\mu_\beta^*(dx) = \frac{h(x) + \|h\|_\infty}{\|h + \|h\|_\infty\|_{L_1}} \kappa(dx)$. Observe that \begin{align*} f_2(\mu_\beta^*) = \frac{\lambda_{1}}{\|h + \|h\|_\infty\|_{L_1}} \sigma(\langle e_1, \beta \rangle) \end{align*} For a function $f \in \mathcal{S}_3$ with density $q$ with respect to $\tau$, we have: \begin{align*} f(\mu_\beta^*) &= \int_{\A_2} \sigma(\langle \phi, \mu_\beta^* \rangle) q(\phi) \tau(d\phi) \\ & = \frac{\lambda_{1}}{\|h + \|h\|_\infty\|_{L_1}} \int_{l_2(\mathbb{R^+})} \int_{\mathbb{S}^d} \sigma(\langle c_1 \alpha_1, \beta \rangle) \hat{q}(c, \alpha_1) \kappa(d \alpha_1) \zeta(d c)\\ & = \frac{\lambda_{1}}{\|h + \|h\|_\infty\|_{L_1}} \int_{\mathbb{S}^d} \sigma(\langle \alpha_1, \beta \rangle) \left[ \int_{l_2(\mathbb{R^+})} c_1 \hat{q}(c, \alpha_1) \zeta(d c) \right] \kappa(d \alpha_1) \\ \end{align*} where $\hat{q}$ marginalizes out all other $\alpha_k$ terms. Let $\tilde{q}(\alpha_1) = \int_{l_2(\mathbb{R^+})} c_1 \hat{q}(c, \alpha_1) \zeta(d c)$. From the fact that $c_1 \leq 1$, and by Jensen's inequality, $\|\tilde{q}\|_{L_2(\kappa)} \leq \|\hat{q}\|_{L_2(\kappa \times \zeta)} \leq \|q\|_{L_2(\tau)}$. Now we may appeal to a separation of test function representations acting on spherical inputs. From D.5 in~\cite{bach2017breaking}, there exists some $\beta \in \mathbb{S}^d$ such that \begin{align*} |\sigma(\langle e_1, \beta \rangle) - \int_{\mathbb{S}^d} \sigma(\alpha_1, \beta) \tilde{q}(\alpha_1) \kappa(d\alpha_1)\| & \gtrsim \|\tilde{q}\|_{L_2}^{-5/d} \geq \|q\|_{L_2}^{-5/d} \end{align*} Therefore \begin{align*} |f_2(\mu_\beta^*) - f(\mu_\beta^*)| \gtrsim \frac{\lambda_{1}}{\|h + \|h\|_\infty\|_{L_1}}\|q\|_{L_2}^{-5/d} \end{align*} Finally, note that $\lambda_1 \simeq d^{-1}$, and by the addition formula and the fact $P_k(1) = 1$ for all $k$: \begin{align*} \|h + \|h\|_\infty\|_{L_1} & \leq 2 \|h\|_\infty\\ & = 2 \max_{x \in \mathbb{S}^d} \sum_{j=1}^{N(d,1)} \beta_{1,j} Y_{1,j}(x)\\ & \leq 2 \max_{x \in \mathbb{S}^d} \|\beta\|_2 \sqrt{\sum_{j=1}^{N(d,1)} Y_{1,j}(x)^2}\\ & \leq 2 N(d,1)\\ & \lesssim d \end{align*} So we arrive at the desired bound. \end{proof} \section{From Set to Measure Functions}\label{sec:set2measure} \subsection{Neural Functional Spaces for Learning over Measures}\label{sec:neural_functional_spaces} Equipped with the perspective of (\ref{eq:oursets}) acting on an empirical measure, we consider shallow neural networks that take probability measures as inputs, with test functions as weights. We discuss in Section \ref{sec:settomeasuresub} which functions defined over sets admit an extension to functions over measures. Let $\mathcal{A}$ be a subset of $C_0(\mathbb{I})$, equipped with its Borel sigma algebra. For $\mu \in \mathcal{P}(\I)$, and a signed Radon measure $\chi \in \mathcal{M}(\mathcal{A})$, define ${f}: \mathcal{P}(\I) \rightarrow \mathbb{R}$ as \begin{equation} {f}(\mu; \chi) = \int_{\mathcal{A}} \widetilde{\sigma}(\langle \phi, \mu \rangle) \chi(d\phi)~. \end{equation} where $\widetilde{\sigma}$ is again a scalar activation function, such as the ReLU, and $\langle \phi, \mu \rangle := \int_\mathbb{I} \phi(x) \mu(dx)$. Crucially, the space of functions given by ${f}(\cdot; \chi)$ were proven to be dense in the space of real-valued continuous (in the weak topology) functions on $\mathcal{P}(\I)$ in~\textcite{pevny2019approximation,de2019stochastic}, and so this network exhibits universality. Keeping in mind the functional norms defined on test functions in Section~\ref{sec:convex_shallow}, we can introduce analogous norms for neural networks on measures. For a fixed probability measure $\tau \in \mathcal{P}(\mathcal{A})$, define \begin{equation} \label{eq:f11} \| f\|_{1, \mathcal{A}} = \inf \left\{ \| \chi \|_{\mathrm{TV}}; \,f(\mu) = \!\int_{\mathcal{A}} \widetilde{\sigma}( \langle \phi, \mu \rangle) \chi(d\phi) \right\}~, \end{equation} \begin{equation} \label{eq:f22} \| f\|_{2, \mathcal{A}} = \inf \left\{ \| q \|_{L_2}; \, f(\mu) = \!\int_{\mathcal{A}} \widetilde{\sigma}( \langle \phi, \mu \rangle) q(\phi) \tau(d\phi) \right\}~, \end{equation} where we take the infima over Radon measures $\chi \in \mathcal{M}(\mathcal{A})$ and densities $q \in L_2(d\tau)$. Analogously these norms also induce the respective function classes $\mathcal{G}_1(\mathcal{A}) = \{f: \|f\|_{1,\mathcal{A}} < \infty\}$, $\mathcal{G}_2(\mathcal{A}) = \{f: \|f\|_{2,\mathcal{A}} < \infty\}$. The argument in Appendix A of~\textcite{bach2017breaking} implies $\mathcal{G}_2(\mathcal{A})$ is an RKHS, with associated kernel $k_\mathcal{G}(\mu, \mu') = \int_\mathcal{A} \widetilde{\sigma}( \langle \phi, \mu \rangle) \widetilde{\sigma}( \langle \phi, \mu' \rangle) \tau(d \phi)$. Moving from vector-valued weights to function-valued weights presents an immediate issue. The space $C_0(\mathbb{I})$ is infinite-dimensional, and it is not obvious how to learn a measure $\chi$ over this entire space. Moreover, our ultimate goal is to understand finite-width symmetric networks, so we would prefer the function-valued weights be efficiently calculable rather than pathological. To that end, we choose the set of test functions $\mathcal{A}$ to be representable as regular neural networks. Explicitly, using the function norms of Section~\ref{sec:convex_shallow}, we define \begin{eqnarray*} \label{eq:bobo} \mathcal{A}_{1,m} &:=& \left\{\phi; ~ \phi(x) = \sum_{j=1}^m \alpha_j \sigma(\langle w_j, \tilde{x} \rangle)~,\,\|w_j\|_2\leq 1, \| \alpha \|_1 \leq 1\right\} \nonumber, \\ \mathcal{A}_{2,m} &:=& \left\{\phi \in \mathcal{F}_{2,m}:\, \gamma_{2,m}(\phi) \leq 1 \right\}~. \end{eqnarray*} $\A_{1,m}$ thus contains functions in the unit ball of $\FF_1$ that can be expressed with $m$ neurons, and $\A_{2,m}$ contains functions in the (random) RKHS $\FF_{2,m}$ obtained by sampling $m$ neurons from $\kappa$. By definition $\A_{2,m} \subset \A_{1,m}$ for all $m$. Representational power grows with $m$, and observe that the approximation rate in the unit ball of $\FF_1$ or $\FF_2$ is in $m^{-1/2}$, obtained for instance with Monte-Carlo estimators \parencite{bach2017breaking,ma2019barron}. Hence we can also consider the setting where $m = \infty$, with the notation $\mathcal{A}_{\{i,\infty\}} = \{\phi \in \FF_{i} : \gamma_{i}(\phi) \leq 1\}$. Note also that there is no loss of generality in choosing the radius to be $1$, as by homogeneity of $\sigma$ any $\phi$ with $\gamma_i(\phi) < \infty$ can be scaled into its respective norm ball. We now examine the combinations of $\mathcal{G}_i$ with $\mathcal{A}_i$: \begin{itemize} \item $\mathcal{S}_{1,m} := \mathcal{G}_1(\mathcal{A}_{1,m})$; the measure $\chi$ is supported on test functions in $\mathcal{A}_{1,m}$. \item $\mathcal{S}_{2,m} := \mathcal{G}_1(\mathcal{A}_{2,m})$; $\chi$ is supported on test functions in $\mathcal{A}_{2,m}$. \item $\mathcal{S}_{3,m} := \mathcal{G}_2(\mathcal{A}_{2,m})$; $\chi$ has a density with regards to $\tau$, which is supported on $\mathcal{A}_{2,m}$. \item The remaining class $\mathcal{G}_2(\mathcal{A}_{1,m})$ requires defining a probability measure $\tau$ over $\mathcal{A}_{1,m}$ that sufficiently spreads mass outside of any RKHS ball. Due to the difficulty in defining this measure in finite setting, we omit this class. \end{itemize} Note that from Jensen's inequality and the inclusion $\mathcal{A}_{2,m} \subset \mathcal{A}_{1,m}$ for all $m$, we have the inclusions $\mathcal{S}_{3,m} \subset \mathcal{S}_{2,m} \subset \mathcal{S}_{1,m}$. And $\mathcal{S}_{3,m}$ is clearly an RKHS, since it is a particular instantiation of $\mathcal{G}_2(\mathcal{A})$. In the sequel we will drop the subscript $m$ and simply write $\A_i$ and $\mathcal{S}_i$. These functional spaces provide an increasing level of adaptivity: while $\mathcal{S}_2$ is able to adapt by selecting `useful' test functions $\phi$, it is limited to smooth test functions that lie on the RKHS, whereas $\mathcal{S}_1$ is able to also adapt to more irregular test functions that themselves depend on low-dimensional structures from the input domain. We let $\|f\|_{\mathcal{S}_i}$ denote the associated norm, i.e. $\|f\|_{\mathcal{S}_1} := \|f\|_{1, \mathcal{A}_{1}}$. \paragraph{Finite-Width Implementation:} For any $m$, these classes admit a particularly simple interpretation when implemented in practice. On the one hand, the spaces of test functions are implemented as a single hidden-layer neural network of width $m$. On the other hand, the integral representations in (\ref{eq:f11}) and (\ref{eq:f22}) are instantiated by a finite-sum using ${m'}$ neurons, leading to the finite analogues of our function classes given in Table~\ref{tab:freeze}. Specifically, \begin{align*} f(\mu) = \frac{1}{m'}\! \sum_{j'=1}^{m'} b_{j'} \widetilde{\sigma}\! \left(\!\!\frac{1}{m} \sum_{j=1}^m c_{j',j} \int \sigma_\alpha( \langle w_{j',j}, \tilde{x} \rangle) \mu(dx)\!\! \right) \end{align*} One can verify \parencite{neyshabur_norm-based_2015} that the finite-width proxy for the variation norm is given by $$\| f \|_1 = \frac{1}{m'} \! \sum_{j'} |b_{j'}| \| \phi_{j'} \|_1 \leq \frac{1}{m m'} \!\sum_{j',j} |b_{j'}| |c_{j',j}| \| w_{j',j} \|~,$$ which in our case corresponds to the so-called path norm \parencite{neyshabur2014search}. In particular, under the practical assumption that the test functions $\phi_{j'}$ are parameterized by two-layer networks with shared first layer, the weight vectors $w_{j',j}$ only depend on $j$ and this norm may be easily calculated as a matrix product of the network weights. We can control this term by constraining the weights of the first two layers to obey our theoretical assumptions (of bounded weights and test functions in respective RKHS balls), and regularize the final network weights. See Section~\ref{sec:experiments} and the Appendix for practical relaxations of the constraints. \begin{table} \centering \begin{tabular}{p{5pt}c|cccccc} & & First Layer & Second Layer & Third Layer \\ \hline & $\mathcal{S}_1$ & Trained & Trained & Trained & \\ & $\mathcal{S}_2$ & Frozen & Trained & Trained & \\ & $\mathcal{S}_3$ & Frozen & Frozen & Trained \\ \end{tabular} \caption{Training for finite function approximation} \label{tab:freeze} \end{table} \subsection{Continuous Extension} \label{sec:settomeasuresub} In general, the functions we want to represent don't take in measures $\mu \in \mathcal{P}(\I)$ as inputs. In this section, we want to understand when a function $f$ defined on the power set $f : \overline{\mathbb{I}} \to \mathbb{R}$ can be extended to a continuous map $\bar{f} : \mathcal{P}(\I) \to \mathbb{R}$ in the weak topology, in the sense that for all $N \in \mathbb{N}$ and all $(x_1, \dots x_N)\in \mathbb{I}^N$, $\bar{f}\left(\frac{1}{N}\sum_{i=1}^N \delta_{x_i} \right) = f(x_1, \dots, x_N)$. Observe that by construction $\bar{f}$ captures the permutation symmetry of the original $f$. Define the mapping $D: \overline{\mathbb{I}} \rightarrow \mathcal{P}(\mathbb{I})$ by $D(x_1, \dots, x_N) = \frac{1}{N}\sum_{i=1}^N \delta_{x_i}$. Let $\hat{\mathcal{P}}_N(\mathbb{I}) := D(\mathbb{I}^N)$ and $\hat{\mathcal{P}}(\mathbb{I}) = \bigcup_{N=1}^\infty \hat{\mathcal{P}}_N(\mathbb{I})$, so that $\hat{\mathcal{P}}(\mathbb{I})$ is the set of all finite discrete measures. For $\mu \in \hat{\mathcal{P}}(\mathbb{I})$, let $N(\mu)$ be the smallest dimension of a point in $D^{-1}(\mu)$, and let $x$ be this point (which is unique up to permutation). Then define $\hat{f}: \hat{\mathcal{P}}(\mathbb{I}) \rightarrow \mathbb{R}$ such that $\hat{f}(\mu) = f_N(x)$. We also write $W_1(\mu, \mu')$ as the Wasserstein 1-metric under the $\|\cdot\|_2$ norm~\parencite{villani2008optimal}. The following proposition establishes a necessary and sufficient condition for continuous extension of $f$: \begin{proposition}\label{prop:extension} There exists a continuous extension $\bar{f}$ iff $\hat{f}$ is uniformly continuous with regard to the $W_1$ metric on its domain. \end{proposition} This result formalises the intuition that extending a symmetric function from sets to measures requires a minimal amount of regularity \emph{across} sizes. We next show examples of symmetric families that can be extended to $\mathcal{P}(\I)$. \subsection{Examples of Eligible Symmetric Families}\label{sec:examples} \paragraph{Moment-based Functions:} Functions based on finite-range interactions across input elements admit continuous extensions. For example, a function of singleton and pairwise interactions $$f(x) = \rho\left(\frac{1}{N} \sum_{i=1}^N \phi_1(x_i), \frac{1}{N^2}\sum_{i_1,i_2=1}^N \phi_2(x_{i_1}, x_{i_2})\right)$$ is a special case of the continuous measure extension $\bar{f}(\mu) = \rho \left( \langle \phi_1, \mu \rangle, \langle \phi_2, \mu \otimes \mu \rangle \right)$ when $\mu = D(x)$. \paragraph{Ranking:} Suppose that $\mathbb{I} \subseteq \mathbb{R}$. The max function $f_N(x) = \max_{i\leq N} x_i$ cannot be lifted to a function on measures due to discontinuity in the weak topology. Specifically, consider $\mu = \delta_0$ and $\nu_{N} = \frac{N-1}{N} \delta_0 + \frac{1}{N} \delta_1$. Then $\nu_N \rightharpoonup \mu$, but for $\hat{f}$ as in Proposition \ref{prop:extension}, $\hat{f}(\nu_N) = 1 \neq 0 = \hat{f}(\mu)$. Nevertheless, we can define an extension on a smooth approximation via the softmax, namely $g_N^\lambda(x) = \frac{1}{\lambda} \log \frac{1}{N} \sum_{i=1}^N \exp(\lambda x_i)$. This formulation, which is the softmax up to an additive term, can clearly be lifted to a function on measures, with the bound $\|g_N^\lambda - f_N\|_\infty \leq \frac{\log N}{\lambda}$. Although we cannot learn the max family across all $N$, we can approximate arbitrarily well for bounded $N$. \paragraph{Counterexamples:} Define the map $\Delta_k: \mathbb{R}^N \rightarrow \mathbb{R}^{kN}$ such that $\Delta_k(x)$ is a vector of $k$ copies of $x$. Then a necessary condition for the function $\hat{f}$ introduced in Proposition~\ref{prop:extension} to be uniformly continuous is that $f_N(x) = f_{kN}(\Delta_k(x))$ for any $k$. Intuitively, if $f_N$ can distinguish the input set beyond the amount of mass on each point, it cannot be lifted to measures. This fact implies any continuous approximation to the family $f_N(x) = x_{[2]}$, the second largest value of $x$ will incur constant error. \section{Preliminaries}\label{sec:prelim} \subsection{Problem Setup} Let $\mathbb{I} \subseteq \mathbb{R}^d$ be a convex domain, and $N \in \mathbb{N}$. A \emph{symmetric} function $f: \mathbb{I}^{ N} \to \mathbb{R}$ is such that $f(x_1, \dots x_N) = f(x_{\pi(1)},\dots x_{\pi(N)})$ for any $x \in \mathbb{I}^{N}$ and any permutation $\pi \in \mathcal{S}_N$. In this work, we are interested in learning symmetric functions defined independently of $N$. Let $\overline{\mathbb{I}}= \bigcup_{N=1}^\infty \mathbb{I}^N$, then $f: \overline{\mathbb{I}} \to \mathbb{R}$ is symmetric if $f$ restricted to $\mathbb{I}^{ N}$ is symmetric for each $N \in \mathbb{N}$. Let $\mathcal{F}_{\mathrm{sym}}$ denote the space of symmetric functions defined on $\overline{\mathbb{I}}$. This setting is motivated by applications in statistical mechanics and particle physics, where $N$ is a sampling parameter. We focus on the realizable regression setting, where we observe a dataset $\{(\boldsymbol{x}_i, f^*(\boldsymbol{x}_i)) \in \overline{\mathbb{I}} \times \mathbb{R} \}_{i=1,\dots n}$ of $n$ samples from an unknown symmetric function $f^*$, and $\boldsymbol{x}_i$ are drawn iid from a distribution $\mathcal{D}$ on $\overline{\mathbb{I}}$. The goal is to find a proper estimator $\hat{f} \in \mathcal{F}_{\mathrm{sym}}$ such that the population error $\mathbb{E}_{\boldsymbol{x} \sim \mathcal{D}} \ell(f^*(\boldsymbol{x}), \hat{f}(\boldsymbol{x}))$ is low, where $\ell$ is a convex loss. Following a standard Empirical Risk Minimisation setup \parencite{shalev2014understanding,bach2017breaking}, we will construct hypothesis classes $\mathcal{F} \subset \mathcal{F}_{\mathrm{sym}}$ endowed with a metric $\| f\|_\mathcal{F}$, and consider \begin{equation} \label{eq:erm} \hat{f} \in \argmin_{f \in \mathcal{F}; \| f\|_{\mathcal{F}} \leq \delta} \frac{1}{n}\sum_{i=1}^n \ell( f^*(\boldsymbol{x}_i), f(\boldsymbol{x}_i) )~, \end{equation} where $\delta$ is a regularization parameter that is optimised using e.g. cross-validation. We focus on the approximation and statistical aspects of this estimator for different choices of $\mathcal{F}$; solving the optimization problem (\ref{eq:erm}) is not the focus of the present work and will be briefly discussed in Section \ref{sec:conclusion}. \subsection{Symmetric Polynomials} \label{sec:symmpoly} A simplest way to approximate symmetric functions is with symmetric polynomials. Combining Weierstrass approximation theory with a symmetrization argument, it can be seen that assuming $d = 1$, any symmetric continuous function $f: \mathbb{I}^N \rightarrow \mathbb{R}$ can be uniformly approximated by symmetric polynomials (see~\textcite{yarotsky2018universal} for a proof). There are several canonical bases over the ring of symmetric polynomials, but we will consider the one given by the power sum polynomials, given by $p_k(x) = \sum_{i=1}^N x_i^k$, with $x \in \mathbb{I}^N$. \begin{theorem}[(2.12) in~\textcite{macdonald1998symmetric}] For any symmetric polynomial $f$ on $N$ inputs, there exists a polynomial $q$ such that $f(x) = q(p_1(x), \dots, p_N(x))$. \end{theorem} If $q$ is linear, this theorem suggests a simple predictor for symmetric functions across varying $N$. If $x \in \mathbb{I}^M$, we can consider $x \mapsto \sum_{i=1}^N c_i \left(\frac{1}{M} p_i(x)\right) = \sum_{i=1}^N c_i \mathbb{E}_{y\sim\mu}(y^i)$ where $\mu = \frac{1}{M} \sum_{j=1}^M \delta_{x_j}$. The truncated moments of the empirical distribution given by $x$ act as linear features, which yield an estimator over any input size $M$. We will consider a generalization of this decomposition, by moving beyond the polynomial kernel to a general RKHS (see Section~\ref{sec:neural_functional_spaces}). \subsection{Convex Shallow Neural Networks}\label{sec:convex_shallow} By considering the limit of infinitely many neurons \textcite{bengio2006convex,rosset2007}, \textcite{bach2017breaking} introduces two norms on shallow neural representation of functions $\phi$ defined over $\mathbb{R}^d$. For a constant $R \in \mathbb{R}$, a fixed probability measure $\kappa \in \mathcal{P}(\mathbb{S}^{d})$ with full support, a signed Radon measure $\nu \in \mathcal{M}(\mathbb{S}^{d})$, a density $p \in L_2(d \kappa)$, and the notation that $\tilde{x} = [x, R]^T$, define: \begin{align} \gamma_1(\phi) = \inf \left\{ \| \nu \|_{\mathrm{TV}}; \, \phi(x) = \int_{\mathbb{S}^{d}} \sigma( \langle w, \tilde{x} \rangle) \nu(dw) \right\}~, \text{ and } \\ \gamma_2(\phi) = \inf \left\{ \| p \|_{L_2(d \kappa)}; \, \phi(x) = \int_{\mathbb{S}^{d}} \sigma( \langle w, \tilde{x} \rangle) p(w) \kappa(dw) \right\}~, \end{align} where $\| \nu \|_{\mathrm{TV}}:= \sup_{|g|\leq 1} \int g d\nu$ is the \emph{Total Variation} of $\nu$ and $\sigma_\alpha(t) = \max(0, t)^\alpha$ is the ReLU activation raised to the positive integer power $\alpha$. These norms measure the minimal representation of $\phi$, using either a Radon measure $\nu$ over neuron weights, or a density $p$ over the fixed probability measure $\kappa$. The norms induce function classes: \begin{equation} \mathcal{F}_1 = \{\phi \in C_0(\mathbb{I}): \gamma_1(\phi) < \infty\} ~,\text{ and}~ \mathcal{F}_2 = \{\phi \in C_0(\mathbb{I}): \gamma_2(\phi) < \infty\}~. \end{equation} We also assume that the input domain $\mathbb{I}$ is bounded with $\sup_{x\in\mathbb{I}} \|x\|_2 \leq R$. These two functional spaces are fundamental for the theoretical study of shallow neural networks and capture two distinct regimes of overparametrisation: whereas the so-called \emph{lazy} or kernel regime corresponds to learning in the space $\mathcal{F}_2$ \parencite{chizat2018note,jacot2018neural}, which is in fact an RKHS with kernel given by $k(x,y)= \mathbb{E}_{w \sim \kappa} \left[\sigma_\alpha( \langle w, \tilde{x} \rangle) \sigma_\alpha( \langle w, \tilde{y} \rangle)\right]$ \parencite{bach2017breaking} \footnote{Or a modified NTK kernel that also includes gradients with respect to first-layer weights \parencite{jacot2018neural} }, the mean-field regime captures learning in $\mathcal{F}_1$, which satisfies $\mathcal{F}_2 \subset \mathcal{F}_1$ from Jensen's inequality, and can efficiently approximate functions with hidden low-dimensional structure, as opposed to $\mathcal{F}_2$ \parencite{bach2017breaking}. Finally, one can leverage the fact that the kernel above is an expectation over features to define a finite-dimensional random feature kernel $k_m(x,y) = \frac{1}{m} \sum_{j=1}^m \sigma_\alpha( \langle w_j, \tilde{x} \rangle) \sigma_\alpha( \langle w_j, \tilde{y} \rangle)$ with $w_j \stackrel{i.i.d.}{\sim} \kappa$, which defines a (random) RKHS $\mathcal{F}_{2,m}$ converging to $\mathcal{F}_2$ as $m$ increases \parencite{bach2017equivalence, rahimi2008random}. The empirical norm $\gamma_{2,m}$ can be defined similarly to $\gamma_2$, where the density $p$ is replaced by coefficients over the sampled basis functions $\sigma_\alpha(\langle w_j, \cdot \rangle)$. \subsection{Symmetric Neural Networks} \label{sec:symmNN} A universal approximator for symmetric functions was proposed by ~\textcite{zaheer2017deep}, which proved that for any fixed $N$ and $f_N \in \mathcal{F}_{\mathrm{sym}}^N$ there must exist $\Phi: \mathbb{I} \rightarrow \mathbb{R}^L$ and $\rho: \mathbb{R}^L \rightarrow \mathbb{R}$ such that \begin{equation}\label{eq:oursets} f_N(x) = \rho \left(\frac{1}{N} \sum_{n=1}^N \Phi(x_n) \right)~. \end{equation} However, universality is only proven for fixed $N$. Given a symmetric function $f \in \mathcal{F}_{\mathrm{sym}}$ we might hope to learn $\rho$ and $\Phi$ such that this equation holds for all $N$. Note that the fraction $\frac{1}{N}$ is not present in their formulation, but is necessary for generalization across $N$ to be feasible (as otherwise the effective domain of $\rho$ could grow arbitrarily large as $N \rightarrow \infty$). Treating the input to $\rho$ as an average motivates moving from sets to measures as inputs, as proposed in \textcite{pevny2019approximation, de2019stochastic}. Given $x \in \mathbb{I}^N$, let $\mu^{(N)} = \frac{1}{N} \sum_{i=1}^N \delta_{x_i}$ denote the empirical measure in the space $\mathcal{P}(\mathbb{I})$ of probability measures over $\mathbb{I}$. Then (\ref{eq:oursets}) can be written as $f_N(x) = \rho\left( \int_{\mathbb{I}} \Phi(u) \mu^{(N)}(du) \right)~.$
{'timestamp': '2021-07-05T02:04:48', 'yymm': '2008', 'arxiv_id': '2008.06952', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06952'}
arxiv
\section{INTRODUCTION} \IEEEPARstart{T}{he} manipulation of deformable objects is currently an open (and hot) research problem in robotics \cite{Book:Cherubini2020} that has attracted many researchers due to its great applicability in many areas, e.g. manipulating fabrics \cite{cusumano2011bringing}, shaping of food materials \cite{tokumoto2002deformation}, assembling soft components \cite{Journals:Li2018}, manipulating cables \cite{wakamatsu2006knotting}, interacting with tissues \cite{tiffany2020_ijmr}, etc. Note that physical interactions between a robot and a deformable object will inevitably alter the object's shape. The feedback control of these additional object degrees-of-freedom (DOF) is referred to in the literature as shape servoing \cite{Journals:Sanchez2018}, a frontier problem that presents three main challenges: (i) The efficient feedback characterization of the object's shape (which has infinite number of DOF to be controlled by a robot with limited manipulation directions); (ii) The computation of a motion-deformation model for control (which depends on the---typically unknown---mechanical properties of the object); (iii) The online adjustment of the robot's motion during the soft object manipulation task (note that these objects might be delicate and easy to damage). For shape servoing tasks, an excellent feature extraction algorithm can describe the soft object to the greatest extent with the least number of feature coordinates. The most widely used image features are feature points, centroid points, distance/angle/curvature features, and other artificially marked points \cite{navarro2014visual}. However, as the above are local features, and hard to describe the overall geometric information of soft objects. Thus, the development of global features present an advantage in this problem. In \cite{1321161}, image moments were used to characterize the object's contour, but its real-time performance was limited due to a large amount of calculations. In \cite{Hu20193}, Principal Component Analysis was used to project raw Fast Point Feature Histograms into a new space with higher variance and a lower dimension. A catenary-based feature descriptor was developed for tethered wheeled robots and underwater vehicles in \cite{laranjeira2017catenary, laranjeira2020catenary}; However, this approach is only applicable to very specific shapes, hence, cannot be used for complex contours. Recently, a method based on Fourier coefficients was developed in \cite{navarro2017fourier,Proceedings:Zhu2018}; This approach can effectively compute a low-dimension feature vector to represent the shape of complex objects. B$\acute{\text{e}}$zier curves and Non-Uniform Rational Basis Splines (NURBS) are an interesting option to describe complex contours, however, they have not been thoroughly exploited in the literature to establish an explicit shape servo-loop. Other types of shape feature representations rely on machine learning, e.g. Nair combined learning and visual feedback to manipulate ropes in \cite{Nair2017Combining}. Although learning-based approaches have good adaptability, they require large and ``rich enough'' data sets to generalize to diffvnerent situations (which is difficult to guarantee in many applications). Designing a computationally efficient feature extraction algorithm that provides a reliable representation for controller design is an important problem in soft object manipulation. To execute shape servoing tasks, a controller requires a model (e.g. a Jacobian matrix) that describes the relationship between robot motions and feedback deformations. In \cite{navarro2013model}, the authors used parameter linearization and least-squares methods to compute the deformation Jacobian matrix. Then, to improve real-time performance, an online estimation technique and its convergence proof were developed in \cite{navarro2014dynamic}. However, both methods depend on the selection of the regression matrix and need a prior-known structure. The Broyden method was used to online estimate the Jacobian matrix in \cite{hosoda1994versatile} without a known structure. In \cite{piepmeier2004uncalibrated}, the authors combined dynamic recursive least square with online estimation; Although these methods have a small amount of calculation and are easy to implement, they are prone to enter local minima. Kalman Filter (KF) has an excellent performance in estimating unknown variables using a series of measurements observed over time in the presence of noise and uncertainty. Thus, KF is a good option for online estimating the sensorimotor relations in our soft object manipulation problem. For example, in \cite{Qian2002Online} a state-space model was established using the Jacobian matrix elements as the system state and used KF to observe its unknown values. With standard Kalman filters, the noise covariance matrix is often a constant matrix, for solving this limitation, the authors in \cite{lv2006fuzzy} proposed a fuzzy adaptive KF to deal with a time-varying covariance matrix. In our soft object manipulation problem, a good Jacobian matrix estimation algorithm is necessary to properly ``steer'' the object towards a desired target shape. Although model-free shape control (as formulated in \cite{navarro2013model}) is known for its simple structure and robustness to uncertainties, these controllers generally use a constant feedback gain (which limits the types of dynamic responses they can achieve). When the performance requirements change (e.g. deforming materials with different stiffness), a fixed gain may produce oscillations, cause the system to lose stability or even damage the manipulated object. Therefore, it is important to design a dynamic parameter tuning algorithm for shape servoing tasks, such that it can adapt to various performance requirements. Based on the limitations of the above mentioned works, in this paper, we propose a new solution with the following original contributions: \begin{enumerate} \item We present new feedback feature vectors (constructed with the coefficients of B$\acute{\text{e}}$zier and NURBS) to efficiently represent elastic rods. \item We propose a new adaptive deformation controller with KF-based estimators and online parameter optimization. \item We report detailed simulations and experimental results to validate the proposed method. \end{enumerate} To the best of authors’ knowledge, this is the first time that a shape servo-controller uses B$\acute{\text{e}}$zier/NURBS to establish an explicit shape servo-loop. These features were used in \cite{Journals:Wang2018} but only to project the object's contour into the image plane, which largely differs from our feedback representation approach. The rest of this paper is organized as follows: Section \ref{sect2} presents the preliminaries; Section \ref{sect3} describes the methods; Section \ref{sect4} and Section \ref{sect5} presents the results; Section \ref{sect6} gives final conclusions. \begin{figure}[t] \centering \includegraphics[scale=0.55]{fig22.pdf} \caption{Representation of the cable manipulation case of study, where a vision sensor continuously measures the feature vector $\mathbf{s}$ of the cable, which should be accurately deformed into target feature $\mathbf{s}^*$ within the controller.} \label{fig24} \end{figure} \section{PRELIMINARIES}\label{sect2} \emph{Notation.} Throughout this paper we use very standard notation. Column vectors are denoted with bold small letters $\mathbf v$ and matrices with bold capital letters $\mathbf M$. Time evolving variables are represented as $\mathbf m_k$, where the subscript $\ast_k$ denotes the discrete time instant. $\mathbf{E}_n$ is an $n \times n$ identity matrix. Our aim in this work is to solve the automatic shape control of elastic rods with visual servoing. We denote the vector of robot motion by $\mathbf{r}_k \in \mathbb R^q$. To derive our new method, let us first consider the following conditions: \begin{itemize} \item The shape of the rod is measured with a fixed camera in an eye-to-hand configuration (depicted in Fig. \ref{fig24}). We denote the 2D image contour as: \begin{equation} \label{eq-1} \begin{array}{*{20}{c}} {\bar{\mathbf{c}} = {{\left[ {\mathbf{c}_1^\T, \dots ,\mathbf{c}_N^\T} \right]}^\T} \in {\mathbb R^{2N}}}&{{\mathbf{c}_i} = {{\left[ {{u_i},{v_i}} \right]}^\T} \in {\mathbb R^2}} \end{array} \end{equation} where, $N$ is the number of the contour points, $\mathbf{c}_i$ denotes the $i$th $(i = 1,\cdots,N)$ point of the contour in the image, $u_i$ and $v_i$ are the coordinates under the image frame. \item During the manipulation task, the rod is rigidly grasped by the robot and remains all the time within the observable range of the camera, and no occlusion occurs. \item The robot's motion is commanded with classical kinematic controls $\Delta \mathbf{r}_k$ \cite{Journals:Siciliano1990} that render stiff behaviours and satisfy the incremental position motions $\mathbf{r}_{k} = \mathbf{r}_{k-1} + \Delta \mathbf{r}_k$. \item The rod is manipulated at low speed such that its shape is determined by the equilibrium of its potential/elastic energy terms only. \end{itemize} \textbf{Problem Statement}. Design a vision-based adaptive control scheme to automatically deform an elastic rod into a desired 2D image shape, without requiring any knowledge of the object's mechanical model. \section{METHODS}\label{sect3} Fig. \ref{fig23} shows the block diagram of the overall manipulation task. The centerline data extraction represents the image processing pipeline, which will be given in Section \ref{5a}. \begin{figure}[t] \centering \includegraphics[scale=1]{fig1.pdf} \caption{The block diagram showing the overall workflow of the system.} \label{fig23} \end{figure} \subsection{Feedback Shape Parameters} The \emph{na\"ive approach} to shape servoing is to synthesise a regulator that attempts to drive the full coordinates of $\bar{\mathbf c}$ into a desired 2D contour. The main problem with this approach is that the raw vector $\bar{\mathbf c}$ is not an efficient signal for real-time control as its dimension very large. Therefore, it is necessary to design an algorithm that computes a reduced dimension feature vector, which can be used for feedback control. In this paper, we fit the feedback signal to a continuous curve $\boldsymbol{f}(\rho)$ that describes the 2D contour, where $\rho$ is a variable constructed with sensor data which represents the normalized arc-length $\left( {0} \le {\rho} \le {1} \right)$. Then, $\mathbf{c}_i=\boldsymbol{f}(\rho_i)$, where ${\rho}_i$ is the arc-length between the start point $\mathbf{c}_1$ and the point $\mathbf{c}_i$ (see Fig. \ref{fig24}), and $\rho_1=0, \rho_N=1$. The idea behind the proposed method proposed is to compute the coefficients of a linearly parametrized regression model of the 2D contour, and use it as a quasi-measurement of the object's shape. Such model has the general form: \begin{equation} \label{eq-2} \bar{\mathbf c} = \bar{\mathbf{G}}(\rho) \cdot \mathbf{s} \end{equation} where $\bar{\mathbf{G}}$ is a regression-like matrix with a known structure, and $\mathbf{s}$ is a vector of \emph{unknown} parameters (which in our formulation represents the shape feature vector). We illustrate this principle with four representative examples: polynomial, B$\acute{\text{e}}$zier, NURBS, and Fourier. The schematic diagrams of the B$\acute{\text{e}}$zier and NURBS curves are shown in Fig. \ref{fig25}. \begin{figure}[t] \centering \includegraphics[scale=0.5]{fig24.pdf} \caption{The schematic diagrams of the B$\acute{\text{e}}$zier and NURBS curve.} \label{fig25} \end{figure} \begin{itemize} \item \emph{Polynomial Parameterization.} Given a variable parameter $\rho$, the general formula is to approximate a curve is: \begin{equation} \label{eq-3} \boldsymbol{f}\left( {\rho}\right) = \sum_{j=0}^n \rho^j \mathbf{p}_j \end{equation} where the positive number $n\in\mathbb N$ is the order of the polynomial, and $\mathbf{p}_j=\left[a_j, b_j \right]^\T$ are the shape parameters of the 2D contour. Polynomial regression can easily represent smooth regular shapes, however, if the order $n$ is selected too large, it may produce overfitting of the curve. \item \emph{B$\acute{\text{e}}$zier Parameterization.} As shown in Fig.\ref{fig25}, B$\acute{\text{e}}$zier curve approximates the curve with a polynomial expression using control points. $n+1$ control points can determine a $n$-degree B$\acute{\text{e}}$zier curve which is described as follows: \begin{align} \label{eq-4} \boldsymbol{f}\left( \rho \right) &= \sum_{j = 0}^n B_{j,n}\left( \rho \right) \mathbf{p}_j,\notag \\ B_{j,n}\left( \rho \right) &= \frac{n!}{j!\left( n - j \right)!} \left(1 - \rho \right)^{n - j}\rho ^j, \end{align} where $\mathbf{p}_j=\left[a_j, b_j \right]^\T$ are control points as well as the shape parameters of the 2D contour. B$\acute{\text{e}}$zier curve has a first-order derivability. It guarantees that the fitting will advance smoothly with the control points without fluctuations, thus, it can represent complex shapes. Yet, note that when many control points are used, it will increase the degree of B$\acute{\text{e}}$zier curve and the computational burden. \item \emph{NURBS Parameterization.} It has local shape description properties, thus, the number of control points is independent from the degree of curves. This model can describe complex curves more accurately and efficiently than polynomial and B$\acute{\text{e}}$zier. The definition of a $m$th-degree NURBS curve \cite{piegl2012nurbs} is: \begin{equation} \label{eq-5} \boldsymbol{f}\left( \rho \right) = \frac{\sum_{j=0}^n N_{j,m} \left( \rho \right) \omega_j \mathbf{p}_j }{\sum_{j=0}^n N_{j,m}\left( \rho \right) \omega_j} \end{equation} where $n$ is the approximation degree of the NURBS, $\mathbf{p}_j=\left[a_j, b_j \right]^\T $ are control points, ${\omega_j}$ are the weights, $N_{j,m}$ are $m$-degree B-spline basis functions. We set \begin{equation} \label{eq-6} R_{j,m}\left( \rho \right) = \frac{N_{j,m} \left( \rho \right) \omega_j}{\sum_{l=0}^n N_{l,m}\left( \rho \right) \omega_l} \end{equation} to rewrite Eq. (\ref{eq-5}) in the form \begin{equation} \label{eq-7} \boldsymbol{f}\left( \rho \right) = \sum_{j=0}^n R_{j,m}\left( \rho \right)\mathbf{p}_j \end{equation} Along this work, we set $m=n$ such that the NURBS reduces to a rational B$\acute{\text{e}}$zier curve and $N_{j,m}(\rho)$ reduces to $B_{j,m}(\rho)$ in (\ref{eq-4}). \item \emph{Fourier Parametrization} Besides the above three cases, Fourier series (as presented in \cite{navarro2017fourier}) are also a type of regression equation. A Fourier curve of degree $n$ is described as follows: \begin{equation} \label{eq-8} \boldsymbol{f}\left( \rho \right) = \left[ \begin{array}{c} a_0\\ c_0 \end{array} \right] + \sum_{j=1}^n \left[ \begin{array}{cc} a_j & b_j\\ c_j & d_j \end{array} \right] \left[ \begin{array}{c} \cos \left( {j\rho } \right) \\ \sin \left( {j\rho } \right) \end{array} \right] \end{equation} where $\left[a_0,c_0\right]^\T$ and $\mathbf{p}_j=[a_j, b_j, c_j, d_j]^\T$ are components of frequencies as well as the shape parameters of the 2D contour. \end{itemize} \emph{Parameterized Regression.} We can rewrite (\ref{eq-3}), (\ref{eq-4}), (\ref{eq-7}) and \eqref{eq-8} into the linear parameterization form $\boldsymbol{f} = \mathbf{G}(\rho)\mathbf{s}$, with the regression matrix $\mathbf{G}$ and feature vector $\mathbf{s}$ defined by: \begin{itemize} \item For polynomial: \begin{align} \label{eq-9} \mathbf{F}_j &= \diag (\rho^j,\rho^j) \in \mathbb R^{2 \times 2} \notag \\ \mathbf{G} &= \left[ \mathbf{F}_0, \cdots, \mathbf{F}_n \right] \in {\mathbb R^{2 \times 2\left( {n + 1} \right)}} \notag \\ \mathbf{s} &= {\left[ \mathbf{p}_0^\T, \cdots, \mathbf{p}_n^\T \right]^\T} \in {\mathbb R^{2\left( {n + 1} \right)}} \end{align} \item For B$\acute{\text{e}}$zier curve: \begin{align} \label{eq-10} \mathbf{F}_j &= \diag (B_{j,n}\left( \rho \right),B_{j,n}\left( \rho \right)) \in \mathbb R^{2 \times 2} \notag \\ \mathbf{G} &= \left[ \mathbf{F}_0, \cdots, \mathbf{F}_n \right] \in {\mathbb R^{2 \times 2\left( {n + 1} \right)}} \notag \\ \mathbf{s} &= {\left[ \mathbf{p}_0^\T, \cdots, \mathbf{p}_n^\T \right]^\T} \in {\mathbb R^{2\left( {n + 1} \right)}} \end{align} \item For NURBS: \begin{align} \label{eq-11} \mathbf{F}_j &= \diag (R_{j,n}\left( \rho \right),R_{j,n}\left( \rho \right)) \in \mathbb R^{2 \times 2} \notag \\ \mathbf{G} &= \left[ \mathbf{F}_0, \cdots, \mathbf{F}_n \right] \in {\mathbb R^{2 \times 2\left( {n + 1} \right)}} \notag \\ \mathbf{s} &= {\left[ \mathbf{p}_0^\T, \cdots, \mathbf{p}_n^\T \right]^\T} \in {\mathbb R^{2\left( {n + 1} \right)}} \end{align} \item For Fourier: \begin{align} \label{eq-12} \mathbf{F}_j &= \left[ \begin{array}{cccc} \cos \left( {j\rho } \right) & \sin \left( {j\rho } \right) & 0 & 0 \\ 0 & 0 & \cos \left( {j\rho } \right) & \sin \left( {j\rho } \right) \end{array} \right] \in {\mathbb R^{2 \times 4}} \notag \\ \mathbf{G} &= \left[ \mathbf{E}_2, \mathbf{F}_1, \cdots, \mathbf{F}_n \right] \in {\mathbb R^{2 \times \left( {4n + 2} \right)}} \notag \\ \mathbf{s} &= {\left[ a_0, c_0, \mathbf{p}_1^\T, \cdots, \mathbf{p}_n^\T \right]^\T} \in {\mathbb R^{\left( {4n + 2} \right)}} \end{align} \end{itemize} By using $N$ sample points combined with the different regression equations (\ref{eq-9}), (\ref{eq-10}), (\ref{eq-11}), and (\ref{eq-12}), we can get the same long structures presented in \eqref{eq-2}: \begin{align*} \bar{\mathbf{c}} &= {\left[ {\mathbf{c}{{\left( {{{\rho} _1}} \right)}^\T}, \cdots ,\mathbf{c}{{\left( {{{\rho} _N}} \right)}^\T}} \right]^\T} \\ \bar{\mathbf{G}} &= {\left[ {\mathbf{G}{{\left( {{{\rho} _1}} \right)}^\T}, \ldots ,\mathbf{G}{{\left( {{{\rho} _N}} \right)}^\T}} \right]^\T} \end{align*} Thus, the feature vector $\mathbf{s}$ is computed from sensor feedback at every iteration as: \begin{equation} \label{eq-13} \mathbf{s} = \boldsymbol {\mathcal G} \cdot \bar{\mathbf{c}}\qquad \text{for}\quad \boldsymbol{\mathcal G} = {{\left( {{{\bar{\mathbf{G}}}^\T}\bar{\mathbf{G}}} \right)}^{ - 1}}{{\bar{\mathbf{G}}}^\T} \end{equation} To invert ${\bar{\mathbf{G}}^\T}{\bar{\mathbf{G}}}$, a sufficient number $N$ of data points must be used such that $2N > 2(n+1)$ (or $2N > 4(n+2)$ for the Fourier case). \begin{remark} Although this paper only gives four forms of curve parametrization, there are many other geometric expressions (e.g. B-spline and rational approximation) that can be linearly parameterized as \eqref{eq-2}. \end{remark} \subsection{Approximation of the Local Deformation Model} Since we consider regular (i.e. mechanically well-behaved) elastic objects, it is reasonable to assume that small robot motions $\Delta \mathbf{r}_k = \mathbf{r}_k - \mathbf{r}_{k-1} \in {\mathbb R^q}$ will produce small changes $\Delta\bar{\mathbf c}$ in the observed 2D contour. We locally model this situation (around the current operating point) with the following expression: \begin{equation} \Delta\bar{\mathbf c}_k = \mathbf D_k \cdot \Delta\mathbf r_k \label{eq-14} \end{equation} where we introduce the matrix $\mathbf D_k$ to model the local deformation properties of the elastic object undergoing quasi-static manipulation by the robot. By combining \eqref{eq-14} with \eqref{eq-13} we obtain the motion model: \begin{equation} \label{eq-15} \begin{array}{*{20}{c}} \Delta{\mathbf s}_k = \boldsymbol {\mathcal G}\mathbf D_k \cdot \Delta\mathbf r_k = \mathbf J_k \cdot \Delta\mathbf r_k \end{array} \end{equation} where $\Delta \mathbf{s}_k = \mathbf{s}_k - \mathbf{s}_{k-1} \in {\mathbb R^p}$ denotes the features' changes, and the matrix $\mathbf J_k = \boldsymbol {\mathcal G}\mathbf D_k \in \mathbb R^{p \times q}$ represents a Jacobian-like matrix that transforms robot motions into shape changes, and which cannot be analytically computed as the deformation properties of the object are \emph{unknown}. Instead of identifying the full mechanical model, in this paper we design an algorithm that computes local approximations of $\mathbf J_k$ in real-time. For estimating the Jacobian-like matrix, we use two KFs, LKF and UKF, which excellent real-time performance and are robust to external disturbances \cite{Charles2009Kalman}. Throughout this note, we assume that $\mathbf J_k$ is full column rank during the manipulation task (a condition that is easy to satisfy in practice as the dimension of $\mathbf s$ is much larger than $\mathbf r$). Consider the discrete form of \eqref{eq-15} \begin{equation} \label{eq-16} \mathbf{s}_k = \mathbf{s}_{k-1} + \mathbf{J}_k \cdot \Delta \mathbf{r}_k \end{equation} with state $\mathbf{x}_k = {\left[ {\partial {s_1}/\partial \mathbf{r}, \ldots ,\partial {s_p}/\partial \mathbf{r}} \right]^\T} \in {\mathbb R^{pq}}$, and ${{\partial {s_i}} \mathord{\left/ {\vphantom {{\partial {s_i}} {\partial \mathbf{r}}}} \right. \kern-\nulldelimiterspace} {\partial \mathbf{r}}} = \left[ {{{\partial {s_i}} \mathord{\left/ {\vphantom {{\partial {s_i}} {\partial {r_1}, \ldots ,{{\partial {s_i}} \mathord{\left/ {\vphantom {{\partial {s_i}} {\partial {r_q}}}} \right. \kern-\nulldelimiterspace} {\partial {r_q}}}}}} \right. \kern-\nulldelimiterspace} {\partial {r_1}, \ldots ,{{\partial {s_i}} \mathord{\left/ {\vphantom {{\partial {s_i}} {\partial {r_q}}}} \right. \kern-\nulldelimiterspace} {\partial {r_q}}}}}} \right] \in {\mathbb R^{1 \times q}}$ is the $i$th row of the Jacobian $\mathbf{J}_k$, the discrete system \eqref{eq-16} can be transformed into the linear stochastic system with no control input: \begin{align} \label{eq-17} \mathbf{x}_k &= \mathbf{x}_{k-1} + \boldsymbol{\eta}_k \notag \\ \mathbf{y}_k &= \mathbf{M}_k \cdot \mathbf{x}_k + \boldsymbol{\nu}_k \end{align} The system output is defined as $\mathbf{y}_k = \Delta\mathbf{s}_k$, and let the noise sequences be zero-mean Gaussian white noise, namely, process noise $\boldsymbol{\eta}_k \sim N\left( {\mathbf{0},\mathbf{A}_k} \right)$ and measurement noise $\boldsymbol{\nu}_k \sim N\left( {\mathbf{0},\mathbf{B}_k} \right)$, with variances $\mathbf{A}_k$ and $\mathbf{B}_k$ respectively. $\mathbf{M}_k$ is the measurement matrix defined by: \begin{equation} \label{eq-18} \mathbf{M}_k = \diag \left( \begin{matrix} \underbrace{ \Delta \mathbf{r}_k^\T,\cdots, \Delta \mathbf{r}_k^\T } \\ p \end{matrix} \right) \in {\mathbb R^{p \times pq}} \end{equation} \subsubsection{Linear Kalman Filter} LKF is an algorithm that estimates unknown states of a system by observing measurements and inaccuracies. The algorithm works in a two-step process: predict and update. With the prediction of the current states and their uncertainties, once the next measurement is observed, these prediction are updated using a weighted average. Firstly, denote the prediction of the state and its variance using $\hat{\mathbf{x}}_k^-$ and $\mathbf{P}_k^-$. Denote the update value of the state and its variance using $\hat{\mathbf{x}}_k$ and $\mathbf{P}_k$ with initialization of $\hat{\mathbf{x}}_0=\text{E}(\mathbf{x}_0)$ and $\mathbf{P}_0 = \text{Var} (\mathbf{x}_0)$ respectively. For system (\ref{eq-17}), present LKF as follows: \begin{align} \text{Predict:}\ \ \ \ \label{eq-19} {\mathbf{P}_k^-} &= {\mathbf{P}_{k - 1}} + \mathbf{A}_{k-1} \notag \\ {\mathbf{H}_k} &= {\mathbf{P}_{k}^-}\mathbf{M}_k^\T{\left( {{\mathbf{M}_k}{\mathbf{P}_{k}^-}\mathbf{M}_k^\T + \mathbf{B}_k} \right)^{ - 1}} \notag \\ \hat{\mathbf{x}}_k^- &= \hat{\mathbf{x}}_{k - 1} \notag \\ \text{Update:}\ \ \ \ {\mathbf{P}_k} &= {\left( {{\mathbf{E}_{pq}} - {\mathbf{H}_k\mathbf{M}_k}} \right)}{\mathbf{P}_k^-} \notag \\ {{\hat{\mathbf{x}}}_k} &= {{\hat{\mathbf{x}}}_k^-} + {\mathbf{H}_k}\left( {{\mathbf{y}_k} - {\mathbf{M}_k}{{\hat{\mathbf{x}}}_k^-}} \right) \\ {{\hat{\mathbf{y}}}_k} &= {\mathbf{M}_k}{{\hat{\mathbf{x}}}_k} \notag \end{align} Once we get $\hat{\mathbf{x}}_k$ at each step, we update the Jacobian ${{\hat{\mathbf{J}}}_k}$. But, LKF is only suitable for linear systems, when estimating the nonlinear time-varying Jacobian matrix, it may cause estimation errors. \subsubsection{Unscented Kalman Filter} KF preforms the propagation of a Gaussian Random Variable (GRV) through the system dynamics while LKF is not good enough to propagate a GRV for a nonlinear system \cite{wan2000unscented}. UKF selects a minimal set of sample points (so called sigma points) of system state $\mathbf{x}$ and guarantees the state distribution is again approximated by a GRV, using the Unscented Transformation (UT)\cite{Julier1995A,gustafsson2011some} which is an approach that maps system state $\mathbf{x}$ to sigma points $\boldsymbol{\chi}$, to fix the large error introduced by the first-order linearization of the nonlinear system. \\ Firstly, we rewrite \eqref{eq-17} into the nonlinear form: \begin{align} \label{eq-20} \mathbf{x}_k &= \boldsymbol{g}(\mathbf{x}_{k-1}) + \boldsymbol{\eta}_k \notag \\ \mathbf{y}_k &= \boldsymbol{h}(\mathbf{x}_k) + \boldsymbol{\nu}_k \end{align} Initialize the mean and covariance of the state with $\hat{\mathbf{x}}_0=\text{E}(\mathbf{x}_0)$ and $\mathbf{P}_{x,0} = \text{Var} (\mathbf{x}_0)$ respectively. Define a matrix $\boldsymbol{\chi} \in \mathbb{R}^{pq\times(2pq+1)}$ of $2pq+1$ sigma vectors $\boldsymbol{\chi}_i\in\mathbb{R}^{pq}$: \begin{align} \label{eq-21} \boldsymbol{\chi}_{k}^0 &= \hat{\mathbf{x}}_{k} \notag\\ \boldsymbol{\chi}_{k}^i &= \hat{\mathbf{x}}_{k} + \left({\sqrt {\left ({pq + \kappa} \right){\mathbf{P}_{x,k}}} } \right)_i \notag\\ \boldsymbol{\chi}_{k}^{i+pq} &= \hat{\mathbf{x}}_{k} - \left({\sqrt {\left ({pq + \kappa} \right){\mathbf{P}_{x,k}}} } \right)_i \end{align} where $i = 1,\cdots,pq$ and ${\left( \bullet \right)_i}$ is the $i$th column of the matrix which should be decomposed using numerical method such as SVD and Cholesky decomposition. The coresponding first-order weights $W^{\left( m \right)}$ and second-order weights $W^{\left( c \right)}$ are \begin{align} \label{eq-22} W_0^{\left( m \right)} &= \frac{{\kappa} }{{pq + {\kappa} }} \notag\\ W_0^{\left( c \right)} &= \frac{{\kappa} }{{pq + {\kappa}}} + \left( {1 - {{\alpha} ^2} + {\beta} } \right)\notag\\ W_i^{\left( m \right)} &= W_i^{\left( c \right)} =\frac{{\kappa} }{{2\left( {pq + {\kappa} } \right)}}, \ \ \ i=1,\cdots,2pq. \end{align} where ${\kappa} = {{\alpha} ^2}\left( {pq + {\lambda}} \right) - pq$ is a scaling parameter. ${\alpha}$ determines the spread of the sigma points around $\hat{\mathbf{x}}_{k-1}$ which is usually set $1{e^{ - 1}} \le {\alpha} \le 1$. ${\lambda}$ is a secondeary scaling parameter, usually set to $0$. ${\beta}$ is state distribution parameters, for Guassian distribution, usually set to 2. \\ The above sigma points in (\ref{eq-21}) are transformed through the state equation $\boldsymbol{g}(\bullet)$ and observation equation $\boldsymbol{h}(\bullet)$ of the system to obtain new sigma points $\boldsymbol{\gamma}$: \begin{align} \label{eq-23} {\boldsymbol{\chi} _k} &= \boldsymbol{g}\left( {{\boldsymbol{\chi} _{k - 1}}} \right) = {\boldsymbol{\chi} _{k - 1}} \notag \\ {\boldsymbol{\gamma} _k} &= \boldsymbol{h}\left( {{\boldsymbol{\chi} _k}} \right) =\mathbf{M}_k {\boldsymbol{\chi} _k}\\ \hat{\mathbf{y}}_{k}^- &= \sum\limits_{i = 0}^{2pq} {W_i^{\left( m \right)}\boldsymbol{\gamma} _k^i} \notag \end{align} Then, present classical two-step KF frame to the new sigma points: \begin{align} \text{Predict:}\ \ &\hat{\mathbf{x}}_{k}^- = \sum\limits_{i = 0}^{2pq} {W_i^{\left( m \right)}\boldsymbol{\chi} _k^i} \notag \\ &\mathbf{P}_{x,k}^- = \sum\limits_{i = 0}^{2pq} {W_i^{\left( c \right)}\left( {\boldsymbol{\chi} _k^i - \hat{\mathbf{x}}_k^- } \right){{\left( {\boldsymbol{\chi} _k^i - \hat{\mathbf{x}}_{k}^-} \right)}^\T}} + {\mathbf{A}_k} \notag \\ \text{Update:}\ \ &{\mathbf{P}_{y,k}} = \sum\limits_{i = 0}^{2pq} {W_i^{\left( c \right)}\left( {\boldsymbol{\gamma} _k^i - \hat{\mathbf{y}}_{k}^-} \right){{\left( {\boldsymbol{\gamma} _k^i - \hat{\mathbf{y}}_{k}^-} \right)}^\T}} + {\mathbf{B}_k} \notag \\ &{\mathbf{P}_{xy,k}} = \sum\limits_{i = 0}^{2pq} {W_i^{\left( c \right)}\left( {\boldsymbol{\chi} _k^i - \hat{\mathbf{x}}_{k}^-} \right){{\left( {\boldsymbol{\gamma} _k^i - \hat{\mathbf{y}}_{k}^-} \right)}^\T}} \notag \\ &\mathbf{K} = {\mathbf{P}_{xy,k}}\mathbf{P}_{y,k}^{ - 1} \notag \\ &{{\hat{\mathbf{x}}}_k} = \hat{\mathbf{x}}_{k}^- + \mathbf{K}\left( {{\mathbf{y}_k} - \hat{\mathbf{y}}_{k}^-} \right) \notag \\ &{\mathbf{P}_{x,k}} = \mathbf{P}_{x,k-1} - \mathbf{K}{\mathbf{P}_{y,k}}{\mathbf{K}^\T} \end{align} Once we get $\hat{\mathbf{x}}_k$ at each step, we update the Jacobian ${{\hat{\mathbf{J}}}_k}$. \subsection{Shape Servoing Controller} Let us assume that at the time instant $k$, the transformation matrix ${\hat{\mathbf{J}}_k}$ has been exactly estimated by the online estimator, so that the shape-motion difference model satisfies: \begin{equation} \label{eq-25} \mathbf{s}_k = \mathbf{s}_{k-1} + \hat{\mathbf{J}}_k \cdot \Delta \mathbf{r}_k \end{equation} In this section, we design the necessary motion command $\Delta \mathbf{r}_k$ to minimize the shape error between the measured feature $\mathbf{s}_k$ and a constant target feature $\mathbf{s}^*$. Define the deformation error as ${\mathbf{e}_k = {\mathbf{s}^* - \mathbf{s}_k}}$. Then, according to (\ref{eq-25}), we have \begin{align} \label{eq-26} {\mathbf{e}_k} - {\mathbf{e}_{k - 1}} &= {{-\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k} \\ \label{eq-27} {\mathbf{e}_k} + {\mathbf{e}_{k - 1}} &= 2{\mathbf{e}_{k - 1}} - {{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k} \end{align} Our new shape control method also has the capability to limit the magnitude of $\Delta \mathbf{r}_k$, which helps to avoid drastic instantaneous movements during the shaping motions (this valuable property is particularly useful during the manipulation of soft/delicate objects). To this end, consider first the following performance index: \begin{equation} \label{eq-28} Q = \mathbf{e}_k^\T \mathbf{e}_k + \lambda \Delta \mathbf{r}_k^\T \Delta \mathbf{r}_k \end{equation} where ${\lambda}$ is the weight that controls the magnitude of ${\Delta \mathbf{r}_k}$. It can also guarantee the smoothness of $\mathbf{r}_k$. Note that if ${\lambda}$ is too small, the system may oscillate or even lose stability. By substituting (\ref{eq-26}) into (\ref{eq-28}), we have: \begin{equation} \label{eq-29} Q = \left( \mathbf{e}_{k-1} - \hat{\mathbf{J}}_k\Delta {\mathbf{r}_k}\right)^\T\left( \mathbf{e}_{k-1} - \hat{\mathbf{J}}_k\Delta {\mathbf{r}_k}\right) + \lambda \Delta \mathbf{r}_k^\T \Delta \mathbf{r}_k \end{equation} The partial derivative of (\ref{eq-29}) along ${\Delta {\mathbf{r}_k}}$ yields: \begin{equation} \label{eq-30} \frac{{\partial Q}}{{\partial \Delta {\mathbf{r}_k}}} = - 2{\hat{\mathbf{J}}_k^\T} \left( \mathbf{e}_{k-1} - \hat{\mathbf{J}}_k\Delta {\mathbf{r}_k} \right) + 2{\lambda} \Delta {\mathbf{r}_k} \end{equation} By equating (\ref{eq-30}) to zero, we can compute the velocity command $\Delta {\mathbf{r}_k}$ as: \begin{equation} \label{eq-31} \Delta {\mathbf{r}_k} = {\left( {{\lambda}\mathbf{E}_q + {\hat{\mathbf{J}}_k^\T}\hat{\mathbf{J}}_k} \right)^{ - 1}}{\hat{\mathbf{J}}_k^\T} \mathbf{e}_{k-1} \end{equation} Thus, at each time step, the incremental position command is calculated as follows: \begin{equation} \label{eq-32} {\mathbf{r}_k} = {\mathbf{r}_{k - 1}} + {\left( {{\lambda} \mathbf{E}_q + {\hat{\mathbf{J}}_k^\T}\hat{\mathbf{J}}_k} \right)^{ - 1}}{\hat{\mathbf{J}}_k^\T}\mathbf{e}_{k-1} \end{equation} \begin{proposition} {\rm Consider that the model estimation algorithm (either LKF or UKF) exactly approximates the deformation Jacobian matrix such that $\mathbf J_k = \hat{\mathbf J}_k$. For this situation, the shape servo-controller \eqref{eq-31} enforces a stable (passive) closed-loop system that locally minimises the error $\mathbf{e}_k$ to a steady-state area whose magnitude depends on the feasibility of the target feature.} \end{proposition} \begin{IEEEproof} \rm From (\ref{eq-31}), we can have the expression: \begin{equation} \label{eq-33} \mathbf{e}_{k - 1}^\T{{\hat{\mathbf{J}}}_k} = \Delta \mathbf{r}_k^\T\left( {\lambda \mathbf{E}_q + \hat{\mathbf{J}}_k^\T{{\hat{\mathbf{J}}}_k}} \right) \end{equation} Let us define the discrete Lyapunov function and its finite difference as \cite{Sarpturk1987On}: \begin{align} \label{eq-34} V_k &= \frac{1}{2}\mathbf{e}_k^\T\mathbf{e}_k \\ \label{eq-35} \Delta V_k &= V_k - V_{k - 1} = \frac{1}{2}\mathbf{e}_k^\T\mathbf{e}_k - \frac{1}{2}\mathbf{e}_{k - 1}^\T\mathbf{e}_{k - 1} \end{align} By substituting (\ref{eq-26}) and (\ref{eq-27}) into (\ref{eq-35}) we obtain: \begin{align} \label{eq-36} \Delta {V_k} &= \frac{1}{2}{\left( {{\mathbf{e}_k} + {\mathbf{e}_{k - 1}}} \right)^\T}\left( {{\mathbf{e}_k} - {\mathbf{e}_{k - 1}}} \right) \notag \\ &= - \left( {{\mathbf{e}_{k - 1}} - \frac{1}{2}{{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k}} \right)^\T{{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k} \notag\\ &= -\mathbf{e}_{k - 1}^\T{{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k} + \frac{1}{2}\Delta \mathbf{r}_k^\T\hat{\mathbf{J}}_k^\T{{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k} \end{align} Then, substituting (\ref{eq-33}) into (\ref{eq-36}) yields: \begin{align} \label{eq-37} \Delta {V_k} &= -\Delta \mathbf{r}_k^\T \left( \lambda \mathbf{E}_q + \hat{\mathbf{J}}_k^\T\hat{\mathbf{J}}_k \right) \Delta \mathbf{r}_k + \frac{1}{2}\Delta \mathbf{r}_k^\T \hat{\mathbf{J}}_k^\T {{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k} \notag \\ &= - \Delta \mathbf{r}_k^\T\mathbf{L}_1\Delta {\mathbf{r}_k} = - \mathbf{e}_{k-1}^\T \mathbf{L}_2 {\mathbf{e}_{k-1}} \notag \le 0 \notag \\ \mathbf{L}_1 &= \lambda \mathbf{E}_q + \frac{1}{2}\hat{\mathbf{J}}_k^\T{{\hat{\mathbf{J}}}_k} \notag \\ \mathbf{L}_2 &= {{\hat{\mathbf{J}}}_k}{\left( {\lambda \mathbf{E}_q + \hat{\mathbf{J}}_k^\T{{\hat{\mathbf{J}}}_k}} \right)^{ - 1}}\mathbf{L}_1{\left( {\lambda \mathbf{E}_q + \hat{\mathbf{J}}_k^\T{{\hat{\mathbf{J}}}_k}} \right)^{ - 1}}\hat{\mathbf{J}}_k^\T \end{align} The stability (passivity) of the system is guaranted since (by definition) the Jacobian matrix $\hat{\mathbf{J}}_k$ has a full column rank, therefore, the matrix $\mathbf{L}_1$ is symmetric and positive definite. Now, to analyze the stability properties of the feedback shape error $\mathbf e_k$, let us note that the symmetric matrix $\mathbf{L}_2$ is only positive semi-definite. This implies that the magnitude of the shape feedback error $\|\mathbf e_k\|$ can only be minimised to a local region around the origin. For these types of overdetermined visual servoing control schemes, global asymptotic convergence of the error cannot be guaranteed \cite{Book:Slotine}. \end{IEEEproof} \begin{remark} The proposed velocity command (\ref{eq-31}) and Jacobian estimation algorithms (LKF, UKF) are entirely determined from the input and output data collected by the sensor feedback and have no relationship with the mathematical model and order of the controlled process. \end{remark} \subsection{Online Parameter Tuning} In general, the weight ${\lambda}$ is constant, which makes the controller not adaptable to different control performance requirements. Meanwhile, elastic rods of different materials have different physical properties for manipulation. Some can be manipulated at high speed, while some are only suitable for chronic uniform deformation. Introducing parameter optimization criterion, the controller can be adaptively extended to various application scenarios. Since we define $\mathbf{e}_k = \mathbf{s}^* - \mathbf{s}_k$ and by referring to \eqref{eq-26} and \eqref{eq-31}, the closed-loop system can be obtained as follows: \begin{equation} \label{eq-38} \mathbf{e}_k = \mathbf{e}_{k-1} - {{\hat{\mathbf{J}}}_k}{\left( {\lambda \mathbf{E}_q + \hat{\mathbf{J}}_k^\T{\hat{\mathbf{J}}_k}} \right)^{ - 1}}\hat{\mathbf{J}}_k^\T \mathbf{e}_{k-1} \end{equation} There are several performance optimization criteria corresponding to diverse performance requirements. In this paper, three of them are introduced: \begin{enumerate} \item ISE criterion. Integral of the squared error (ISE) is one of the most well known criteria for obtaining optimal controller parameters \cite{Zhuang1993Automatic}, which penalizes both positive and negative errors. \begin{equation} \label{eq-39} H =\frac{1}{2} \sum\limits_{k = 1}^{\infty} {\mathbf{e}_k^\T{\mathbf{e}_k}} \end{equation} where, $\mathbf{e}_k$ defined in \eqref{eq-38}. According to \eqref{eq-31} and \eqref{eq-39}, we can obtain the ISE-based parameter optimization criterion as: \begin{align} \label{eq-40} \frac{{\partial H}}{{\partial \lambda }} &= \sum\limits_{k = 1}^{\infty} {\mathbf{e}_k^\T{{\hat{\mathbf{J}}}_k}{\mathbf{Z}}\hat{\mathbf{J}}_k^\T \mathbf{e}_{k-1}} \\ \label{eq-41} {\mathbf{Z}} &= {\left( {\lambda \mathbf{E}_q + \hat{\mathbf{J}}_k^\T{{\hat{\mathbf{J}}}_k}} \right)^{ - 2}} \end{align} \item IAE criterion. Another frequently used criteria, the integral of the absolute error (IAE), is shown as follows: \begin{equation} \label{eq-42} H = \sum\limits_{k = 1}^{\infty} {\left\| {{\mathbf{e}_k}} \right\|} \end{equation} Similar to the previous derivation, we can obtain the IAE-based parameter optimization criterion as: \begin{equation} \label{eq-43} \frac{{\partial H}}{{\partial \lambda }} = \sum\limits_{k = 1}^{\infty} {\frac{{\mathbf{e}_k^\T}}{{\sqrt {\mathbf{e}_k^\T{\mathbf{e}_k}} }}{{\hat{\mathbf{J}}}_k}{\mathbf{Z}}\hat{\mathbf{J}}_k^\T\mathbf{e}_{k-1}} \end{equation} where $\mathbf{Z}$ is defined by (\ref{eq-41}). Comparison of (\ref{eq-40}) and (\ref{eq-43}) shows that IAE is sensitive with small errors (smaller than one) while ISE works well on large errors. \item JEU criterion. ISE and IAE only consider the performance requirements on errors but not meet higher standards of the system, such as the minimum overshoot, the peak time, the rising time, etc.. Therefore, in order to more comprehensively adjust the system transition performance and dynamic properties, JEU criterion which is a weighted sum of ISE and Integral Squared Controller Output\cite{Xiong2005Study,das2013lqr} is used here. In our case, the velocity command constraint is added: \begin{equation} \label{eq-44} H = \frac{1}{2}\sum\limits_{k = 1}^{\infty} {{\omega _1}\mathbf{e} _k^\T{\mathbf{e}_k} + {\omega _2}\Delta \mathbf{r}_k^\T\Delta {\mathbf{r}_k}} \end{equation} where ${\omega}_1$ and ${\omega}_2$ are positive scalar weight that satisfy ${\omega}_1+{\omega}_2=1$. The parameter optimization criterion is: \begin{equation} \frac{{\partial H}}{{\partial \lambda }} = \sum\limits_{k = 1}^{\infty} {\left( {{\omega _1}\mathbf{e}_k^\T{{\hat{\mathbf{J}}}_k} - {\omega _2}\Delta \mathbf{r}_k^\T} \right){\mathbf{Z}}\hat{\mathbf{J}}_k^\T\mathbf{e}_{k-1}} \end{equation} where $\mathbf{Z}$ is defined by (\ref{eq-41}). Besides, ISE can be seen as a simplified version of JEU. \end{enumerate} For any of the above methods, the parameter ${\lambda}$ is updated with the gradient descent rule: \begin{equation} {{{\lambda} _k} = {{\lambda} _{k-1}} + \Delta {\lambda} },\qquad {\Delta {\lambda} = - d \cdot \frac{{\partial H}}{{\partial {\lambda} }}} \end{equation} where $H$ is defined in \eqref{eq-39}, \eqref{eq-42}, \eqref{eq-44} and $d$ is a small positive weight which controls the update rate of ${\lambda}$. \section{Simulation Results}\label{sect4} We consider a planar robot that rigidly grasps one end of an elastic rod, whose other end is static. A monocular vision sensor observes the manipulated cable and measures its 2D contour in real-time. The cable simulation is simulated as in \cite{Wakamatsu1995Modeling} by using the minimum energy principle \cite{Fleisch2015A}. This simulator is publicly available at \url{https://github.com/q546163199/shape_deformation/}. All numerical simulations are implemented in MATLAB. Since the real feedback data point is in pixels, the simulated cable is designed to move within the range of 600px$\times$600px. \subsection{Feature Extraction Comparison} \label{4a} To verify the accuracy of the proposed shape feature, we compare three regression equations (\ref{eq-9}), (\ref{eq-10}), (\ref{eq-11}) with the Fourier method \eqref{eq-12}. Fig. \ref{fig1} describes the error $(\bar{\mathbf{c}} - \bar{\mathbf{G}}\mathbf{s})$ between the original shape $\bar{\mathbf{c}}$ and the reconstruction shape $\bar{\mathbf{G}}\mathbf{s}$, which depicts the NURBS has the highest accuracy while the polynomial is the worst. The higher the polynomial order is, the worse the regression becomes. Table \ref{table1} shows that Fourier is the fastest. Although the NURBS is the slowest, it can be handled as long as the robot motion is slow enough. In the following sections, we uniformly use the NURBS with approximation order of 8. \begin{table}[H] \setlength{\abovecaptionskip}{-0.2 cm} \setlength{\belowcaptionskip}{-1cm} \caption{Comparison results among Fourier, Polynomial, B$\acute{\text{e}}$zier and NURBS among 30 shape sets} \label{table1} \centering \begin{tabular}{cccccc} \hline \thead[c]{} & \thead[c]{\textbf{G}}& \thead[c]{\textbf{s}} & \thead[c]{Order} & \thead[c]{Average time} & \thead[c]{Average error} \\ \hline Fourier & 200x18 & 18 & 4 & 0.002s & 8.1965px \\ Polynomial & 200x18 & 18 & 8 & 0.004s & 16.5667px \\ B$\acute{\text{e}}$zier & 200x18 & 18 & 8 & 0.007s & 10.1931px \\ NURBS & 200x18 & 18 & 8 & 0.011s & 4.5628px \\ \hline \end{tabular} \end{table} \begin{figure} \centering \includegraphics[scale=0.2]{fig21.pdf} \caption{Feature extraction comparison among polynomial, B$\acute{\text{e}}$zier, NURBS and Fourier among 30 shape sets in the simulation.} \label{fig1} \end{figure} \begin{figure} \vspace{-0.2cm} \centering \subfloat{\includegraphics[scale=0.155]{fig2a.pdf}}\quad \subfloat{\includegraphics[scale=0.155]{fig2b.pdf}}\quad \subfloat{\includegraphics[scale=0.155]{fig2c.pdf}}\\ \caption{Comparison between the visually measured cable profile (black solid line) and its approximation with NURBS series (red dashed line)} \label{fig9} \end{figure} \begin{figure} \vspace{-0.0cm} \centering \includegraphics[scale=0.25]{fig3.pdf} \caption{Profiles of the cost functions $T_1$ and $T_2$ that are computed along the circular trajectory around the center $(0.4,0.4)$.} \label{fig2} \end{figure} \begin{figure} \vspace{-0.2cm} \centering \subfloat{\includegraphics[scale=0.155]{fig4a.pdf}}\quad \subfloat{\includegraphics[scale=0.155]{fig4b.pdf}}\quad \subfloat{\includegraphics[scale=0.155]{fig4c.pdf}}\\ \caption{Initial (red dashed line) and target (black solid line) configurations of the shape deformation simulation among RLS, LKF, and UKF.} \label{fig10} \end{figure} \begin{figure} \vspace{-0.2cm} \centering \includegraphics[scale=0.25]{fig5.pdf} \caption{Profiles of the cost function $T_1$ and velocity command $\Delta \mathbf{r}_k$ among RLS, LKF and UKF within manipulation task.} \label{fig3} \end{figure} \begin{figure} \centering \includegraphics[scale=0.25]{fig23.pdf} \caption{Profiles of the cost function $T_1$ and velocity command $\Delta \mathbf{r}_k$ among FIX, ISE, IAE and JEU (${\omega}_1=0.5, {\omega}_2=0.5$) tested in the LKF case.} \label{fig5} \end{figure} \begin{figure} \centering \includegraphics[scale=0.25]{fig8.pdf} \caption{Profiles of the cost function $T_1$ and velocity command $\Delta \mathbf{r}_k$ between two different weight values (case 1: ${\omega}_1=0.1, {\omega}_2=0.9$ and case 2: ${\omega}_1=0.9, {\omega}_2=0.1$) of JEU (\ref{eq-44}) tested in the LKF case.} \label{fig7} \end{figure} \subsection{Validation of the Jacobian Estimation} \label{4b} In this section, we compare the accuracy of three methods in estimating the Jacobian matrix, namely, LKF, UKF, and Recursive Least Square (RLS) given in \eqref{eq23}. The cable is manipulated by the robot which moves along a circular trajectory whose center is $(0.4,0.4)$ in the anticlockwise direction. At the very beginning of the movement, the robot moves the grasped cable in an initial sampling area to initialize the Jacobian matrix, based on which Jacobian matrix update with new input and output data \begin{align} \label{eq23} {{\hat{\mathbf{J}}}_k} &= {{\hat{\mathbf{J}}}_{k - 1}} + \frac{{\left( {{\mathbf{y}_k} - {{\hat{\mathbf{J}}}_{k - 1}}\Delta {\mathbf{r}_k}} \right)\Delta \mathbf{r}_k^\T{\mathbf{U}_{k - 1}}}}{{{\lambda} + \Delta \mathbf{r}_k^\T{\mathbf{U}_{k - 1}}\Delta {\mathbf{r}_k}}} \notag \\ {\mathbf{U}_k} &= \frac{1}{{\lambda} }\left( {{\mathbf{U}_{k - 1}} - \frac{{{\mathbf{U}_{k - 1}}\Delta {\mathbf{r}_k}\Delta \mathbf{r}_k^\T{\mathbf{U}_{k - 1}}}}{{{\lambda} + \Delta \mathbf{r}_k^\T{\mathbf{U}_{k - 1}}\Delta {\mathbf{r}_k}}}} \right) \end{align} Fig. \ref{fig9} demonstrates three measured shapes (black solid line) of the cable in circular motion, and the corresponding approximated shapes (red dashed line) based on the feedback feature vector $\mathbf{s}$. To assess the accuracy of the proposed algorithms, two errors are computed throughout the process: \begin{align} \label{eq24} \begin{array}{*{20}{c}} {{T_1} = \left\| {\bar{\mathbf{c}}_k^* - \bar{\mathbf{c}}_k} \right\|}&{{T_2} = \left\| {{\Delta \mathbf{s}_k} - {{\hat{\mathbf{J}}}_k}\Delta {\mathbf{r}_k}} \right\|} \end{array} \end{align} Fig. \ref{fig2} demonstrates the plots of $T_1$ and $T_2$ during the circular motion. Except for the UKF method, both errors increase when the robot is initializing the Jacobian matrix and decrease when the Jacobian matrix estimitor starts to work. Compared with RLS and LKF, the UKF method has a stronger ability to estimate the Jacobian matrix for both errors quickly converge to a smaller steady error under the UKF method. \subsection{Manipulation of Elastic Rods} \label{4c} In this section, we use adaptive controller (\ref{eq-31}) with fixed ${\lambda}$ to allow the robot to manipulate the simulated cable into the desired shapes. Note that, to design feasible target cable shapes, a number of attempting computation is conducted. Fig. \ref{fig10} depicts the progress of the cable deformation under the controllers based on RLS, LKF, and UKF. The red dashed curves represent the initial and transitional trajectories, and the black solid curve represents the target shape with parameters vector $\mathbf{s}^*$. Fig. \ref{fig3} depicts the error $T_1$ and the velocity command $\Delta \mathbf{r}_k$. Table \ref{table2} clearly shows that UKF is the best method with the shortest convergence time and smallest deformation error. \begin{table}[h] \setlength{\abovecaptionskip}{-0.2 cm} \setlength{\belowcaptionskip}{-1 cm} \caption{Results among RLS, LKF and UKF} \label{table2} \centering \begin{tabular}{cccccc} \hline \thead[c]{} & \thead[c]{RLS}& \thead[c]{LKF} & \thead[c]{UKF} \\ \hline Steps & 534 & 488 & 158 \\ Time(second) & 55.54 & 48.83 & 17.91 \\ \hline \end{tabular} \end{table} \subsection{Comparison of Parameter Optimization} \label{4d} In this section, we compare the performance of various parameter optimization criteria, including FIX (fixed ${\lambda}$), ISE (\ref{eq-39}), IAE (\ref{eq-42}) and JEU (\ref{eq-44})), based on LKF. Fig. \ref{fig5} depicts the profiles of the error $T_1$ and the velocity command $\Delta \mathbf{r}_k$. Table \ref{table3} shows that ISE has shortest convergence time, while the FIX has the longest one, for ISE focuses on compensating errors so that the control command based on ISE heavily fluctuates in order to make the error converge as soon as possible. Meanwhile, ISE has a better performance than IAE for it is sensitive of large errors. \begin{table}[h] \setlength{\abovecaptionskip}{-0.2 cm} \setlength{\belowcaptionskip}{-1 cm} \caption{Comparison among Fixed, ISE, IAE and JEU tested in the LKF} \label{table3} \centering \begin{tabular}{cccccc} \hline \thead[c]{} & \thead[c]{Fixed}& \thead[c]{ISE} & \thead[c]{IAE} & \thead[c]{JEU} \\ \hline Steps & 386 & 186 & 233 & 291 \\ Time(second) & 36.42 & 17.18 & 21.92 & 31.17 \\ \hline \end{tabular} \end{table} To further illustrate the impact of different weight factors for JEU (\ref{eq-44}), we give two cases: \begin{itemize} \item case 1: ${\omega}_1=0.1, {\omega}_2=0.9$, namely, we pay more attention to the smoothness of the velocity command. \item case 2: ${\omega}_1=0.9, {\omega}_2=0.1$, namely, we pay more attention to the convergence speed of the error. \end{itemize} Fig. \ref{fig7} shows that the error in case 1 converges slower with smoother velocity commands than case 2. This further verifies the effectiveness and feasibility of the parameter optimization criterion (\ref{eq-44}). \begin{remark} In the real applications, it is necessary to set the weight coefficients ${\omega}_1, {\omega}_2$ reasonably to prevent damage of the robotic arm caused by high-frequency chattering of the command signal. \end{remark} \begin{figure} \centering \includegraphics[width=\columnwidth]{fig26.pdf} \caption{Experimental setup.} \label{fig11} \end{figure} \begin{figure} \vspace{-0.4cm} \centering \subfloat[Marker point]{\includegraphics[scale=0.13]{fig10a.png}\label{fig12a}} \subfloat[ROI selection]{\includegraphics[scale=0.13]{fig10b.png}\label{fig12b}} \subfloat[Thresholding]{\includegraphics[scale=0.13]{fig10c.png}\label{fig12c}} \subfloat[Thinning]{\includegraphics[scale=0.13]{fig10d.png}\label{fig12d}} \subfloat[Coordinate sorting]{\includegraphics[scale=0.13]{fig10e.png}\label{fig12e}} \subfloat[Downsampling]{\includegraphics[scale=0.13]{fig10f.png}\label{fig12f}} \caption{Image processing steps.} \label{fig12} \end{figure} \section{Experimental Results}\label{sect5} In this section, we conduct various experiments using a UR5 robot constrained to xy-plane $(q=2)$ motion $\Delta \mathbf{r} = (\Delta r_x, \Delta r_y) $ defined in the base frame. An experimental video demonstrating our method can be downloaded here \url{https://github.com/q546163199/experiment_video/raw/master/paper1/video.mp4}. Fig. \ref{fig11} shows our experiment setup. The rod's images are captured by a Logitech C270 camera and processed with a Linux-based PC at 30 fps and OpenCV. The results are displayed by MATLAB. We assess each algorithm's convergence speed by comparing the deformation of the moving cable every two frames. \begin{algorithm}[t] \caption{Centerline of the object coordinate sorting} \label{alg::1} \begin{algorithmic}[1] \Require Unordered centerline ${\mathbf{p}_{in}} = \left[ {{p}_{in}^0, \ldots ,{p}_{in}^N} \right]$; starting point $p_{out}^0$; \Ensure Ordered centerline ${\mathbf{p}_{out}} = \left[ {{p}_{out}^0, \ldots ,{p}_{out}^N} \right]$; \State $k=0$, $j=0$ \State $box\_size=10$ \While {$j <= N-1$} \For{$i=0$ to $column(\mathbf{p}_{in})-1$} \If {${{{| {p_{in}^i - p_{out}^j} |}_x} \le box\_size}$ $\text{and}\qquad\qquad\qquad$ ${{{| {p_{in}^i - p_{out}^j} |}_y} \le box\_size}$} \State Save ${p_{box}^k} = p_{in}^i$ with index $i$ \State $k=k+1$ \EndIf \EndFor \State $index = \left\{ {i|\min \left\| {p_{box}^k - p_{out}^j} \right\|}_2 \right\}$ \State $j=j+1$ \State $p_{out}^{j}=p_{in}^{index}$ \State Delete $p_{in}^{index}$ from $\mathbf{p}_{in}$ \State $k=0$ \State Reset $\mathbf{p}_{box}$ \EndWhile \end{algorithmic} \end{algorithm} \subsection{Image Processing} \label{5a} This section presents the relevant image processing for feature extraction and data sampling. The overall process (shown in Fig. \ref{fig12}) is as follows: \begin{enumerate} \item Segment the red area nearby the gripper based on HSV color space and abstract it as a green marker point (see Fig. \ref{fig12a}). \item Segment the region of the interest (ROI) containing the rod according to the green marker point (see Fig. \ref{fig12b}). \item Identify the rod in ROI, remove the noise, and obtain a binary image with the skeleton of the rod using OpenCV morphological opening algorithm (see Fig. \ref{fig12c}). \item Get an unordered centerline by applying OpenCV GUOHALL thinning algorithm to the rod skeleton (see Fig. \ref{fig12d}). \item Design the {\bf Algorithm} \ref{alg::1} to get the ordered centerline. Note that starting point is the closest point to the marker point on the centerline. (see Fig. \ref{fig12e}). \item Equidistantly sample the ordered centerline to get a fixed number of data points (see Fig. \ref{fig12f}). \end{enumerate} \begin{figure} \vspace{-0.4cm} \centering \includegraphics[scale=0.2]{fig11.pdf} \caption{Feature extraction comparison among polynomial, B$\acute{\text{e}}$zier, NURBS and Fourier among on 30 shape sets in the experiment.} \label{fig13} \end{figure} \begin{figure} \vspace{-0.5cm} \centering \subfloat[RLS]{\includegraphics[scale=0.13]{fig12a.png}} \subfloat[LKF]{\includegraphics[scale=0.13]{fig12b.png}} \subfloat[UKF]{\includegraphics[scale=0.13]{fig12c.png}} \caption{Comparison between the visually measured cable profile (green dashed line) and its approximation with NURBS series (red dashed line)} \label{fig14} \end{figure} \begin{figure} \centering \includegraphics[scale=0.25]{fig13.pdf} \caption{Profiles of the cost functions $T_1$ and $T_2$ that are computed along the circular trajectory.} \label{fig15} \end{figure} \begin{figure*} \vspace{-0.4cm} \centering \subfloat[experiment1-RLS]{\includegraphics[scale=0.133]{fig14a1.png}} \subfloat[experiment2-RLS]{\includegraphics[scale=0.133]{fig14b1.png}} \subfloat[experiment3-RLS]{\includegraphics[scale=0.133]{fig14c1.png}} \subfloat[experiment4-RLS]{\includegraphics[scale=0.133]{fig14d1.png}} \subfloat[experiment5-RLS]{\includegraphics[scale=0.133]{fig14e1.png}} \subfloat[experiment6-RLS]{\includegraphics[scale=0.133]{fig14f1.png}} \subfloat[experiment1-LKF]{\includegraphics[scale=0.133]{fig14a2.png}} \subfloat[experiment2-LKF]{\includegraphics[scale=0.133]{fig14b2.png}} \subfloat[experiment3-LKF]{\includegraphics[scale=0.133]{fig14c2.png}} \subfloat[experiment4-LKF]{\includegraphics[scale=0.133]{fig14d2.png}} \subfloat[experiment5-LKF]{\includegraphics[scale=0.133]{fig14e2.png}} \subfloat[experiment6-LKF]{\includegraphics[scale=0.133]{fig14f2.png}} \subfloat[experiment1-UKF]{\includegraphics[scale=0.133]{fig14a3.png}} \subfloat[experiment2-UKF]{\includegraphics[scale=0.133]{fig14b3.png}} \subfloat[experiment3-UKF]{\includegraphics[scale=0.133]{fig14c3.png}} \subfloat[experiment4-UKF]{\includegraphics[scale=0.133]{fig14d3.png}} \subfloat[experiment5-UKF]{\includegraphics[scale=0.133]{fig14e3.png}} \subfloat[experiment6-UKF]{\includegraphics[scale=0.133]{fig14f3.png}} \caption{Initial (black solid line), transition (green solid line) and target (red solid line) configurations in the six shape deformation experiments which have a variety of different initial and target shape with a single robot among RLS, LKF and UKF.} \label{fig16} \end{figure*} \begin{figure*} \centering \subfloat[experiment1 result]{\includegraphics[scale=0.44]{fig15a.pdf}} \subfloat[experiment2 result]{\includegraphics[scale=0.44]{fig15b.pdf}} \subfloat[experiment3 result]{\includegraphics[scale=0.44]{fig15c.pdf}} \subfloat[experiment4 result]{\includegraphics[scale=0.44]{fig15d.pdf}} \subfloat[experiment5 result]{\includegraphics[scale=0.44]{fig15e.pdf}} \subfloat[experiment6 result]{\includegraphics[scale=0.44]{fig15f.pdf}} \caption{Profiles of the cost function $T_1$ and velocity command $\Delta \mathbf{r}_k$ among RLS, LKF and UKF within six shape deformation experiments.} \label{fig17} \end{figure*} \begin{figure} \vspace{-0.6cm} \centering \subfloat[Fault case 1]{\includegraphics[scale=0.16]{fig20a.png}\label{fig20a}} \subfloat[Fault case 2]{\includegraphics[scale=0.16]{fig20b.png}\label{fig20b}} \caption{Fault shape deformation experiments display.} \label{fig22} \end{figure} \begin{figure} \vspace{-0.6cm} \centering \subfloat[FIX]{\includegraphics[scale=0.15]{fig16a.png}} \subfloat[ISE]{\includegraphics[scale=0.15]{fig16b.png}} \subfloat[IAE]{\includegraphics[scale=0.15]{fig16c.png}} \subfloat[JEU]{\includegraphics[scale=0.15]{fig16d.png}} \caption{Initial (black solid line), transition (green solid line) and target (red solid line) configurations among FIX, ISE, IAE and JEU (${\omega}_1=0.5, {\omega}_2=0.5$) tested in the LKF.} \label{fig18} \end{figure} \begin{figure} \vspace{-0.2cm} \centering \includegraphics[scale=0.25]{fig17.pdf} \caption{Profiles of the cost function $T_1$ and velocity command $\Delta \mathbf{r}_k$ among FIX, ISE, IAE and JEU (${\omega}_1=0.5, {\omega}_2=0.5$) tested in the LKF.} \label{fig19} \end{figure} \begin{figure} \vspace{-0.2cm} \centering \subfloat[case 1]{\includegraphics[scale=0.15]{fig18a.png}} \subfloat[case 2]{\includegraphics[scale=0.15]{fig18b.png}} \caption{Initial (black solid line), transition (green solid line) and target (red solid line) configurations between two conditions (case 1: ${\omega}_1=0.01, {\omega}_2=0.99$ and case 2: ${\omega}_1=0.99, {\omega}_2=0.01$) of JEU (\ref{eq-44}) tested in the LKF.} \label{fig21} \end{figure} \begin{figure} \centering \includegraphics[scale=0.25]{fig18.pdf} \caption{Profiles of the cost function $T_1$ and velocity command $\Delta \mathbf{r}_k$ between two different weight values (case 1: ${\omega}_1=0.01, {\omega}_2=0.99$ and case 2: ${\omega}_1=0.99, {\omega}_2=0.01$) of JEU (\ref{eq-44}) tested in the LKF.} \label{fig20} \end{figure} \subsection{Feature Extraction Comparison} Similar to Section \ref{4a}, we control the random movement of the UR5 to get 30 sets of centerline data; Fig. \ref{fig13} shows these comparison results. We can see that NURBS's fitting accuracy is still the best, while the polynomial is the worst; this is consistent with the simulation results. It further verifies the effectiveness of the feature extraction algorithms designed in this paper. In the following sections, we use NURBS with approximation order of 8. \subsection{Validation of the Jacobian Estimation} Similar to Section \ref{4b}, we test the accuracy of three methods (RLS, LKF, and UKF) for estimating the Jacobian matrix. In Fig. \ref{fig14}, the green dashed line is obtained by real feedback measurement, while the red dashed line represents the cable's estimation centerline with the NURBS series. From Fig. \ref{fig15}, we can see that UKF estimates are the best. Meanwhile, no noticeable fluctuation of UKF plots reflects the strong adaptability of the UKF algorithm to effectively estimate the Jacobian matrix in different local regions. \subsection{Manipulation of Elastic Rods} Similar to Section \ref{4c}, we use the proposed adaptive controller (\ref{eq-31}) with fixed ${\lambda}$ to allow the robot to manipulate the simulated cable into the desired shapes. Note that, to design feasible target cable shapes, the robot grasping the cable moves to a predefined position and the target shape is computed using image processing and shape feature extraction algorithm. Then, the robot automatically goes back to the initial position and starts the shape deformation experiment. Considering safety, the upper limit of the saturation of the velocity command $\Delta \mathbf{r}_k$ is set to $0.01 m/s$. We carry out six experiments with a variety of different initial and desired shapes, shown in Fig. \ref{fig16}, while Fig. \ref{fig17} shows the profiles of $T_1$ and the velocity command $\Delta \mathbf{r}_k$. No apparent fluctuations in Fig. \ref{fig16} shows that the proposed algorithms have excellent adaptability to the different starting conditions. Corresponding to the simulation results, Fig. \ref{fig17} shows that UKF converges the fastest while FIX is the slowest. UKF can quickly respond to sudden deviations of the system and control the robot back to the normal state, showing the strong adaptability and robustness. During the experiment, we found the following fault conditions, shown in Fig. \ref{fig22}. \begin{enumerate} \item If the initial shape is too different from the target shape or the initial sampling area, it is easy to cause singular control problems, seen in Fig. \ref{fig20a}. \item If the target shape is similar to a straight line, as the proposed feature extraction algorithm is based on the least square method, so it is easy to cause singularity in the feature extractor, which makes the velocity command $\Delta \mathbf{r}_k$ too large and the system out of control, seen in Fig. \ref{fig20b}. \end{enumerate} Therefore, in the practical applications, it is necessary to guarantee the initial shape around the initial sampling area and avoid singular shapes such as straight lines. \subsection{Parameter Optimization Comparison} Similar to Section \ref{4d}, we validate the effectiveness of the proposed parameter optimization criteria based on LKF, shown in Fig. \ref{fig18}. Set the upper limit of the velocity command $\Delta \mathbf{r}_k$ as $0.02m/s$. Fig. \ref{fig19} demonstrates that three adaptive methods (ISE, IAE, and JEU) converge to smaller errors and provide smoother velocity commands than FIX. Meanwhile, ISE converges the fastest and FIX converges the slowest. Since we set ${\omega}_1=0.5,{\omega}_2=0.5$ for JEU method, to some extent, the effect of JEU is similar to IAE. At the same time, the velocity command $\Delta \mathbf{r}_k$ fluctuates heavily under the ISE and keeps stable under the JEU. The correspondence between experimental results and simulation results demonstrates that the proposed parameter optimization criteria can effectively adjust the dynamic value of ${\lambda}$ according to the control requirements. Consistent with the simulation part, we also verify the effect of the JEU with different weight coefficients, shown in Fig. \ref{fig21}. The Difference is that, to highlight the impact of different weight coefficients, we design, case 1: ${\omega}_1=0.01, {\omega}_2=0.99$ and case 2: ${\omega}_1=0.99, {\omega}_2=0.01$. Fig. \ref{fig20} shows that the error in case 1 converges slower with smoother velocity commands. In contrast, the velocity command of case 2 is relatively larger and close to the upper limit of saturation. From Fig. \ref{fig20}, we know different weight coefficients of JEU can bring significantly different control performance, thus, in the practical applications, they should be thoughtfully designed according to the system performance requirements. \section{Conclusion}\label{sect6} This paper presents a new visual servoing framework for automatically manipulating elastic rods to a desired configuration; It includes shape feature design, Jacobian matrix estimation, and online parameter optimization. First, new shape features (B$\acute{\text{e}}$zier/NURBS) based on a regressive identification process are presented to characterize the object's contour. Second, we compare the performance of two KFs (LKF, UKF) in estimating the nonlinear time-varying Jacobian matrix. Then, the velocity command and its implementation are derived. To optimize control parameters, we utilize various performance criteria and an adaptive update law combined with a gradient descent rule. Finally, numerical and experimental results validate the effectiveness and feasibility of the proposed control method. The proposed shape features (B$\acute{\text{e}}$zier/NURBS) flexibly represent the high-dimension contour information with a low-dimension feature vector, in which NURBS has the highest accuracy. The identification method needs no artificial markers which makes it suitable for real-world applications. When estimating the shape Jacobian matrix, UKF performs better than LKF at nonlinear time-varying scenarios. The introduced parameter optimization criteria are able to meet different performance requirements and achieve online adaptive parameter adjustment. The sensorimotor model is estimated from visual feedback data without prior knowledge of the object deformation properties and camera calibration. The proposed method also has many limitations. For instance, the manipulated object is limited to elastic materials (i.e. with a self-recovery ability), hence, the proposed approach might not be suitable for inelastic or non-homogeneous objects. The method is not able to judge if the desired configuration is reachable, which might lead to the failure during the task. Besides, the proposed centerline coordinate sorting algorithm has an inevitable delay; Thus, the algorithm is mainly applied to the low-speed movements. For the KF-based estimators, it should be assumed that both process noise and measurement noise are Gaussian noise with known distribution (in the simulations and experiments, we set both as constant matrices), which is hard to guarantee in practice. We also assume that the object is always within the camera's visible range. However, occlusions caused by the robot's movement or the object itself may sometimes happen. As future work, we plan to manipulate objects into a more complex shapes, such as spatial 3D shapes or by using multiple robots. An algorithm with a complete feature detection will be designed to improve the system's robustness in the case of occlusion. We may combine neural networks (due to its strong nonlinear function approximation ability) with the manipulation tasks to obtain more accurate features and to determine the reachability of the desired shape. \appendices \ifCLASSOPTIONcaptionsoff \newpage \fi
{'timestamp': '2020-08-18T02:17:14', 'yymm': '2008', 'arxiv_id': '2008.06896', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06896'}
arxiv
\subsection{Experimental Setup} We train our model using SGD with momentum using an initial learning rate of $10^{-4}$, momentum of 0.9 and a weight decay of $5x10^{-4}$. A learning rate scheduling is used where it is divided by 10 at iterations 280k and 600k. We train with batch size 4 for 150 number of epochs using ImageNet~\cite{denglarge} pretrained weights. The rest of the hyper-parameters and data augmentation technique are similar to YOLACT~\cite{bolya2019yolact}. For the dataset, we extend KITTIMoSeg with instance motion masks as explained in section~\ref{sec:instmoseg} to create InstanceMotSeg dataset which is used in training our network in addition to DAVIS'17~\cite{Caelles_arXiv_2019}. We plan to release the augmented labels for KITTIMoSeg to benefit researchers working on motion instance segmentation for autonomous driving. Finally, we report frame rate and time in milliseconds for all models running on Titan Xp GPU on image resolution 550 $\times$ 550 including FuseMODNet~\cite{Rashed_2019_ICCV_Workshops}. \subsection{Benchmarking and Analysis} \begin{table}[] \caption{Quantitative comparison between our proposed model and state-of-the-art motion segmentation methods. } \label{tab:compare_motion_seg} \centering \resizebox{0.45\textwidth}{!}{ \begin{tabular}{|l|l|c|c|c|c|} \hline Model & Moving IoU & Background IoU & mIoU & FPS \\ \hline RTMotSeg~\cite{siam2018real} & 50 & 99.1 & 74.6 & {25} \\ FuseMODNet~\cite{Rashed_2019_ICCV_Workshops} & 53.2 & 99.3 & 76.2 & 18 \\ Ours & \textbf{59.7} & \textbf{99.4} & \textbf{79.5} & \textbf{39} \\ \hline \end{tabular} } \end{table} We benchmarked our model with other state of the art motion segmentation methods in Table~\ref{tab:compare_motion_seg}. Since we are the first to propose instance motion segmentation in autonomous driving literature we post-process the instance motion masks into pixel-level motion segmentation and compare using mean intersection over union for moving pixels and frame rate. The closest work in motion segmentation literature is RTMotSeg~\cite{siam2018rtseg} and FuseMODNet~\cite{Rashed_2019_ICCV_Workshops}. Our model outperforms these methods in terms of mean IoU with 3.3\% and 4.9\% respectively. Also in terms of frames per second, our MobileNetV2 model is a more efficient solution with $\sim$ 39 fps than FuseMODNet model. Furthermore, we provide exhaustive ablation studies in Table~\ref{tab:quantitative}. Two main factors are studied namely: (A) The impact of different input modalities to the model. In this study, we provide results which help us evaluate the importance of using optical flow against stack of images where the network learns to model motion implicitly. (B) The impact of various backbones to estimate the optimal performance in terms of accuracy vs speed trade-off. For this purpose, we explore ResNet101~\cite{he2016deep}, EfficientNet~\cite{tan2019efficientnet}, ShuffleNetV2~\cite{ma2018shufflenet} and MobileNetV2~\cite{sandler2018mobilenetv2} as backbone architectures. Table~\ref{tab:quantitative} demonstrates quantitative results evaluated on our dataset using various network architectures. Significant improvement of 11\% in mean average precision has been observed with feature-fusion which confirms the conclusions of \cite{siam2018modnet,yahiaoui2019fisheyemodnet,rashed2019motion}. Due to limitations of embedded devices used in autonomous driving, we focus our experiments on achieving the best balance between accuracy and speed using various network architectures. MobileNetV2 has the best run-time while maintaining the second best mean average precision. The best performing backbone is ShufflenetV2 with an insignificant improvement over MobileNetV2 with 0.3\%, but lower frames per second. {To our surprise, MobileNetV2 provides higher accuracy than the more complex ResNet101 architecture. It is probably because of the overfit to the training data and a higher network capacity is not required for the proposed task on InstanceMotSeg dataset.} Thus, MobileNetV2 provides the best speed-accuracy trade-off. \begin{figure*}[t] \captionsetup[subfigure]{labelformat=empty} \centering \begin{subfigure}{.498\textwidth} \includegraphics[width=\textwidth]{content/Images/results/008408_GT.png} \vspace{-1cm} \caption{\textcolor{white}{(a)}} \end{subfigure}% \hfill \begin{subfigure}{.498\textwidth} \includegraphics[width=\textwidth]{content/Images/results_moving/rgbOnly.png} \vspace{-1cm} \caption{\textcolor{white}{(b)}} \end{subfigure}% \quad \begin{subfigure}{.498\textwidth} \includegraphics[width=\textwidth]{content/Images/results_moving/efficientNet.png} \vspace{-1cm} \caption{\textcolor{white}{(c)}} \end{subfigure}% \hfill \begin{subfigure}{.498\textwidth} \includegraphics[width=\textwidth]{content/Images/results_moving/mobileNet.png} \vspace{-1cm} \caption{\textcolor{white}{(d)}} \end{subfigure} \quad \caption{Qualitative results using our model on KITTI dataset. \textbf{(a)} Ground Truth, \textbf{(b)} RGB-only, \textbf{(c)} Feature-Fusion EfficientNet, \textbf{(d)} Feature-Fusion MobileNet} \label{fig:qualitativeEval_Single} \end{figure*} Figure \ref{fig:qualitativeEval_Single} shows our qualitative results on KITTI dataset. (a) shows the ground truth of the moving instances using weak annotations in \cite{Rashed_2019_ICCV_Workshops}. (b) demonstrates inability of the baseline network to distinguish between moving and static objects using only color images without feeding the network with any motion signal. (c), (d) demonstrate our results using different backbones where MobileNetV2 show the best accuracy vs speed trade-off as shown in Table \ref{tab:quantitative}. \begin{table}[] \caption{Quantitative Evaluation of Class Agnostic \& Semantic Instance Segmentation on DAVIS'17-val $AP_{50}$ score. } \label{tab:quantitative_MTL_DAVIS} \centering \resizebox{0.4\textwidth}{!}{ \begin{tabular}{|l|c|c|c|c|} \hline \multirow{2}{*}{Backbone} & \multicolumn{2}{c|}{Class Agnostic} & \multicolumn{2}{c|}{Semantic} \\ \cline{2-5} & Mask & Box & Mask & Box \\ \hline ResNet101 & 23.5 & \textbf{45.4} & \textbf{42.9} & \textbf{56.2} \\ MobileNetV2 & \textbf{28.2} & 45.3 & \textbf{42.9} & 55.6 \\ \hline \end{tabular} } \vspace{-0.5cm} \end{table} \begin{figure*}[t!] \captionsetup[subfigure]{labelformat=empty} \centering \begin{subfigure}{0.25\textwidth} \includegraphics[width=\textwidth]{content/Images/class_agnostic/00215_small.jpg} \end{subfigure}% \begin{subfigure}{.25\textwidth} \includegraphics[width=\textwidth]{content/Images/class_agnostic/00426_small.jpg} \end{subfigure}% \begin{subfigure}{.25\textwidth} \includegraphics[width=\textwidth]{content/Images/class_agnostic/00617_small.jpg} \end{subfigure}% \begin{subfigure}{.25\textwidth} \includegraphics[width=\textwidth]{content/Images/class_agnostic/01478_small.jpg} \end{subfigure} \quad \vspace{-0.1cm} \caption{Class-agnostic instance masks for moving objects in Multitask Model.} \label{fig:qualitativeEval_MTL} \end{figure*} Table \ref{tab:quantitative_MTL} illustrates our results for the multi-task semantic and class agnostic instance segmentation. We compare against the baseline models trained only for one task either semantic or class agnostic instance segmentation on InstanceMotSeg. Generally the multitask model performs on par with the class agnostic single task baseline, but with the added benefit of jointly predicting both semantic and class agnostic masks. Although we notice a degradation in the semantic instance segmentation performance from the baseline model to the multitask model due to much smaller size of instance segmentation dataset, we think this can be remedied by learning a re-weighting for the losses or by training the class agnostic head while freezing the weights for the rest of the model. Nonetheless the scope of the current work is to show the efficiency of sharing protonet among these two tasks where our multi-task model runs at 34 fps while the class agnostic baseline runs at 39 fps. Thus without large degradation in computational performance we are able to predict both semantic and class agnostic segmentation. We further validate and analyse the shared protonet in the following section. In order to assess the power of class agnostic segmentation on more general moving objects that are outside the labels within InstanceMotSeg we report results on alternate training the model between DAVIS'17 and InstanceMotSeg in Table~\ref{tab:quantitative_MTL_DAVIS}. Figure~\ref{fig:qualitativeEval_MTL} further shows the multi-task model inferring semantic labels on KITTI, while still being able to segment unknown moving objects that exist in DAVIS dataset. The multi-task model has the advantage of sharing the encoder for both the tasks and reduces computational cost drastically as encoder is the most intensive part. Finally, we evaluate our model on an unseen YouTube video with a running moose. The moose was detected using the class agnostic segmentation as shown in the qualitative results video. \begin{figure*}[t!] \label{fig:qualitativeEval} \centering \begin{subfigure}{.3\textwidth} \includegraphics[width=\textwidth]{content/Images/protos/mot_coeffs.png} \caption{\textcolor{white}{(a)}} \end{subfigure}% \begin{subfigure}{.3\textwidth} \includegraphics[width=\textwidth]{content/Images/protos/semantic_coeffs.png} \caption{\textcolor{white}{(b)}} \end{subfigure}% \begin{subfigure}{.3\textwidth} \includegraphics[width=0.85\textwidth]{content/Images/protos/protos.png} \caption{\textcolor{white}{(c)}} \end{subfigure} \begin{subfigure}{.498\textwidth} \includegraphics[width=\textwidth]{content/Images/protos/motion.png} \caption{\textcolor{white}{(d)}} \end{subfigure}% \begin{subfigure}{.498\textwidth} \includegraphics[width=\textwidth]{content/Images/protos/semantic.png} \caption{\textcolor{white}{(e)}} \end{subfigure} \caption{Prototypes and Coefficients Analysis. (a, b) 6 $\times$ 5 Motion and Semantic coefficients in a grid, notice that coefficients can be positive or negative. (c) 6 $\times$ 5 Prototypes grid corresponding to coefficients of 32 basis prototypes. (d, e) motion and semantic instance segmentation masks. As described in Section \ref{sec:protos_analysis}, coefficients of motion and semantic show how the model learns to linearly combine between different prototypes which are shared among the two tasks to finally get both motion and semantic instance predictions.} \label{fig:protos} \end{figure*} \subsection{Prototype and Coefficients Analysis} \label{sec:protos_analysis} In order to better understand the model output, we perform an analysis on the common prototypes and coefficients learned for both motion and semantic instance segmentation. Figure~\ref{fig:protos} shows the output for the basis learned with a total of 32 prototypes in (c) for two different frames. The output basis are organized in a 6 $\times$ 5 grid which correspond to the 6 $\times$ 5 grid for the coefficients. We denote the different grid cells using $c^s_{i,j}$, $c^m_{i,j}$ and $p_{i,j}$ for semantic coefficients, motion coefficients and prototypes respectively. Here $i$ indicates row index starting from top to bottom and $j$ indicates column index starting from left to right. Both semantic and motion coefficients are shown in (a, b), where they can be negative or positive which can help to mask or add certain objects to the final mask. The predicted final semantic and motion instance masks for the corresponding two frames are shown last row in (d, e) which are constructed as a linear combination using these basis and coefficients. The output shows meaningful learned basis that can help in constructing the final masks. Interestingly, the comparison between motion and semantic coefficients can explain what the model is learning. In Figure~\ref{fig:protos}, we aim to visualize the prototypes and the coefficients to interpret our model. Images with semantic and motion instance segmentation are shown along with the generated prototypes and the corresponding weighting coefficients. $p_{4,6}$ (row 4, col 6) shows a single prototype where all the vehicles are highlighted including the static car on the right side and the moving cars in the background. The activation in the corresponding semantic coefficient is high (yellow) as all the vehicles are highlighted. It is also high in case of the motion coefficients as most of these vehicles are moving. On the other hand, $p_{5,4}$ shows only the static vehicle. Thus, there is a high activation in the semantic coefficients and a low activation in the motion coefficients as the vehicle is static. If we take these two prototypes and combine them linearly using the motion coefficients, the static car will be suppressed in the motion output, but it will remain in the semantic output using the semantic coefficients. Thus it appears that the shared prototypes is sufficient to jointly handle the two tasks. Another interesting observation is that some of the prototypes are not significantly useful in highlighting an object. This indicates that we can use lesser number of prototypes to further improve the efficiency. YOLACT~\cite{bolya2019yolact} proposed the use of 32 prototypes for handling 80 classes setting in MS-COCO. Our problem setting is much simpler with 8 classes for semantic instance segmentation. \subsection{KITTI InstanceMotSeg Dataset} \label{sec:instmoseg} Table~\ref{table:datasets_motion} shows a comparison of the different datasets with respect to our KITTI InstanceMotSeg dataset. The main motivation of this dataset to create instance level motion segmentation annotations for multiple classes. None of the other motion segmentation datasets in the table provide instance level labels. However, it is easy to obtain for Cityscapes-Motion \cite{Valada_2017_IROS} using instance segmentation annotation provided in Cityscapes\cite{Cordts2016cityscapes}. Compared to Cityscapes-Motion, our dataset provides nearly 4x more samples and 5 classes instead of one. The other KITTI motion segmentation datasets namely KITTI-SceneFlow~\cite{menze2015object}, KITTI-Motion~\cite{Valada_2017_IROS} and KITTI-MoSeg~\cite{siam2018modnet} do not provide instance labels and have far lesser samples. In our previous work, we created KITTI-MoSeg Extended~\cite{Rashed_2019_ICCV_Workshops} which had a significantly higher number of 12.9k samples. It made use of a semi-automated approach to obtain motion segmentation labels via finding difference in ego-motion and the motion of other objects in Velodyne coordinate system. This method produced erroneous annotations when the camera undergoes rotation due to the car turning. In this work, we modified the annotation tool to estimate motion in 3D world coordinate system instead of the Velodyne coordinate system which significantly improved the accuracy of annotations. We also extend the dataset with instance segmentation masks for 5 classes including car, pedestrian, bicycle, truck, van instead of the original annotations only for car class. Addition of more classes provides larger variability in appearance and thus improves the appearance agnostic detection of motion segmentation. Our dataset comprises of 12.9k frames and we divide it to 80-20\% ratio for training and testing. Table \ref{tab:dataset_stats} demonstrates the class distribution in our dataset for both moving and static states. \subsection{Instance-Level Class Agnostic Segmentation} Our baseline model from YOLACT~\cite{bolya2019yolact} has a feature extractor network, a feature pyramid network~\cite{lin2017feature} and a protonet module that learns to generate prototypes. We experiment with different feature extractor networks as shown in section~\ref{sec:exps}. In parallel to protonet, a prediction head is learned that outputs bounding boxes, classes and coefficients that are linearly combined with the prototypes to predict the instance masks. We train this model for the class agnostic (motion) instance segmentation task to serve as a baseline for comparative purposes. The model is originally trained for semantic instance segmentation discarding the images with no mask annotations. On the other hand, in InstanceMotSeg dataset we use, there is a significant portion of frames that do not have moving objects. Utilization of such frames will provide a lot of negative samples of static cars which will help the model understand the appearance of static vehicles as well and thus reduce overfitting. In order to solve this problem, the loss function has been updated to reduce the confidence score of the predicted object in case of a false positive. The mask segmentation loss is formulated as binary cross entropy, while the bounding box regression uses a smooth L1 loss similar to SSD~\cite{liu2016ssd}. We refer to this baseline model \textit{RGB-Only} since the input modality is only appearance information. \begin{figure*}[t] \centering \includegraphics[width=.9\textwidth]{content/Images/InstanceMODNet_arch.pdf} \caption{Proposed multi-task network architecture. RGB and optical flow are fed as inputs to the network. Mask coefficients are learnt for two tasks separately using two prediction heads, namely semantic instance segmentation and motion instance segmentation. The coefficients of both prediction heads are combined with the prototypes generating semantic and motion instance masks. Our model has a real-time performance of 39 fps using MobileNet-V2 encoder. } \label{fig:networkarch} \vspace{-0.4cm} \end{figure*} We feed the model with motion information using two approaches and we provide a comparative study for their impact on motion instance segmentation. (1) Implicit method in which the network accepts a stack of images (t, t+1) and learns to model the motion implicitly as referred to by~\cite{ramzy2019rst}. (2) Explicit method where we use optical flow map highlighting pixels motion. In this approach, we make use of FlowNet 2.0~\cite{Ilg2016FlowNet2E} model to compute optical flow. Our main objective is to predict instance masks for moving objects. Hence, a motion representation, in our case optical flow, should be fed into the network in addition to appearance. As motion cues are important in automated driving, the standard automotive embedded platforms including Nvidia Xavier, TI TDA4x and Renesas V3H have a hardware accelerator for computing dense optical flow and it can be leveraged without requiring additional processing. Thus our runtime computation does not include optical flow processing step. Feature fusion method is adopted in our experiments in which we construct two separate feature extractors to process appearance and motion separately. The fusion is performed on the feature level which has provided significant improvement in~\cite{rashed2019motion, 8917447, Rashed_2019_ICCV_Workshops}. We refer to this feature-fusion model as \textit{RGB+OF}. The same architecture has been used to evaluate the impact of implicit motion modelling in which two sequential RGB images \textit{(t, t+1)} are input to the two-stream feature extractor. This model is referred to as \textit{RGB+RGB}. \subsection{Multi-task Learning of Semantics and Class Agnostic Instances} We further propose the joint model to learn semantic and class agnostic instance segmentation. The motivation is to provide a more generic representation for the surrounding environment including both static and moving instances while both tasks are learnt jointly. Separate prediction heads $D_s$ and $D_m$ are used for semantic and motion instance segmentation tasks respectively as shown in Figure~\ref{fig:networkarch}. During training, we alternate between $k$ steps for training $D_s$ semantic labels, and $k$ steps for training $D_m$ using InstanceMotSeg motion labels or the generic DAVIS dataset. One other approach to tackle the problem of learning both semantic and motion instance segmentation would be to pose it as a multi-label classification problem. However, to allow for the flexibility for training the model from different datasets that do not necessarily have the joint annotations and to allow for training motion instance segmentation as a class agnostic segmentation we follow our proposed approach. The separate motion instance segmentation head would be responsible for segmenting generally moving objects even if they are unknown for the semantic head. The feature extraction network, feature pyramid network and protonet are shared among the two tasks to ensure computational efficiency of our proposed multi-task learning system. Thus the learned prototypes are the same for both tasks but the learned coefficients to construct masks and the learned box regression are different. For improving the functional safety of the system, the two outputs are independent and will be fused at the end in a sensor fusion module. For standard objects like vehicles, there will be two independent sources of detection based on motion and appearance. For objects unseen during training or not labelled explicitly, class agnostic motion instance segmentation will be used to detect. \subsection{Motion Segmentation} Motion analysis approaches can be roughly categorized into geometry, tracking or learning based methods. Geometry based approaches are typically pixel-based constrained with some global regularization and they typically do not exploit global context. It has been extensively studied in ~\cite{torr1998geometric,kundu2009moving,menze2015object,scott2017motion,bideau2016s}. Scott et. al.~\cite{scott2017motion} relied on a homography based method but it is simplistic for handling complex motion in automotive scenes. Bideau et. al.~\cite{bideau2016s} utilized optical flow and relied on perspective geometry and feature matching to perform motion segmentation. Tracking based methods~\cite{lin2014deep,brox2010object,ochs2011object} rely on computing object trajectories and can perform clustering to perform the final motion segmentation. These methods are computationally expensive. Most of the current progress is focused on learning based methods~\cite{tokmakov2016learning,tokmakov2017learning,Valada_2017_IROS,siam2018rtseg}. Tokmakov et al. initially explored optical flow based single stream fully convolutional network \cite{tokmakov2016learning} and then extended it to use both motion and appearance by learning a bidirectional recurrent model with memory~\cite{tokmakov2017learning}. Vertens et. al.~\cite{Valada_2017_IROS} proposed a method based on FlowNet~\cite{dosovitskiy2015flownet,Ilg2016FlowNet2E} to jointly learn semantic segmentation and motion segmentation. The model was trained on their dataset CityMotion based on Cityscapes~\cite{Cordts2016cityscapes}. Concurrently Siam et. al.~\cite{siam2018modnet} proposed a motion and appearance based multitask learning framework called MODNet to perform object detection and motion segmentation. MODNet was trained on KITTIMoseg that they released based on KITTI dataset~\cite{Geiger2013IJRR}. It was further extended using ShuffleNet encoder for computational efficiency~\cite{siam2018rtseg}. Rashed et. al. released a larger scale KITTIMoseg and experimented on using LIDAR flow as another mean to improve motion segmentation~\cite{Rashed_2019_ICCV_Workshops}. A similar approach to~\cite{siam2018modnet,rashed2019motion} that can generate motion segmentation weakly supervised annotations was used on WoodScape fisheye dataset~\cite{yogamani2019woodscape}. \textbf{Instance Motion Segmentation:} Segmentation of Independently Moving Objects is a well studied problem in classical computer vision literature \cite{bideau2020motion}. However, it has been relatively less explored in the area of autonomous driving due to lack of large datasets. In a rare attempt in \cite{cao2019learning}, instance motion segmentation was explored for stereo cameras. They reported that there was no prior work in this area. The results were reported on a small KITTI Sceneflow dataset containing 200 test images. Thus we were motivated to create a large scale dataset for instance level motion segmentation and implement a new baseline for monocular setting which is more challenging. \begin{table*}[!t] \caption{Comparison of different datasets for motion segmentation. } \label{table:datasets_motion} \centering \begin{tabular}{|l|l|l|l|l|} \hline Datasets & \# Frames & \# Sequences & \# Object Categories & Instance Labels \\ \hline Cityscapes-Motion~\cite{Valada_2017_IROS} & 3475 & - & 1 (Car Only) & \xmark \\ \hline KITTI-SceneFlow~\cite{menze2015object} & 400 & - & 1 (Car Only) & \xmark \\ \hline KITTI-Motion~\cite{Valada_2017_IROS} & 455 & - & 1 (Car Only) & \xmark \\ \hline KITTI-MoSeg~\cite{siam2018modnet} & 1300 & $\sim$ 5 & 1 (Car Only) & \xmark \\ \hline KITTI-MoSeg Extended~\cite{Rashed_2019_ICCV_Workshops} & 12919 & $\sim$ 38 & 1 (Car Only) & \xmark \\ \hline KITTI-InstanceMotSeg (Ours) & 12919 & $\sim$ 38 & 5 & \cmark \\ \hline \end{tabular} \end{table*} \begin{table}[] \caption{ Class distribution of moving and static objects in our dataset. } \label{tab:dataset_stats} \centering \resizebox{0.45\textwidth}{!}{ \begin{tabular}{|l|l|c|c|c|c|c|} \hline Type/Class & Car & Truck & Van & Pedestrian & Cyclist \\ \hline Static & 29656 & 542 & 3388 & 927 & 243 \\ Moving & 8788 & 1117 & 1382 & 1358 & 1292\\ Total & 38444 & 1659 & 5220 & 2285 & 1535\\ \hline \end{tabular} } \end{table} \subsection{Video Object Segmentation (VOS)} A related task which has been extensively studied in the literature on the DAVIS benchmark~\cite{Perazzi2016} is Video object segmentation. It can be categorized into semi-supervised and unsupervised approaches. Semi-supervised methods utilize a mask initialization to track the objects of interest through the video sequence~\cite{voigtlaender2017online,khoreva2016learning}. Unsupervised approaches do not require any initialization mask and they segment the primary object in the sequence based on appearance and motion saliency~\cite{kohprimary,tokmakov2017learning,jain2017fusionseg}. Most of the initial work in video object segmentation did not predict at instance level. The first attempts to perform instance level video object segmentation was proposed by Hu et. al.~\cite{hu2017maskrnn} relying on recurrent neural networks. VOS setting is based on one large moving object in a scene which is the most salient. Relatively, automotive scenes are much more complex with multiple moving objects. The focus of this work is on automotive scenes. However, we use DAVIS'17 training data in some experiments to train our class agnostic head which provides higher variability in the classes presented in the dataset. \section{INTRODUCTION} \label{sec:introduction} \input{content/intro} \section{Related Work} \label{sec:related} \input{content/related} \section{Proposed Method} \label{sec:method} \input{content/method} \section{Experimental Results} \input{content/exps} \section{Conclusions} \input{content/conc} \section*{ACKNOWLEDGEMENTS} We would like to thank B Ravi Kiran (Navya), Letizia Mariotti and Lucie Yahiaoui for reviewing the paper and providing feedback. \bibliographystyle{IEEEtran}
{'timestamp': '2021-05-27T02:24:30', 'yymm': '2008', 'arxiv_id': '2008.07008', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07008'}
arxiv
\section{Credits} \section{Introduction} We live in a world saturated with media. Any major public issue, such as the ongoing COVID-19 pandemic and the Black Lives Matter protests, attracts tremendous attention from hundreds of thousands of news media outlets — traditional and emerging - around the world. The reporting angles on a single issue are often varied across different media outlets. In covering COVID-19, for example, some media outlets focus on government response and actions while others emphasize the economic consequences. Social science scholars call this process \emph{media framing}. To define, or to \emph{frame}, is ``to select some aspects of a perceived reality and make them more salient in a communicating text'' \cite{entman1993framing}. When used in news articles, frames can strongly impact public perception of the topics reported and lead to different assessments by readers \cite{hamborg2020media}, or even reinforce stereotypes and project explicit and implicit social and racial biases \cite{drakulich2015explicit,sap2019social}. Frame discovery in media text has been traditionally accomplished using methods such as quantitative content analysis \cite{krippendorff2018content}. However, in the emerging media environment, the sheer volume and velocity with which content is generated makes manual labeling increasingly intractable. To overcome this ``big data'' challenge, researchers have employed computational methods based on both unsupervised and supervised machine learning (ML) techniques. This has enabled users to detect frames automatically and robustly \cite{akyurek-etal-2020-multi,liu2019detecting,tsur-etal-2015-frame}. However, these state-of-the-art computational tools are not readily accessible to social sciences scholars who typically do not have machine learning training. This hampers their ability to glean valuable insights from unprecedentedly large media datasets. Our goal is to make computational framing analysis accessible to researchers from a diverse array of disciplines. We present \href{http://www.openframing.org}{OpenFraming}, a user-friendly and interactive Web-based system that allows researchers to conduct computational framing analysis without having to write and debug complex code. There does, of course, exist click-and-run commercial software, but these tools often pose issues for researchers by their lack of transparency into their inner computational mechanisms. In contrast, our system is based on state-of-the-art research and our code is publicly available. While the focus of the project is on news media framing, the proposed system can also be used to implement other tasks such as sentiment detection or process other data types like social media data. Specifically, \href{http://www.openframing.org}{OpenFraming} can perform two types of computational framing analysis: 1) unsupervised topic modeling based on Latent Dirichlet Allocation (LDA; \citet{blei2003latent}), and 2) supervised learning using deep neural network Bidirectional Encoder Representations from Transformers (BERT; \citet{devlin2018bert}). Both approaches have been applied to media framing in communication research and are proven to be efficient and valid \cite{guo2016big,liu2019detecting}. When encountering a large set of unknown media data, researchers can employ the LDA-based approach to make sense of the data inductively \cite{guo2016big}. Using the LDA output, researchers can find the main threads of discourse in a corpus by examining the LDA ``topics'' associated with keywords that are most indicative of that particular thread of discourse. Ultimately, the ``topics'' can prove useful for frame discovery. However, the LDA output may not produce a useful framing model on its own. Because the method is unsupervised, the ``topics'' it creates may overlap with each other; appear to be irrelevant to the phenomenon being studied; or seem so ill-defined to the trained researcher that the results would not contribute to the framing literature. Therefore, our system also provides an alternative approach that allows domain experts (i.e., the users) to intervene in building the framing model. In this setting, the user can first employ the LDA-based approach to discover potential frames in the corpus. Then, using their domain-specific knowledge, they can manually label and upload a dataset to the system with frames suggested by the LDA model or uncovered from other explorations, whether machine-guided or not. We employ a BERT-based classification model to create a state-of-the-art frame classifier. Researchers can upload unlabeled documents to \href{http://www.openframing.org}{OpenFraming} and use the trained classifier to extract the frames. To summarize, our system \href{http://www.openframing.org}{OpenFraming} has the following advantages: (1) It can process textual media data and detect frames automatically (2) It is accessible to researchers without computational backgrounds (3) It produces valid media frames based on peer-reviewed, state-of-the-art computational models (4) It provides many options for users to perform unsupervised ML, supervised ML, or both. In the supervised setting, the model trained on user-provided labeled data can be used to label a much larger dataset than would be feasible for human workers. \section{Related Work} A typical task in the field of communication research is the identification of topics, attributes, and frames in document collections to understand, for example, news media messages, elite discourse, and public opinion. Traditionally, scholars rely on content analysis approaches, both qualitative and quantitative, to manually annotate the data \cite{krippendorff2018content,lindlof2017qualitative}. In recent years, a group of communication researchers has taken advantage of advances in computational sciences and applied both unsupervised and supervised ML, to analyze large-scale communication text. In light of the growing importance of media and communication in our lives concerning agenda setting, framing, and biases, more and more computer scientists also joined this line of research and consider media framing to be a domain to apply their algorithms \cite{tsur-etal-2015-frame,field2018framing,liu2019detecting,akyurek-etal-2020-multi,hamborg2020media,sap2019social}. Within the world of unsupervised ML for text analysis, LDA-based topic modeling is one of the most widely used approaches in communication research (see \citet{maier2018applying} for a systematic review). The LDA algorithm generates a set number of ``topics'' associated with a list of terms. Researchers then review the terms and decide the label for each topic. Consider the news coverage of COVID-19 as an example. An LDA topic may include the terms \textit{pandemic}, \textit{job}, \textit{million}, \textit{economy}, and \textit{unemployment}, which can be labeled as the topic ``economic consequences''. Another topic may include the terms \textit{season}, \textit{player}, \textit{sport}, \textit{game}, and \textit{return}, and can be labeled as ``the impact on the sports industry''. \citet{guo2016big} made the first attempt to assess the efficacy and validity of the LDA-based approach in the context of journalism and mass communication research; furthermore, they prove that it is useful and efficient to obtain initial ideas about the data. Since a frame, explicitly defined, is ``a central organizing idea for news content that supplies a context and suggests what the issue is through the use of selection, emphasis, exclusion, and elaboration'' \cite{reese2001framing}, LDA-generated topics related to frames may elide the abstraction and nuance that the frames themselves contain. Framing scholars have identified a list of \textit{generic} and \textit{issue-specific} frames and argued that framing analysis should be built on the existing work to make a meaningful contribution to the literature \cite{guo2012transnational,nisbet2010knowledge,semetko2000framing}. This suggests that not all LDA-generated topics can be productively considered as frames. Using the running example of the COVID-19 coverage, while the LDA topic ``economic consequences'' corresponds to one of the generic frames identified earlier, it is debatable whether the topic discussing the impact on the sports industry can be interpreted as a frame. The LDA-based approach has other imperfections as well: it may generate meaningless ``topics'' or produce ``topics'' that contain unrelated or even conflicting information. Given this, the LDA approach is most useful for exploratory analysis. Although the LDA-generated topics are not necessarily equivalent to frames, the information can be used to infer potential frames for the next step of supervised frame analysis. Unlike unsupervised ML, the supervised approach is a deductive research method and is used to identify pre-determined frames based on the literature. In communication research, scholars have used supervised ML algorithms such as support vector machines and deep learning models to identify frames in a media text. Two recent studies used BERT to identify frames in the news coverage of gun violence in the US; the studies both demonstrate a high level of accuracy \cite{akyurek-etal-2020-multi,liu2019detecting}. The implementation of both unsupervised ML and supervised ML discussed above requires a computational background. Some social science scholars explore the methods themselves, and others choose to collaborate with colleagues in computer science. However, due to a lack of formal computer science training, it is often difficult for social science scholars to apply the computational models appropriately on their own. Also, not all scholars have the opportunities and resources for cross-disciplinary collaboration. Commercial software programs exist for this type of analysis, but most are costly and the algorithms they provide remain a black box. To overcome these challenges, we present \href{http://www.openframing.org}{OpenFraming}, a free and open-sourced Web-based system specialized in computational framing analysis. \section{System Architecture} While we make a Web server that runs \href{http://www.openframing.org}{OpenFraming} publicly available, running one's copy of the system is also streamlined. This is possible through our release of a Docker container that orchestrates the various technologies used by our system. Concretely, this means that anyone ranging from the user who would like to have their own version of the system on their personal computers, to bigger organizations who would like to host and extend the system on more capable hardware, can get it up and running in minutes. The publicly available server, for example, was set up on an EC2 instance on Amazon Web Services (AWS) with minimal additional configuration. The software that makes up the system includes Gensim's \cite{gensim2010} Python interface to Mallet \cite{mallet2002} for LDA topic modeling; the transformers library for supervised classification \cite{wolf2019transformers}, Redis for queuing the jobs, SQLite for a database solution, Flask for the Web application backend, and jQuery and Bootstrap for the frontend. \paragraph{Data Cleaning and Pre-processing for LDA} While there is some flexibility regarding the format of the dataset (the system currently supports .xls, .xlsx, and .csv), it is nonetheless necessary that it at least contain a column labeled as ``Example''. This column will hold the text examples, with one document or, broadly speaking, textual entity, per row. LDA employs a bag-of-words model, where each document is understood as an unordered collection of words; to make the analysis more conducive to the discovery of useful topics, the system filters out extremely common and extremely rare words. The pre-processing steps we employ include the following: \begin{itemize} \item \textbf{Removing punctuation and digits.} this is a standard step in natural language processing (NLP) applications. \item \textbf{Removing stopwords}: stopwords are extremely common words, usually filtered out by default in NLP applications. \item \textbf{Lemmatizing content}: this groups together different inflected forms of a word into a single entity. \item \textbf{Setting minimum word length}: the system removes words shorter than 2 characters. \end{itemize} \begin{figure}[ht!] \includegraphics[width=8cm]{lda_process.png} \caption{LDA pipeline for topic Discovery} \label{lda_pipeline} \end{figure} \paragraph{LDA for topic discovery} The system runs LDA using the Mallet\cite{mallet2002} implementation and its preset parameter tuning. The random seed is set deterministically so that subsequent runs of the algorithm will yield the same results. LDA models each document as a probabilistic mixture of topics. A topic is defined as a probability distribution over keywords. LDA iteratively updates the topic-keyword distributions to maximize the log-likelihood of the entire corpus. The system uses LDA to create a matrix mapping documents to weight vectors which quantify the contribution (weight) of each topic to the document; we can think of the weight vector as a probability distribution over topics for a particular document. Our system also produces a list of the most relevant keywords for each topic; the user can specify how many keywords they would like to be given before runtime. Because running LDA over a large corpus can be time-consuming, the user's part in monitoring the modeling finishes when they hit the ``submit'' button. The system then sends them an e-mail with a link to download the results of the analysis when it is ready. We also provide topic quality metrics, namely coherence, and perplexity, to aid researchers in refining the number of topics they choose to use to further analysis. Figure~\ref{lda_pipeline} provides a more detailed explanation of the LDA pipeline. \paragraph{Labeling Procedure For LDA Results} When the LDA algorithm has completed, the user will receive its output, which contains a set of ``topics'', each of which is associated with a list of keywords. Communications researchers recommend that at least two researchers manually review the keywords and decide on a label for each topic. Ideally, for framing analysis, each label should correspond to one of the frames — generic or issue-specific — identified in the relevant literature. New labels may be created to signify topics or frames related to the specific issue. Given the limitations of the LDA approach, it is also possible that some ``topics'' may not be meaningful. \begin{figure*}[ht!] \includegraphics[width=15cm]{bert.png} \caption{BERT training/fine-tuning pipeline.} \label{bert_pipeline} \end{figure*} \paragraph{Text classification using BERT} BERT's masked language model \cite{devlin2018bert}, which builds on a deep Transformer's encoder architecture that relies on multi-layer self-attention to compute contextual representations of its input \cite{vaswani2017attention}, has shown impressive performance across a wide range of tasks, including framing analysis \cite{liu2019detecting}, when fine-tuned on labeled data for the task. However, there remains a significant access barrier for those with a non-computational background to truly make use of BERT's wide-ranging applicability. To our knowledge, all publicly available Web services and software packages that make use of BERT either constrain the end-user to one specific fine-tuned model (for example, fine-tuned on a specific sentiment analysis dataset), or, they require their users to be prepared to write code to fine-tune and further predict on a custom dataset. \href{http://www.openframing.org}{OpenFraming} makes it possible for those without a computational background to take advantage of BERT's impressive fine-tuned performance on a custom dataset of their own. When the user uploads \textit{labeled} data for training and testing or \textit{unlabeled} data for inference, our system either fine-tunes a new BERT model or uses our existing fine-tuned BERT for classifying the frame labels in the data. For fine-tuning, our system uses the standard configuration of BERT's internal architecture, and uses one set of training parameters recommended for BERT: a learning rate of 5e-5, 3 epochs of fine-tuning training, and a batch size of 8. Once training or inference are completed, the user receives an e-mail with a download link to the frame prediction results on their data. In the case of fine-tuning a new BERT model on user-provided labeled data, we also provide accuracy on user-provided test data and the newly fine-tuned BERT model that the user can download. Figure~\ref{bert_pipeline} provides a more detailed description of the BERT training pipeline. \paragraph{Labeling Procedure for Training a New BERT Model} With the feature ``Training BERT – Do-it-yourself method,'' users can train a new BERT classification model using their own labeled data. In social science research, quantitative content analysis is one of the most widely used methods for labeling visual and textual content \cite{kripendorff2004content, riffe2019analyzing}. The approach involves drawing a representative sample of data; training two or more human coders on a labeling protocol to identify patterns in content, and measuring intercoder reliability between their coding results. Once the coders reach a certain degree of intercoder reliability, they can start labeling the remaining data independently. Communications researchers have recently suggested that crowdsourcing, if appropriately implemented, can be a valid alternative to annotating media messages \cite{guo2019accurate,lind2017content}. The labeled data can then be uploaded to our system to train a new BERT model. \paragraph{Available Pre-Trained BERT Models for Frame Classification} For the feature ``Using BERT – off-the-shelf classifier,'' users can use models that we have fine-tuned on benchmark frame datasets to classify their unlabeled data. We make available models that can label frames on issues that include (1) immigration, (2) tobacco-use, (3) same-sex marriage (fine-tuned on Media Frame Corpus dataset \cite{card2015media}), (4) US Gun Violence issue (fine-tuned on Gun Violence Frame Corpus \cite{liu2019detecting}), or (5) COVID-19. To validate the performance of our fine-tuned model and the quality of its predictions, users can label a sample of their documents using the aforementioned approaches — quantitative content analysis and crowdsourcing — and compare the manual and machine-generated labels. \section{User Interface and Site Design} Our demo Website includes framing analysis as well as LDA topic discovery utilities. Additionally, our landing page provides an introduction to the user explaining what various building blocks of our Website are (Figure~\ref{landing_page}) \begin{figure}[ht!] \includegraphics[width=\linewidth]{landingpage.png} \caption{The landing page of \href{http://www.openframing.org}{openframing.org}} \label{landing_page} \end{figure} \begin{figure}[ht!] \includegraphics[width=\linewidth]{framing.png} \caption{Framing analysis Web page} \label{Figure2} \end{figure} Our framing analysis page (Figure~\ref{Figure2}) is created to accommodate two use cases. Either the user inputs a file for framing classification and chooses one of the policy issues for which we already have pre-trained models (e.g. \textit{Immigration}), or picks one of the policy issues of their choosing (e.g. \textit{Labor Market Inequality}). If the user chooses their own policy issue for which we don't have a pre-trained model, they are required to also upload a sizable dataset labeled with frames (containing approximately 100 documents for each frame) so that the system can train a new BERT-based framing classifier for the issue in the backend. Once the backend has completed running inference on the pre-defined and pre-trained policy issues or completed the training and inference on user-defined policy issue, the results will be shown dynamically on the same page (Figure~\ref{framing_UI}). The user can then scroll through the predicted results and download the results to their local machines. \begin{figure}[ht!] \includegraphics[width=\linewidth]{framing_results.png} \caption{A snapshot of framing classification results} \label{framing_UI} \end{figure} Here, we illustrate the topic discovery functionality of \href{http://www.openframing.org}{OpenFraming} (Figure~\ref{LDA_UI}) using a sample from the Kaggle `A Million News Headline' dataset\footnote{\href{https://www.kaggle.com/therohk/million-headlines}{https://www.kaggle.com/therohk/million-headlines}}. Once topics are discovered, we send the topics and their keywords as well as the document topic probabilities to user's provided e-mail (Figure~\ref{LDA_results_email} and Figure~\ref{LDA_results}). We have also created a screencast video demonstrating the use of the system, which can be accessed at \url{https://www.youtube.com/watch?v=u8SJAZ-EbgU}. \begin{figure}[ht!] \includegraphics[width=\linewidth]{LDA.png} \caption{LDA topic discovery page} \label{LDA_UI} \end{figure} \begin{figure}[ht!] \includegraphics[width=\linewidth]{LDA_results_download.png} \caption{LDA results are ready and e-mailed to the user.} \label{LDA_results_email} \end{figure} \begin{figure}[ht!] \includegraphics[width=\linewidth]{snapshot_of_LDA_results.png} \caption{A snapshot of one of the topics discovered by LDA on `A Million News Headline' dataset, the keywords for the topic, and the headlines labeled with the topic. } \label{LDA_results} \end{figure} \section{Conclusion and Future Work} We have introduced OpenFraming, a Web-based system for analyzing and classifying frames in the text documents. OpenFraming is designed to lower the barriers to applying machine learning for frame analysis, including giving researchers the capability to build models using their own labeled data. Its architecture is designed to be user-friendly and easily navigable, empowering researchers to comfortably make sense of their text corpora without specific machine learning knowledge. In future work, we hope to incorporate semi-supervised machine learning methods to allow researchers to iterate quickly on models; if a researcher submits a dataset with a relatively small number of labels, for example, the system will eventually be able to generate labels for the much larger unlabeled dataset, creating a synthetic training set for the BERT supervised model to train on. \bibliographystyle{acl_natbib}
{'timestamp': '2020-08-18T02:19:46', 'yymm': '2008', 'arxiv_id': '2008.06974', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06974'}
arxiv
\section*{Appendix} \chen{Move all these results to our website, as this makes the paper too long.} \label{sec:appendix} \begin{table*}[htb] \caption{Tag classification accuracy for five categories in different methods(70$\%$ training, 15$\%$ validation, 15$\%$ testing).} \label{tab:Result_715} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.6848 &{0.6182} & 0.6303 & 0.7879 & 0.8061 & \textbf{0.8303}\\ food\&drink&{0.6181}&{0.5866} &0.6969 & {0.7480} & \textbf{0.7638} & 0.7559\\ ecommerce & 0.5672 &{0.5457} & 0.6452& {0.7312} & 0.8118 & \textbf{0.8199}\\ finance&{0.6255}&{0.5618} &0.5976& {0.7171} & \textbf{0.8486}&0.7928\\ travel&{0.5825}&{0.5789} &0.5754& {0.6632} & 0.7474 &\textbf{0.7895}\\ game&{0.5521}&{0.5625} &0.6979& {0.7500} & 0.7552 &\textbf{0.7917}\\ weather&{0.6571}&{0.5286} &0.7000& {0.7571} & \textbf{0.8143} &0.7714\\ sport&{0.5549}&{0.5915} &0.5976& {0.6463} & 0.7500 & \textbf{0.7744}\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5613}&0.5097 & 0.7742 & \textbf{0.8258}&0.6839 & 0.7806 \\ red&{0.5780}&{0.5046} & 0.7706 & \textbf{0.8257}& 0.5963 &0.8073\\ pink&{0.6232}&{0.5652} & \textbf{0.8261} & {0.7536} & 0.5797 &0.7971\\ blue&{0.5302}&{0.5772} & \textbf{0.7651} & {0.6779}& 0.6644 & 0.7383\\ green&{0.5189}& 0.5283 & \textbf{0.8679} & {0.7830} & 0.6132 & {0.8019} \\ white&{0.6370}&{0.5481} & 0.7111 & \textbf{0.7704}& 0.6519 & \textbf{0.7704} \\ black&{0.6450}&{0.5500} & 0.7850 & \textbf{0.8350} & 0.6050 & 0.8250\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.5840}&{0.5920} &{0.6704}&{0.7168}& 0.8144 & \textbf{0.8368}\\ signup&{0.6006}&0.5820&{0.6161}&{0.6966}& 0.7059 &\textbf{0.7183}\\ checkout&{0.5818}&0.5212&{0.5697}&{0.6364}& \textbf{0.8061} &0.7152\\ profile&{0.5822}&{0.5719} &{0.5925}&{0.6507}&\textbf{0.7089} & 0.6986 \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.7265 & 0.6592 &{0.7309}&0.8655& 0.7803 & \textbf{0.8700}\\ chart&{0.5300}&{0.5200} &{0.5800}&{0.7800}& 0.8300 & \textbf{0.8600}\\ form&{0.6321}&{0.6226} &{0.6132}&{0.6698}& \textbf{0.6887} & 0.6792 \\ list&{0.6462}&{0.5538} &{0.5538}&\textbf{0.7077}& 0.5846 & 0.6923\\ grid&{0.5676}&{0.5766} &{0.6126}&{0.5946}& \textbf{0.7748} & 0.7027\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7719}&{0.7775} & 0.8328 & {0.8003} & 0.9409 & \textbf{0.9481}\\ website&{0.7603}&{0.7596} & 0.8388 & {0.8153} & 0.8894 & \textbf{0.9085}\\ \midrule \textbf{Average} & {0.6123} & {0.5805} & {0.6866} & {0.7387} & 0.7391 & {\textbf{0.7875}}\\ \bottomrule \end{tabular} \end{table*} \begin{table*} \caption{Tag classification accuracy for five categories in different methods(60$\%$ training, 20$\%$ validation, 20$\%$ testing).} \label{tab:Result_622} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.6409 &{0.5364} & 0.6182 & 0.7955 & 0.7864 & \textbf{0.8455}\\ food\&drink&{0.6154}&{0.5178} &0.6864 & {0.7604} & 0.7574& \textbf{0.8225}\\ ecommerce & 0.5755 &{0.5163} &0.6286& {0.7449} & 0.7837 & \textbf{0.8102}\\ finance&{0.5493}&{0.5463} &0.6000& {0.7731} & \textbf{0.8179}&\textbf{0.8179}\\ travel&{0.6069}&{0.5567} &0.5937& {0.7361} & 0.7652 &\textbf{0.8311}\\ game&{0.5882}&{0.5412} &0.6078& {0.7098} & 0.7647 &\textbf{0.7922}\\ weather&{0.6344}&{0.5269} &0.5806& {0.7097} & 0.6882 &\textbf{0.7742}\\ sport&{0.5367}&{0.5688} &0.5550& {0.6147} & \textbf{0.7706} & 0.7477\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5096}&0.5240 & 0.7356 & {0.7404}&0.6538 & \textbf{0.7692} \\ red&{0.5385}&{0.5385} & 0.7902 & \textbf{0.8601}& 0.6084 &\textbf{0.8601}\\ pink&{0.5543}&{0.5435} & \textbf{0.8913} & {0.6848} & 0.7391 &0.7826\\ blue&{0.5450}&{0.5200} & \textbf{0.7750} & {0.7300}& 0.6500 & 0.7700\\ green&{0.5571}& 0.5500 & \textbf{0.8429} & {0.7571} & 0.6000 & {0.7857} \\ white&{0.6056}&{0.5333} & 0.7389 & \textbf{0.8056}& 0.7000 & 0.7944 \\ black&{0.6312}&{0.5361} & 0.8289 & {0.8289} & 0.6236 & \textbf{0.8441}\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.6345}&{0.5826} &{0.6622}&{0.7226}& 0.8082 & \textbf{0.8227}\\ signup&{0.6419}&0.6163&{0.6023}&{0.7047}& 0.7116 &\textbf{0.7512}\\ checkout&{0.5409}&0.5318&{0.5773}&{0.6636}& 0.7273 &\textbf{0.7455}\\ profile&{0.5426}&{0.5530} &{0.5762}&{0.6150}&\textbf{0.6951} & 0.6822 \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.7033 & 0.6333 &{0.7533}&\textbf{0.8467}& 0.7400 &0.8267\\ chart&{0.6439}&{0.4924} &{0.6591}&{0.7652}&\textbf{0.8258} & 0.7424\\ form&{0.6214}&{0.5357} &{0.6214}&{0.6786}& 0.6429 &\textbf{0.7000}\\ list&{0.6364}&{0.5909} &{0.5909}&\textbf{0.7045}& 0.6136 & 0.6591\\ grid&{0.5850}&{0.5374} &{0.5850}&{0.6803}& \textbf{0.7279} & 0.7143\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7757}&{0.7691} & 0.8377 & {0.7993} & \textbf{0.9368} & 0.8236\\ website&{0.7452}&{0.7377} & 0.8117 & {0.8134} & \textbf{0.8824} & 0.8396\\ \midrule \textbf{Average} & {0.6061} & {0.5629} & {0.6827} & {0.7402} & 0.7316 & {\textbf{0.7829}}\\ \bottomrule \end{tabular} \end{table*} \begin{table*} \caption{Tag classification accuracy for five categories in different methods(50$\%$ training, 25$\%$ validation, 25$\%$ testing).} \label{tab:Result_622} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.5782 & 0.5164 & 0.6582 & \textbf{0.7709} & \textbf{0.7709} & {0.7491}\\ food\&drink&{0.6306}&{0.5482} &0.6894 & {0.7624} & 0.7576& \textbf{0.7694}\\ ecommerce & 0.5684 &{0.5342} &0.6596& {0.7182} & 0.8143 & \textbf{0.8306}\\ finance&{0.5971}&{0.5444} &0.6139& {0.6954} & \textbf{0.7986} & 0.7890\\ travel&{0.6118}&{0.5823} &0.6350& {0.7363} & 0.7616 &\textbf{0.8143}\\ game&{0.6176}&{0.6113} &0.7367& {0.7680} & \textbf{0.7806} &0.7712\\ weather&{0.6174}&{0.5478} &0.6174& {0.7217} & \textbf{0.7739} & 0.7304\\ sport&{0.5277}&{0.5129} &0.5646& {0.6162} & 0.7491 & \textbf{0.7823}\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5405}&0.5135 & 0.7104 & {0.7181}&0.6718 & \textbf{0.7259} \\ red&{0.5611}&{0.5167} & 0.7556 & 0.7944& 0.6000 &\textbf{0.8056}\\ pink&{0.6228}&{0.5175} & 0.8246 & {0.7544} & 0.6140 & \textbf{0.8421}\\ blue&{0.5360}&{0.5000} & \textbf{0.7320} & {0.6800}& 0.6400 & 0.7240\\ green&{0.5575}& 0.5230 & {0.7989} & {0.8276} & 0.6667 & \textbf{0.8506} \\ white&{0.5422}&{0.5556} & 0.7556 & {0.7333}& 0.7111 & \textbf{0.8000} \\ black&{0.5964}&{0.4789} & \textbf{0.8554} & {0.8313} & 0.5753 & 0.8464\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.6143}&{0.5757} &{0.6403}&{0.7194}& 0.7772 & \textbf{0.8129}\\ signup&{0.5651}&0.5279&{0.6115}&{0.7138}& 0.7138 &\textbf{0.7491}\\ checkout&{0.5401}&0.5438&{0.5219}&{0.6752}& 0.7117 &\textbf{0.7664}\\ profile&{0.6058}&{0.5477} &{0.5643}&{0.6701}& 0.6618 & \textbf{0.6971} \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.7005 & 0.5963 &{0.7299}&{0.8262}& 0.7326 & \textbf{0.8289}\\ chart&{0.6606}&{0.5152} &{0.6909}&{0.7939}&{0.8182} & \textbf{0.8303}\\ form&{0.6571}&{0.5714} &{0.6000}&{0.7314}& 0.6743 &\textbf{0.7714}\\ list&{0.5545}&{0.5364} &{0.6455}&0.7182& 0.7091 & \textbf{0.7364}\\ grid&{0.5351}&{0.4919} &{0.5676}&{0.6595}& 0.7081 & \textbf{0.7730}\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7581}&{0.7522} & 0.8015 & {0.8036} & 0.9295 & \textbf{0.9426}\\ website&{0.7270}&{0.7201} & 0.8046 & {0.8256} & 0.8745 & \textbf{0.9068} \\ \midrule \textbf{Average} & {0.6009} & {0.5531} & {0.6841} & {0.7410} & 0.7306 & {\textbf{0.7940}}\\ \bottomrule \end{tabular} \end{table*} \section{Augment Tags for the UI Design} \label{sec:tagAugmentation} Although extracting morphological forms mentioned in the last section can boost the performance of UI retrieval by normalizing the existing tags from designers, some UIs are still missing related tags which makes them unsearchable. Therefore, a method to recover the missing tags of existing UIs is necessary. However, based on the labeled data, we could not find a code-based heuristic that distinguishes tags from UI design images with high accuracy: the existing UI designs are too diverse. So, we propose a hybrid deep learning method modelling both the visual and textual information to predict missing tags of the UI design. \subsection{Approach overview} The overview of our approach can be seen in Fig~\ref{fig:CNN_Architecture}. To train the deep learning for tag augmentation, we first collect all existing UI designs with specific tags identified in our empirical study (Section~\ref{sec:trainingData}). We then develop a tag augmentation model by combining a CNN model for capturing visual UI information and a fully-connected neural network for capturing textual information of existing tags (Section~\ref{sec:model}). Additionally, to understand how our ensemble model makes its decisions through the visual and textual information, we apply a visualization technique (Saliency Maps~\cite{simonyan2013deep} and Softmax function~\cite{chen2018data}) for understanding which part of the figure and which words lead to the final prediction (Section~\ref{sec:visualization}). \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/CNN_structure.png} \caption{The architecture of our tag prediction model.} \label{fig:CNN_Architecture} \vspace{-5mm} \end{figure*} \begin{comment} \ruiqi{We have collect approximately 210K images along with their metadata from Dribbble\cite{web:dribble}. Based on the labeled data, we could not find a code-based heuristic that categorizes different UI designs with high accuracy: the tags used to describe UI designs by different labelers are not consistent or complete.} Label incompleteness can severely degrade the performance of the learned multi-label classification models, since it will build negative prediction patterns between the input instances and the missing labels and further propagate the mistakes into the prediction phase on the test data. Not all tag labels are rigidly exclusive, i.e., one UI design can be attached with multiple tags. For example, the UI design in Figure 1 is attached with ``ios app'', ``mobile app'', ``mobile app design'', ``ui'', ``uidesign''. \\ \ruiqi{To assist designers with the UI search, we trained a vision-based, deep learning pipeline that can automatically recommend tags for both newly created and existing UI designs, adapting a convolutional neural network (CNN) architecture to binary UI design classification.} \end{comment} \subsection{Dataset preparing} \label{sec:trainingData} We formulate this tag augmentation task as a classification problem. We leverage the tag categorization during the creation of the UI semantic vocabulary as the label, and corresponding UI design images and attached tags as the training data. Note that each UI design may own many semantic tags such as ``mobile'', ``blue'', ``social'', ``login'' and ``form'', and these tags are not exclusive from each other. Therefore, we cannot regard all tags as equal for training a multi-class classifier for tag prediction. In this work, we train a binary classifier for each tag label. Such binary classifiers also benefit the system extensibility for new tags, as we only need to train a new binary classifier for the new tag without altering existing models for the existing tags. For training each binary classifier, we take the UI design with that tag as the positive data. We randomly take the same amount of UI designs attached with tags which are in the same category of the target tags in Table~\ref{tab:tagCategory} as the negative training data, as tags in the same categories are always exclusive from each other. To keep the balance of data, we make the amount of positive data equal to that of negative data. Therefore, the chance level for accuracy is 50\%. We further preprocess the data in two aspects. For each tag, we merge similar tags based on the morphological/synonym form identification and some minor manual check. For example, the tag ``traveling'', ``travel guide'', ``trip'' are all merged to tag ``travel''. Note that the manual check is only carried out once for grouping similar tags in dataset preparation and no more human efforts are needed in the model construction. For each image, we normalize the pixel value by dividing the mean and standard deviation so that each pixel value is in the range between 0 to 1 for accelerating the training process. \begin{comment} \sidong{The dataset collected ranges from 440 to 18,772 for each category as seen in Fig~\ref{fig:frequency} with the balance of positive data and negative data. We further preprocess the data in two aspects. For each tag, we merge similar tags based on both the morphological form identification to decrease the ambiguity. For example, the tag ``traveling'', ``travel guide'', ``trip'' are all merged to tag ``travel''. For each image, we normalize the pixel value by dividing the mean and standard deviation so that each pixel value is in the range between 0 to 1 for accelerating the training process. Finally, data splitting is an important step whereby data is divided into training, validation and testing subsets to ensure good generalization ability of the model. By investigating the impact of different data splitting ratio in Section~\ref{third:evaluation}, we randomly take 80\% of them as the training data, 10\% as the validation data and 10\% as the testing data.} \end{comment} \begin{comment} \sidong{tags in the same category are not exclusive. For example, red UI can also tag with blue. Maybe rewrite as positive training data from tagged and negative from untagged? please check.} \end{comment} \subsection{Model Architecture} \label{sec:model} In this section, we propose an end-to-end deep fusion model to jointly learn visual and textual information. The architecture of the proposed network is shown in Fig~\ref{fig:CNN_Architecture}, which contains two main components. One CNN model takes the GUI design image as the input for extracting the visual features. The other CNN model takes the existing tags as the input for extracting the textual information. We then merge both information sources to the final fully-connected layers for predicting the tag of the GUI design. \subsubsection{Capturing Visual Information} Convolutional Neural Network (CNN)~\cite{lecun1998gradient, krizhevsky2012imagenet} is a class of deep, feed-forward neural networks, most commonly applied to analyze visual imagery. The architecture of a typical CNN is structured as a series of stages such as different layers called convolution layers, pooling layers, and fully-connected layers. In the convolutional layers, the convolution of an image is to use a kernel (e.g., $3\times3$ matrix) and then slide that window around the image. At each position in the image that the kernel ($K$) visits, we multiply its values element-wise with the original matrix, then sum them up i.e., matrix dot multiply. After the convolutional layers, it is the pooling layer. Max Pooling works very much like convoluting, where we take a kernel and move the kernel over the image with no overlap. It reduces parameter numbers and computation in the network, and hence controls the overfitting. Different from the original CNN model, we adopt a more advanced one, ResNet (Residual Neural Network)~\cite{Resnet} with skip connections among the convolutional layers so that the model can be designed as very deep. But due to the limitation of our dataset and deep structure of the model, we cannot train the ResNet directly with our small-scale dataset. Therefore, we adopt the existing pretrained model which already distills the visual features from the ImageNet~\cite{imagenet}, the largest image dataset including more than 14 million natural images. Based on the pre-trained ResNet, we further use our dataset to fine-tune the ResNet to adjust the parameters in different layers. \begin{comment} Our CNN model comprises 6 convolutional layers, and each one of them is followed by a max pooling layer with a stride and filter size of 2. Then there are three fully connected layers containing 2048, 1024, 2 neurons respectively with a dropout rate of 0.5. All layers except the last one are activated by ReLU activation function. The categorical cross entropy loss was minimized by Adaptive Moment Estimation(Adam) with a learning rate of 0.0001. \end{comment} \subsubsection{Capturing Textual Information} Apart from the GUI design picture, designers also attach some tags to index their picture. According to the observation in Figure~\ref{fig:communitydetection}, we find that some tags co-occur frequently, indicating some implicit relations among them. To predict the missing tags of a certain GUI design picture, we also take the existing tags into consideration in our model. Given a set of existing tags, we first adopted the pre-trained word embedding model~\cite{web:glove} to convert each tag into a 50-dimension vector that encodes its semantic. As an image has $n_{tags}$ number of tags, we concatenate the vectors of tags together, and obtain a $n_{tags}\times50$ vector representation. Finally, we pad and synthesize all tags' vector representation of each image into a $50\times50$ map (similar format to a figure) and input it to a 2-layer CNN for extracting the salient textual information. Note that we do not adopt the widely-used Recurrent Neural Network (RNN) to model tag information, as there is no explicit order among tags. \subsubsection{Combining Visual and Textual Information for Prediction} Based on the picture and tag input to the ResNet and text CNN, we obtain the embedding vectors which encode the visual and textual information. We then concatenate both vectors and feed them into another fully-connected layer for the final prediction. Therefore, we link both the ResNet, text CNN and final fully-connected layer as an end-to-end system for taking the UI design pictures and attached tags as the input, and output the predicted missing tags for them. Note that we train a separate binary classifier for each tag. We regard the UI is of one tag if the output is smaller than 0.5, while not if the output is equal to or larger than 0.5. For detailed implementation, we adopt the max-pooling and use our dataset to fine-tune the last classification layer of the pretrained ResNet when modeling the visual information. For modeling the textual data, we adopt the Glove word embedding~\cite{web:glove} with embedding size as 50. To make our training more stable, We use a constant learning schedule with rate 0.0001 and adopt Adam as an optimizer~\cite{kingma2014adam}, BCELoss as the loss function. \begin{comment} Please introduce our website including the overall data and all functionalities.\ \subsubsection{Implementation} We randomly crawl another 16546 ui designs as our website database. First, we provide a search box for users to enter filter keywords. In order to refine and decompose user requirements, we offer category filters based on Table~\ref{tab:morphologicalForm}. For example, if the user selects "Color" filter, the retrieved results would be split into "White", "Yellow", "Red" etc. Furthermore, we provide two baselines to compare our results. One is a link to the results of same filter keywords in Dribbble website. However, Dribbble database is several dozens of times larger than us. Therefore, we provide another link, which simulates Dribbble search engine (i.e., a fully matched search on tag, color, title etc.) but on our 16546 designs database. Furthermore, we find that some designers may upload their designs with irrelevant tags so that their designs is easier to search. In order to bring most relevant designs to designers, we apply a ranking system based on our prediction accuracy. For example, assume a design that is already tagged with "sport" by designer. If our model gives "Sport" a low degree of confidence, we still return this design in "Sport" result, but appear at bottom. Therefore, we balance the reliability and quantity. \end{comment} \subsection{Prediction Visualization} \label{sec:visualization} One of the main drawbacks of the deep learning system is its interpretability i.e., how the model gives a certain prediction, especially considering the multi-channel data that we adopt as the input. To gain insight into our classifier for the prediction results, we visualize the contribution from both the visual and textual input to the final prediction. For visualizing the contribution from the visual input to the prediction, we adopt a visualization technique~\cite{simonyan2013deep} which calculates a saliency map of the specific class, highlighting the conclusive features captured by ResNet. Given the prediction result, the activities of decisive features in intermediate layers are mapped back to the input pixel space by class saliency extraction~\cite{simonyan2013deep}. For one input UI design image, the final encoding of ResNet is mostly based on the weight of each pixel. Given the prediction result, the derivative weight map can be computed by back-propagation. Then the elements of weight are rearranged to form the saliency map. As shown in the final part of Figure~\ref{fig:CNN_Architecture}, it can be seen that the ResNet model predicts the tag ``Weather'' for that input design due to the existence of the sun, umbrella, and cloud in the UI design image. For visualizing the contribution from the textual input to the prediction, we first trace back through the CNN model to locating the filtered phrases in the input layer. Then we predict the contribution score of the phrases' corresponding features in the fully connected layer to the prediction class, through a series of feature mapping, unpooling and deconvolution operation. The predicted class of our CNN model is calculated by applying Softmax function~\cite{chen2018data} on the sum of the dot product of the weight matrix in the fully connected layer and the output feature vector of the concatenate layer. For each UI design, we rank the score of each tag and select three top tags that contribute most to the prediction of the missing tag. For example, it can be seen in Figure~\ref{fig:deepvisualization} that for the predicted tag "travel", the model highlights the words related to the landscape like "forest", "nature" and "mountain". \section{Augment Tags for the UI Design} \label{sec:tagAugmentation} Although extracting morphological forms mentioned in the last section can boost the performance of UI retrieval by normalizing the existing tags from designers, some UIs are still missing related tags which makes them unsearchable. Therefore, a method to recover the missing tags of existing UIs is necessary. However, based on the labeled data, we could not find a code-based heuristic that distinguishes tags from UI design images with high accuracy: the existing UI designs are too diverse. So, we propose a hybrid deep learning method modelling both the visual and textual information to predict missing tags of the UI design. \subsection{Approach overview} The overview of our approach can be seen in Fig~\ref{fig:CNN_Architecture}. To train the deep learning for tag augmentation, we first collect all existing UI designs with specific tags identified in our empirical study (Section~\ref{sec:trainingData}). We then develop a tag augmentation model by combining a CNN model for capturing visual UI information and a fully-connected neural network for capturing textual information of existing tags (Section~\ref{sec:model}). Additionally, to understand how our ensemble model makes its decisions through the visual and textual information, we apply a visualization technique (Saliency Maps~\cite{simonyan2013deep} and Softmax function~\cite{chen2018data}) for understanding which part of the figure and which words lead to the final prediction (Section~\ref{sec:visualization}). \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/CNN_structure.png} \caption{The architecture of our tag prediction model.} \label{fig:CNN_Architecture} \vspace{-5mm} \end{figure*} \begin{comment} \ruiqi{We have collect approximately 210K images along with their metadata from Dribbble\cite{web:dribble}. Based on the labeled data, we could not find a code-based heuristic that categorizes different UI designs with high accuracy: the tags used to describe UI designs by different labelers are not consistent or complete.} Label incompleteness can severely degrade the performance of the learned multi-label classification models, since it will build negative prediction patterns between the input instances and the missing labels and further propagate the mistakes into the prediction phase on the test data. Not all tag labels are rigidly exclusive, i.e., one UI design can be attached with multiple tags. For example, the UI design in Figure 1 is attached with ``ios app'', ``mobile app'', ``mobile app design'', ``ui'', ``uidesign''. \\ \ruiqi{To assist designers with the UI search, we trained a vision-based, deep learning pipeline that can automatically recommend tags for both newly created and existing UI designs, adapting a convolutional neural network (CNN) architecture to binary UI design classification.} \end{comment} \subsection{Dataset preparing} \label{sec:trainingData} We formulate this tag augmentation task as a classification problem. We leverage the tag categorization during the creation of the UI semantic vocabulary as the label, and corresponding UI design images and attached tags as the training data. Note that each UI design may own many semantic tags such as ``mobile'', ``blue'', ``social'', ``login'' and ``form'', and these tags are not exclusive from each other. Therefore, we cannot regard all tags as equal for training a multi-class classifier for tag prediction. In this work, we train a binary classifier for each tag label. Such binary classifiers also benefit the system extensibility for new tags, as we only need to train a new binary classifier for the new tag without altering existing models for the existing tags. For training each binary classifier, we take the UI design with that tag as the positive data. We randomly take the same amount of UI designs attached with tags which are in the same category of the target tags in Table~\ref{tab:tagCategory} as the negative training data, as tags in the same categories are always exclusive from each other. To keep the balance of data, we make the amount of positive data equal to that of negative data. Therefore, the chance level for accuracy is 50\%. We further preprocess the data in two aspects. For each tag, we merge similar tags based on the morphological/synonym form identification and some minor manual check. For example, the tag ``traveling'', ``travel guide'', ``trip'' are all merged to tag ``travel''. Note that the manual check is only carried out once for grouping similar tags in dataset preparation and no more human efforts are needed in the model construction. For each image, we normalize the pixel value by dividing the mean and standard deviation so that each pixel value is in the range between 0 to 1 for accelerating the training process. \begin{comment} \sidong{The dataset collected ranges from 440 to 18,772 for each category as seen in Fig~\ref{fig:frequency} with the balance of positive data and negative data. We further preprocess the data in two aspects. For each tag, we merge similar tags based on both the morphological form identification to decrease the ambiguity. For example, the tag ``traveling'', ``travel guide'', ``trip'' are all merged to tag ``travel''. For each image, we normalize the pixel value by dividing the mean and standard deviation so that each pixel value is in the range between 0 to 1 for accelerating the training process. Finally, data splitting is an important step whereby data is divided into training, validation and testing subsets to ensure good generalization ability of the model. By investigating the impact of different data splitting ratio in Section~\ref{third:evaluation}, we randomly take 80\% of them as the training data, 10\% as the validation data and 10\% as the testing data.} \end{comment} \begin{comment} \sidong{tags in the same category are not exclusive. For example, red UI can also tag with blue. Maybe rewrite as positive training data from tagged and negative from untagged? please check.} \end{comment} \subsection{Model Architecture} \label{sec:model} In this section, we propose an end-to-end deep fusion model to jointly learn visual and textual information. The architecture of the proposed network is shown in Fig~\ref{fig:CNN_Architecture}, which contains two main components. One CNN model takes the GUI design image as the input for extracting the visual features. The other CNN model takes the existing tags as the input for extracting the textual information. We then merge both information sources to the final fully-connected layers for predicting the tag of the GUI design. \subsubsection{Capturing Visual Information} Convolutional Neural Network (CNN)~\cite{lecun1998gradient, krizhevsky2012imagenet} is a class of deep, feed-forward neural networks, most commonly applied to analyze visual imagery. The architecture of a typical CNN is structured as a series of stages such as different layers called convolution layers, pooling layers, and fully-connected layers. In the convolutional layers, the convolution of an image is to use a kernel (e.g., $3\times3$ matrix) and then slide that window around the image. At each position in the image that the kernel ($K$) visits, we multiply its values element-wise with the original matrix, then sum them up i.e., matrix dot multiply. After the convolutional layers, it is the pooling layer. Max Pooling works very much like convoluting, where we take a kernel and move the kernel over the image with no overlap. It reduces parameter numbers and computation in the network, and hence controls the overfitting. Different from the original CNN model, we adopt a more advanced one, ResNet (Residual Neural Network)~\cite{Resnet} with skip connections among the convolutional layers so that the model can be designed as very deep. But due to the limitation of our dataset and deep structure of the model, we cannot train the ResNet directly with our small-scale dataset. Therefore, we adopt the existing pretrained model which already distills the visual features from the ImageNet~\cite{imagenet}, the largest image dataset including more than 14 million natural images. Based on the pre-trained ResNet, we further use our dataset to fine-tune the ResNet to adjust the parameters in different layers. \begin{comment} Our CNN model comprises 6 convolutional layers, and each one of them is followed by a max pooling layer with a stride and filter size of 2. Then there are three fully connected layers containing 2048, 1024, 2 neurons respectively with a dropout rate of 0.5. All layers except the last one are activated by ReLU activation function. The categorical cross entropy loss was minimized by Adaptive Moment Estimation(Adam) with a learning rate of 0.0001. \end{comment} \subsubsection{Capturing Textual Information} Apart from the GUI design picture, designers also attach some tags to index their picture. According to the observation in Figure~\ref{fig:communitydetection}, we find that some tags co-occur frequently, indicating some implicit relations among them. To predict the missing tags of a certain GUI design picture, we also take the existing tags into consideration in our model. Given a set of existing tags, we first adopted the pre-trained word embedding model~\cite{web:glove} to convert each tag into a 50-dimension vector that encodes its semantic. As an image has $n_{tags}$ number of tags, we concatenate the vectors of tags together, and obtain a $n_{tags}\times50$ vector representation. Finally, we pad and synthesize all tags' vector representation of each image into a $50\times50$ map (similar format to a figure) and input it to a 2-layer CNN for extracting the salient textual information. Note that we do not adopt the widely-used Recurrent Neural Network (RNN) to model tag information, as there is no explicit order among tags. \subsubsection{Combining Visual and Textual Information for Prediction} Based on the picture and tag input to the ResNet and text CNN, we obtain the embedding vectors which encode the visual and textual information. We then concatenate both vectors and feed them into another fully-connected layer for the final prediction. Therefore, we link both the ResNet, text CNN and final fully-connected layer as an end-to-end system for taking the UI design pictures and attached tags as the input, and output the predicted missing tags for them. Note that we train a separate binary classifier for each tag. We regard the UI is of one tag if the output is smaller than 0.5, while not if the output is equal to or larger than 0.5. For detailed implementation, we adopt the max-pooling and use our dataset to fine-tune the last classification layer of the pretrained ResNet when modeling the visual information. For modeling the textual data, we adopt the Glove word embedding~\cite{web:glove} with embedding size as 50. To make our training more stable, We use a constant learning schedule with rate 0.0001 and adopt Adam as an optimizer~\cite{kingma2014adam}, BCELoss as the loss function. \begin{comment} Please introduce our website including the overall data and all functionalities.\ \subsubsection{Implementation} We randomly crawl another 16546 ui designs as our website database. First, we provide a search box for users to enter filter keywords. In order to refine and decompose user requirements, we offer category filters based on Table~\ref{tab:morphologicalForm}. For example, if the user selects "Color" filter, the retrieved results would be split into "White", "Yellow", "Red" etc. Furthermore, we provide two baselines to compare our results. One is a link to the results of same filter keywords in Dribbble website. However, Dribbble database is several dozens of times larger than us. Therefore, we provide another link, which simulates Dribbble search engine (i.e., a fully matched search on tag, color, title etc.) but on our 16546 designs database. Furthermore, we find that some designers may upload their designs with irrelevant tags so that their designs is easier to search. In order to bring most relevant designs to designers, we apply a ranking system based on our prediction accuracy. For example, assume a design that is already tagged with "sport" by designer. If our model gives "Sport" a low degree of confidence, we still return this design in "Sport" result, but appear at bottom. Therefore, we balance the reliability and quantity. \end{comment} \subsection{Prediction Visualization} \label{sec:visualization} One of the main drawbacks of the deep learning system is its interpretability i.e., how the model gives a certain prediction, especially considering the multi-channel data that we adopt as the input. To gain insight into our classifier for the prediction results, we visualize the contribution from both the visual and textual input to the final prediction. For visualizing the contribution from the visual input to the prediction, we adopt a visualization technique~\cite{simonyan2013deep} which calculates a saliency map of the specific class, highlighting the conclusive features captured by ResNet. Given the prediction result, the activities of decisive features in intermediate layers are mapped back to the input pixel space by class saliency extraction~\cite{simonyan2013deep}. For one input UI design image, the final encoding of ResNet is mostly based on the weight of each pixel. Given the prediction result, the derivative weight map can be computed by back-propagation. Then the elements of weight are rearranged to form the saliency map. As shown in the final part of Figure~\ref{fig:CNN_Architecture}, it can be seen that the ResNet model predicts the tag ``Weather'' for that input design due to the existence of the sun, umbrella, and cloud in the UI design image. For visualizing the contribution from the textual input to the prediction, we first trace back through the CNN model to locating the filtered phrases in the input layer. Then we predict the contribution score of the phrases' corresponding features in the fully connected layer to the prediction class, through a series of feature mapping, unpooling and deconvolution operation. The predicted class of our CNN model is calculated by applying Softmax function~\cite{chen2018data} on the sum of the dot product of the weight matrix in the fully connected layer and the output feature vector of the concatenate layer. For each UI design, we rank the score of each tag and select three top tags that contribute most to the prediction of the missing tag. For example, it can be seen in Figure~\ref{fig:deepvisualization} that for the predicted tag "travel", the model highlights the words related to the landscape like "forest", "nature" and "mountain". \section{Information Needs Beyond Design Sharing} We interviewed four professional UI designers, including one interaction designers and one visual designer from Google, and the other two visual designers from Huawei. These designers acknowledge that they regularly (at least once weekly) visit design sharing websites like Dribbble. They appreciate the creativity and aesthetics of high-quality UI design artworks on Dribbble, which inspire their own design work. However, they also pinpoint several information needs in their work which demand us to think beyond existing content sharing mechanisms. First, as the contributors of Dribbble site, some designers do not pay much attention to their tagging, though it is crucial for the GUI index and searching. One designer from Huawei mentioned us that he did not intentionally use the semantic words (e.g., functionality, layout) to annotate his design works, as he did not know much what tags are there and which tags to use. Instead, he attached his UI design with some fancy tags like ``2019trending'' to make his design more attractive to other designers. A structured vocabulary of available tags is needed to assist designers in efficiently annotating their design works for other designers' retrieval. Second, there is a gap between existing UI tags and the query due to two reasons. On the one hand, some UIs are missing important semantic tags. For example, one Google designer was designing a website about Yoga. When she searched ``yoga``, there are many different kinds of returning results from Dribbble including the icons, charts, illustration which are not related to her designed UI or website. She had to manually filter out irrelevant ones, and that process took much time. But when she zoomed into a more specific query like ``yoga website``, only very few results were returned by Dribble. On the other hand, designers may adopt different words to tag the same GUI, resulting in the difficulty of retrieval. Another designer in Google mentioned that he would use different words in the same meaning for searching such as both ``travel`` and ``trip`` for related GUI, but that process is inefficient as many results from two queries overlap, and he may miss some potential synonyms. Some effective mechanism have to be devised to help retrieve more results by not only adding more semantic tags to the GUI design, but also organizing existing tags. \section{Discussion} \label{sec:discussion} In this section, we discuss the implication of our work on designers, design sharing platform, and the generalization of our approach. \textbf{On designers:} Designing good UI is a challenging task and the design taste of users is changing dynamically. To continually follow the trend, designers always resort to the online sharing resources such as design kits, blogs, design sharing websites for inspirations. Apart from browsing others' designs, many designers also actively share their own designs into the platform. Despite that the generosity is appreciated, more meta information related to the UI is also welcomed. The precise and complete tags attached to the UI can attract more designers, potentially leading to the popularity and reputation of you and your design. So, it is necessary for designers to add as many and precise tags to their design before uploading. \textbf{On design sharing platform:} To ensure the quality of UI design tags for supporting effective retrieval, the design sharing platform should develop a proactive mechanism. Although our model can recommend missing tags for indexing the UI semantics which further benefits the community with textural retrieval and management, there are still some limitations using it solely. First, without the support of the design platform, we can only implement our model as an extension of the browser like Chrome. Then it works as a reactive way for adding tags to the existing UI design, but missing tags may already harm the designers who want to search before our tag recommendation. Second, although our model can achieve good accuracy, there are still some error predictions that need some human efforts to confirm the recommended tags. Therefore, in addition to the reactive addition of tags to the existing UI design from our side, we also need a more proactive mechanism of tag assurance which could check a UI design before it is uploaded by spotting the potential missing tags, and reminding the design owner to confirm the recommended tags and add them. The simplest way is to list the vocabulary of existing tags aside when designers are filling in tags for their sharing design. We also hope that our model can be embedded into the design sharing sites, behaving as a proactive mechanism to not only automatically recommend designers with potential tags for choosing, but also warn them about wrong tags they adopt initially such as inconsistent tagging vocabulary (i.e., morphological forms). We can also leverage the crowd source i.e., the peer designers in the community to ensure the completeness and correctness of tags, and that mechanism is widely used in content generation sites like Wikipedia and Stack Overflow. The design sharing site should also allow and encourage moderators to edit community-generated tags. Previous studies~\cite{li2015good, chen2017community, choi2018will} indicate that experienced moderators are able to improve content consistency and quality by making lasting edits to low-quality posts, especially content curated by novices in Q\&A sites. There may be extra benefits to emphasize the role moderators can play at standardizing content across the site. \textbf{On the generalization of our approach}: We report and analyze the performance of our CNN-based model for predicting missing UI tags in Section \ref{third:evaluation}. One limitation with our model is that we current only test our model on 26 tags with enough corresponding UI designs. But note that given a new tag, our model just needs to collect all GUI designs with/without that tags as the training data after normalizing the tags. We then can train a specific binary classifier for amending that tags to the GUI design. Another limitation with our evaluation is that due to the time limit, we only take a single split of the dataset to plot the evaluation accuracy which may bring some noise or bias. In the future, we will try to mitigate that effect by adopting K-fold cross evaluation. In addition, our approach is not limited to UI designs. In fact, we do similar experiments in other tag categories with high frequency and large instances (20000 $\sim$ 60000 images) in Dribbble, including tag ``illustration'', ``icon'' and ``logo''. Table \ref{tab:ResultsForNonUI} shows that our model also achieves high accuracy in non-UI-related tags. The result demonstrates that our deep-learning method can be generalized to a broader range of graphic designs. \begin{table*} \caption{Tag classification model accuracy for non-UI-related tags} \vspace{-3mm} \label{tab:ResultsForNonUI} \begin{tabular}{lc} \toprule \textbf{Classes} & \textbf{Tag+Image accuracy}\\ \midrule illustration & 0.9336 \\ icon & 0.9296\\ logo & 0.9478\\ \bottomrule \end{tabular} \vspace{-5mm} \end{table*} \begin{comment} \subsection{Proactive Semantic Tag Assurance of UI Design} Based on the large-scale UI design and its corresponding tags, we develop a deep learning model to recommend additional tags for indexing the UI semantics. Although our model can benefit the design community with the textural retrieval, there are still some problems with that mechanism. First, our model now works as a reactive way for adding tags to the existing UI design, but missing tags may already harm the designers who want to search before our tag recommendation. Second, although our model can achieve good accuracy, there are still some error predictions which need some human efforts to confirm the recommended tags. Therefore, in addition to the reactive addition of tags to the existing UI design, we also need a more proactive mechanism of tag assurance which could check a UI design before it is uploaded, spot the potential missing tags, and remind the design owner to confirm the recommended tags and add them. We hope that our model can be embedded into the design sharing sites, behaving as a proactive mechanism to not only recommend designers with potential tags for choosing, but also warn them about wrong tags they adopt initially. \subsection{Serendipitous Designs} \begin{figure} \centering \subfigure[Mood board]{ \begin{minipage}[h]{0.33\linewidth} \centering \label{fig:moodboard} \includegraphics[height = 1.2in, width=1in]{figures/s2.jpg} \end{minipage}% }% \subfigure[Cartoon]{ \begin{minipage}[h]{0.33\linewidth} \centering \label{fig:foodList} \includegraphics[height = 1.2in, width=1in]{figures/s1.png} \end{minipage}% }% \subfigure[3D]{ \begin{minipage}[h]{0.33\linewidth} \centering \label{fig:3d} \includegraphics[height = 1.2in, width=1in]{figures/s3.png} \end{minipage} }% \captionsetup{labelfont = {bf,small}, textfont={bf,small}} \caption{Examples of the serendipitous designs.} \vspace{-5mm} \label{fig:serendipitous_design} \end{figure} Apart from the students who label if the candidate UI is related to the query, we also invite a professional UI designer from Google to see the results from our model informally. She was impressed by the number, and the accuracy of UI results given the queries. She mentioned that as a designer, she always searched the UI on Dribbble iteratively, i.e., after the initial query, she would continuously refine the queries according to the inspiration of the retrieved results, until getting the final most inspiring one. With the assistance of our model, she can obtain more related results from the query, leading to higher possibilities of getting the inspirations and refining more appropriate queries. Besides related candidates for each query, she also found some serendipities from the results. For example, for the query ``\textit{website, blue, landing page}'', there is a mood board~\cite{garner2001problem} of things from photos to various textures so that they could visualize ideas and concepts. Figure~\ref{fig:moodboard} showcases font, button, and layout stylings without the limitations of adhering to a particular wireframed page for inspiration. For the query ``mobile, food\&drink, listview'', different from other UIs with the real dishes, Figure~\ref{fig:foodList} shows a cute UI design which uses some cartoon objects to represent the real food and drink. Such UI design may be more attractive to children customers. For the query ``ios finance chart'', Figure~\ref{fig:3d} not only contains the 2D financial line charts which frequently appear in other results, but also includes a 3D bar chart to highlight the number distributions. She acknowledged these results retrieved by our method, and these results may inspire her in the real-world design works. \end{comment} \begin{comment} Maybe we can discuss the implication of this work to the website design like how to maintain the tagging system like Stack Overflow. 1) help retrieval 2) proactively remind designers about the missing tag. 3) help remove some wrong tags \end{comment} \section{Accuracy Evaluation} \label{sec:AccurayEvaluation} \subsection{Dataset} Given all the data assigned to each tag, we prepare the dataset as discussed in Section~\ref{sec:trainingData}. The foundation of the deep learning model is the big data, so we only select tags (including its derived tags) with frequency larger than 300 in Table~\ref{tab:tagCategory} for training the model. Therefore, there are 26 tags (e.g., ``music'', ``signup''\footnote{The full list of tags and their frequency can be seen at \url{https://github.com/UITagPrediction/CSCW2020}}) left with the number of UI designs ranging from 312 to 13,233. Note when splitting the dataset, we only carry out a single split into training, validation, and testing set which may cause some bias. We discuss this limitation in the end of the paper and propose the improvement in the future work. Note that as the splitting ratio may influence the final results, we experiment four splitting ratio (training : validation : testing), 50\%:25\%:25\%, 60\%:20\%:20\%, 70\%:15\%:15\% and 80\%:10\%:10\% for each model respectively. \begin{comment} and randomly take 80\% of them as the training data, 10\% for validation and the other 10\% as the testing data. \sidong{I think that this part can be merged with dataset preparing in Section~\ref{sec:trainingData}. This part looks confused in Accuracy evaluation.} \subsection{The influence of training dataset} \label{influenceOfTrainingDataset} \zhengyang{ We compare our deep-learning based model with other several approaches with respect to different dataset splitting ratio. Specifically, we use the ratio (training : validation : tesing) 50\%:25\%:25\%, 60\%:20\%:20\%, 70\%:15\%:15\% and 80\%:10\%:10\% for each model respectively. The average accuracy of five classes for each approach is presented in table \ref{tab:DatasetSplittingRatio} and some detailed evaluation results are shown in appendix. The result shows that the performances are not much different but in general the ratio 80\%:10\%:10\% dominants others. Therefore, we take the 80\% training 10\% testing and 10\% validation which is also commonly used in deep-learning experiments.} \end{comment} \begin{table} \centering \caption{Tag classification accuracy for four dataset splitting ratios in different methods.} \label{tab:DatasetSplittingRatio} \resizebox{1\textwidth}{!}{ \begin{tabular}{ccccccc} \toprule \textbf{Dataset splitting ratio} & \multicolumn{6}{c}{\textbf{ACCURACY} } \\ \cline{2-7} \multicolumn{1}{l}{\begin{tabular}[c]{@{}c@{}}\textbf{(train:validation:test)}\\\end{tabular}} & \begin{tabular}[c]{@{}c@{}}\textbf{Histo }\\\textbf{ +SVM} \end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{Histo }\\\textbf{ +DT} \end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{ResNet }\\\textbf{ -pretraind} \end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{ResNet }\\\textbf{ +pretraind} \end{tabular} & \textbf{Tag only} & \textbf{Tag+Image} \\ \hline \textbf{50\%:25\%:25\%} & 0.6009 & 0.5531 & 0.6841 & 0.7410 & 0.7306 & \textbf{0.7940} \\ \textbf{60\%:20\%:20\%} & {0.6061} & {0.5629} & {0.6827} & {0.7402} & 0.7316 & {\textbf{0.7829}}\\ \textbf{70\%:15\%:15\%} & {0.6123} & {0.5805} & {0.6866} & {0.7387} & 0.7391 & {\textbf{0.7875}}\\ \textbf{80\%:10\%:10\%} & {0.5965} & {0.6249} & {0.7342} & {0.7545} & 0.7522 & {\textbf{0.8272}}\\ \bottomrule \end{tabular}} \end{table} \subsection{Baselines} We first set up several basic machine-learning baselines including the feature extraction (e.g., color histogram~\cite{wang2010robust}) with machine-learning classifiers (e.g., decision tree~\cite{quinlan1983learning}, SVM~\cite{cortes1995support}). Color histogram (Histo) is a simple image feature that represents the distribution of colors in each RGB (red, green, blue) channel. Based on these hand-crafted features, we adopt the support vector machine (SVM) and decision tree (DT) as the classifiers. Apart from these conventional machine learning based baselines, we also set up several derivations of our model as baselines to test the importance of different inputs of our approach including with or without pretrained model (ResNet-pretained, ResNet+pretained), only using UI design image, existing tags or both of them (ResNet+pretained, Tag only, Tag+Image). The training and testing configurations for these baselines are the same as that of our CNN model. \begin{table*} \caption{Tag classification accuracy for five categories in different methods.} \label{tab:Result} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.6636 &{0.5545} & 0.6727 & 0.7909 & 0.8545 & \textbf{0.8909}\\ food\&drink&{0.5765}&{0.6294} &0.7529 & {0.7882} & 0.7706& \textbf{0.8294}\\ ecommerce & 0.5565 &{0.5726} &0.6895& {0.7460} & 0.8306 & \textbf{0.8710}\\ finance&{0.5655}&{0.5833} &0.6964& {0.7500} & 0.8274&\textbf{0.8512}\\ travel&{0.5211}&{0.5842} &0.7316& {0.7053} & 0.8053 &\textbf{0.8474}\\ game&{0.5814}&{0.5814} &0.8062& {0.7984} & 0.7597 &\textbf{0.8605}\\ weather&{0.5745}&{0.7021} &0.7447& {0.7872} & 0.8085 &\textbf{0.8298}\\ sport&{0.4220}&{0.6147} &0.6147& {0.6239} & 0.7064 & \textbf{0.7798}\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5865}&\textbf{0.7596} & 0.7404 & {0.7404}&0.6442 &0.7500 \\ red&{0.6667}&{0.7083} & 0.8194 & \textbf{0.8472}& 0.6111 &\textbf{0.8472}\\ pink&{0.7609}&{0.6522} & 0.7826 & {0.7391} & 0.6522 &\textbf{0.8261}\\ blue&{0.6600}&{0.6800} & 0.7700 & {0.7400}& 0.6800 & \textbf{0.8700}\\ green&{0.7000}&\textbf{0.8714} & 0.8286 & {0.7714} & 0.6571 & {0.7857} \\ white&{0.6111}&{0.6111} & 0.7778 & {0.7333}& 0.7333 & \textbf{0.7888} \\ black&{0.6241}&{0.6015} & 0.8496 & {0.8271} & 0.6617 & \textbf{0.8571}\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.5465}&{0.5346} &{0.7106}&{0.7017}& 0.7947 & \textbf{0.8115}\\ signup&{0.4907}&0.5556&{0.7731}&{0.7130}& 0.7361 &\textbf{0.7778}\\ checkout&{0.5545}&0.4182&{0.6000}&{0.7091}& 0.7545 &\textbf{0.8000}\\ profile&{0.4667}&{0.5538} &{0.5487}&{0.6513}&\textbf{0.9026} & 0.7590 \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.5867 & 0.6067 &{0.7600}&{0.7933}& 0.7867 &\textbf{0.8800}\\ chart&{0.6061}&{0.6667} &{0.7121}&{0.7424}&\textbf{0.8485} & 0.8030\\ form&{0.5429}&{0.5000} &{0.6857}&{0.7429}& 0.5714 &\textbf{0.7714}\\ list&{0.6136}&{0.5909} &{0.7045}&\textbf{0.9091}& 0.6364 & 0.8182\\ grid&{0.5000}&{0.5811} &{0.6351}&{0.6486}& 0.7162 &\textbf{0.7432}\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7785}&{0.7847} & 0.8356 & {0.7954} & 0.9250 & \textbf{0.9402}\\ website&{0.7513}&{0.7481} & 0.8418 & {0.8224} & 0.8837 & \textbf{0.9171}\\ \midrule \textbf{Average} & {0.5965} & {0.6249} & {0.7342} & {0.7545} & 0.7522 & {\textbf{0.8272}}\\ \bottomrule \end{tabular} \end{table*} \subsection{Evaluation Results} \label{third:evaluation} As we train a binary classifier for each tag, we adopt the accuracy as the evaluation metric for the model. In different settings of data splitting, our model can still achieve the best performance compared with all baselines with average accuracy as 0.7875, 0.7829, 0.7940 (Table~\ref{tab:DatasetSplittingRatio}). It also demonstrates the robustness of our model in the scenario of the small training dataset. Due to space limitations, we introduce more detailed performance only in one setting\footnote{More detailed results in other settings can be seen at \url{https://github.com/UITagPrediction/CSCW2020}} (80\% training, 10\% validation and 10\% testing) which can be seen in Table~\ref{tab:Result}. For comparison, the first 4 models (i.e., Histo+SVM, Histo+DT, ResNet-pretrain and ResNet+pretrain) only use images as input, while only textual information is used in ``tag only'' model. Our model (Tag+Image) combine both images and tags. The traditional machine learning method based on the human-crafted features can only achieve about 0.6 average accuracy, while our model can achieve the average accuracy as 0.8272 i.e., the 32.4\% boost than the best baseline. The good performance of our model is due to two factors. First, the usage of the pretrained ResNet based on the ImageNet dataset increases the accuracy from 0.7342 to 0.7545. Second, combining both the visual information and textual information can lead to better prediction accuracy than using any single information. \begin{comment} Compared with the other baselines, our model achieves the best performance with the average accuracy as 0.8272. First, the fine-tune process makes the ResNet model have 2.36\% boost in accuracy. Second, the best baseline method is DT with Histo which can only obtain 0.6101 accuracy. In contrast, the performance of our model is 22.56\% better than the best baseline. It shows that the conventional machine learning based methods are not capable to deal with the complexity of the UI design images. \end{comment} \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/tagpredict.pdf} \vspace{-3mm} \caption{The predicted tags by our model for complementing the original tags.} \label{fig:UItagPrediction} \vspace{-0.8em} \end{figure*} Figure~\ref{fig:UItagPrediction} shows some predicted additional tags for example UI designs by our model. It shows that our models can help locate the platform (e.g., ``website'' for the second UI), screen color (e.g, ``blue'' for the fifth UI), app functionality (e.g., ``food'' for the first UI), screen functionality (e.g., ``checkout'' for the third UI), and screen layout (e.g., ``grid'' for the fourth example). All of these predicted tags are not appearing in the original tag set, and these additional tags can complement with the original ones for more effective UI retrieval. Besides, once our method can be incorporated into the real site like Dribbble, our model can recommend users with potential tags before their design upload which proactively ensures the quality of design tags. To show how our deep learning model works well for predicting the tag for the given UI design, we visualize the features learned in our model in Figure~\ref{fig:deepvisualization}. For example, our model spots the play button which widely appears in the music player apps and highlights the "player" in the words in Figure~\ref{fig:deepvisualization}.(c) when predicting tag ``music''. \begin{comment} For the predicted tag ``game'', we can see that our model pays much attention to the game controller in the UI, and "controller", "control panel" in the words. For the predicted tag ``music'', our model spots the play button which widely appears in the music player apps and highlights the "player" in the words. For the predicted tag ``chart'', our model not only can recognize the line-chart and pie-chart position, but also highlight words related to the chart related words like "analyse" and user-defined "analysticschart". \end{comment} The visualization results reveal that our model does capture the visual and textual semantics of different UI designs. \begin{figure*} \centering \subfigure[Predicted tag: game]{ \includegraphics[width = 0.475\textwidth]{figures/vis1.png} \label{fig:vis1}} \hfill \subfigure[Predicted tag: travel]{ \includegraphics[width = 0.475\textwidth]{figures/vis2.png} \label{fig:vis2}} \hfill \subfigure[Predicted tag: music]{ \includegraphics[width = 0.475\textwidth]{figures/vis3.png} \label{fig:vis3}} \hfill \subfigure[Predicted tag: chart]{ \includegraphics[width = 0.475\textwidth]{figures/vis4.png} \label{fig:vis4}} \vspace{-3mm} \caption{Visualization of the salient features in our model leading to the final predictions.} \label{fig:deepvisualization} \vspace{-5mm} \end{figure*} Albeit the good performance of our model, we still make wrong predictions for some UI designs. To identify the common causes of prediction errors, we then further manually check the wrong predictions in the test dataset. According to our observation, there are two main reasons leading to the wrong prediction. First, some UI designs are too complicated for the model to recognize the right tag for it. For example, the design in Figure ~\ref{fig:predicterror_1} is tagged with a ``music'' class. However, there is no notable feature for our classifier to understand it correctly. Second, some negative data is not really negative data due to the different preferences of designers. Our way to collect negative data assumes that one UI design image that does not contain the target tags but contains other same-category tags should not be attached to the target tag. Although it works for most cases, the collected negative data still contains some ``noisy'' UI designs i.e., UI design not attached with the target tags (maybe due to the designers' neglect) should be attached with tag. As seen in Figure~\ref{fig:predicterror_2}, although the main color is white, the designers still assign the tag ``blue'' to highlight the selected date in the calendar. It also applies to Figure ~\ref{fig:predicterror_3} whose label is ``sport'' while our model recognizes it as the ``e-commerce'' app. Although our prediction does not match the label, it still makes sense. \begin{comment} Third, there is ambiguity in the tag vocabulary since a tag may have multiple meanings. For example, the tag ``sport'' is usually associated with fitness applications, but it can also indicate sports wears. As in Figure ~\ref{fig:predicterror}(c), the design is clearly a e-commerce app, but it is tagged with ``sport'' without any ``e-commerce'' related tags. \end{comment} \begin{figure*} \centering \subfigure[No notable feature for the classifier to understand it correctly (missing "music" tag)]{ \includegraphics[width = 0.3\textwidth]{figures/new_p1.png} \label{fig:predicterror_1}} \hfill \subfigure[Some negative data is not really negative data (original design is tagged as "blue")]{ \includegraphics[width = 0.3\textwidth]{figures/new_p2.png} \label{fig:predicterror_2}} \hfill \subfigure[Different preferences of designers (the design is tagged as "sport" while our model predict it as "e-commerce")]{ \includegraphics[width = 0.3\textwidth]{figures/new_p3.png} \label{fig:predicterror_3}} \vspace{-5mm} \caption{Examples of the three kinds of prediction errors.} \label{fig:predicterror} \end{figure*} \section{Conclusion \& Future Works} UI is crucial for the success of the software especially for mobile apps in the market. Albeit a large number of UI designs online with human tags, many UIs are still missing some closely related keywords for retrieval. To assist designers with better UI design retrieval, we adopt a deep learning method to automatically recommend additional tags that convey the semantics of the UI. Based on the systematical analysis of the existing large-scale UI designs, our model can achieve the accuracy as 0.827 which significantly outperforms other baselines. The user study also demonstrates the usefulness of our model in UI retrieval. In the future, we are extending our research works into three different directions. On the one hand, we are diving into the model to improve the current accuracy performance. Currently, we only evaluate our model on tags which have many related UI as the training data, and we will also customize our model for achieving good performance on tags with only small datasets. On the other hand, we are exploring the searching for dynamic animation UI designs. According to our observation, apart from the static UI design images, there are also some animation designs in GIF format which show how users interact with the UI dynamically. We will leverage the video analysis method to analyze the human actions and design interactions within those GIFs, so that designers can search the animation with textual queries. Furthermore, to understand the usefulness of our technology in a real design context, we hope to cooperate with professional designers and design sharing sites by deploying our model. We will explore how designers actually make use of the retrieved UIs, and collect valuable feedback to improve our technology and evaluation methods. \section{Empirical Study of Design Sharing} \label{sec:empiricalStudy} In this work, we select Dribbble as our study subject, not only because of its popularity and large user base, but also due to its support for collaborative tagging. Dribbble is an online design sharing community which contains over 3.6 million uploaded artworks covering graphic design, user interface design, illustration, photography, and other creative areas. Only professional designers can be invited to upload their design works for sharing with the community, leading to high-quality design within the site. Since its foundation in 2009, Dribbble has become one of the largest networking platforms for designers to share their own designs and get inspirations from others'. For each design work, the graphical design is attached with the corresponding metadata including a title, a short description, tags specified by the designer, and comments from other users as seen in Figure~\ref{fig:missingTag}. To collect designs and associated metadata from Dribbble, we build a web crawler based on the Breadth-First search strategy~\cite{najork2001breadth} i.e., collecting a queue of URLs from a seed list, and putting the queue as the seed in the second stage while iterating. Apart from the graphical design (always in png, jpeg format), our crawler also obtains the corresponding metadata including title, description, tags, uploading date, number of likes, saves, views, etc. The crawling process continued from December 27, 2018 to March 19, 2019 with a collection of 226,000 graphical designs. Note that these graphical designs are diverse including UI design, logo, icon, clip art, branding, typography, etc. In this work, as we are concerned with the UI related design, we only select the UI attached with related tags such as ``user interface'', ``ui'', ``ux'', ``app design'', ``website design'', etc. Finally, we obtain a dataset of 61,700 UI design and their metadata. Based on this large dataset, we carry out an empirical study of collaborative tagging in Dribbble to understand its characteristics for motivating the required tool support. \subsection{What are designers sharing?} \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/communitydetection.pdf} \caption{The UI-related tag associative graph from December 27, 2018 to March 19, 2019.} \label{fig:communitydetection} \vspace{-1.0em} \end{figure*} Within the Dribbble site, the design creators can add at most 20 tags for their design work. These natural-language tags convey the semantics of the UI design such as internal structural information (e.g., ``dashboard'', ``list'', ``chart'') and belonging-software information (e.g., ``ecommerce'', ``food'', ``travel''). To provide readers with a better understanding of detailed semantic embedded in the UI design, we adopt the association rule mining~\cite{agrawal1994fast} and community detection~\cite{blondel2008fast} for visualizing the landscape of collected tags. \subsubsection{Overview of UI semantics} We first collect all the UI designs with tags $t$, and tags of each design figure are correlated. In the example of Fig.~\ref{fig:missingTag}, \textit{iphone} is one kind of \textit{mobile} phones. Each design is considered as a record and the design tags as the items in the record. We use association rule mining~\cite{agrawal1994fast} to discover tag correlations from tag co-occurrences in designs. As we want to mine the pair-wise correlation of tags and construct the landscape graph, we find frequent pairs of tags. A pair of tags is frequent if the percentage of how many designs are tagged with this pair of tags compared with all the designs is above the minimum support threshold $t_{sup}$. Given a frequent pair of tags $\{t_1, t_2\}$, association rule mining generates an association rule $t_1 \Rightarrow t_2$ if the confidence of the rule is above the minimum confidence threshold $t_{conf}$. The confidence of the rule $t_1 \Rightarrow t_2$ is computed as the percentage of how many designs are tagged with the pair of tags compared with the designs that are tagged with the antecedent tag $t_1$. Note that the original tags for filtering out non-UI designs like ``ui'', ``user interface'' are removed from the figure, as they are related to all tags in our dataset. Given the mined tag association rules, we construct an undirected graph $G(V, E)$, where the node set $V$ contains the tags (i.e., technologies) appearing in the association rules, and the edge set $E$ contains undirected edges $<t_1, t_2>$ (i.e., tag associations) if the two tags have the association $t_1 \Rightarrow t_2$ or $t_2 \Rightarrow t_1$\footnote{The edge is undirected because association rules indicate only the correlations between antecedent and consequent.} i.e., the confidence of either $\{t_1, t_2\}$ or $\{t_2, t_1\}$ larger than the threshold. Each edge has a confidence attribute indicating the strength of the technology association. Considering the balance between the information coverage and overload, we set the $t_{sup}$ as 0.001 and $t_{conf}$ as 0.2, resulting in the 197 nodes and 246 edges. We then carry out community detection~\cite{blondel2008fast} to group highly related nodes in the graph. In graph theory, a set of highly correlated nodes is referred to as a community (cluster) in the network. In this work, we use the Louvain method~\cite{blondel2008fast} implemented in the Gephi~\cite{bastian2009gephi} tool to detect communities. We visualize different communities with different colors and the nodes with higher frequency as large size as seen in Fig.~\ref{fig:communitydetection}. \subsubsection{Vocabulary of UI semantics} \begin{table*} \centering \makebox[0pt][c]{\parbox{1\textwidth}{% \begin{minipage}[b]{0.49\hsize}\centering \scriptsize \caption{The categorization of some most frequent UI-related tags.} \label{tab:tagCategory} \begin{tabular}{>{}p{2.5cm} >{}p{3.8cm}} \toprule \bf{CATEGORY} & \bf{ASSOCIATED TAG NAME}\\ \midrule \underline{PLATFORM} \\ \bf{\quad Website:} & Website, Web, Mac, Macbook\\ \textbf{\quad Mobile:} & Mobile, Phone, IOS, Iphone, Android\\ \textbf{\quad Tablet:} & Tablet, Ipad, Ipadpro\\ \underline{COLOR} \\ \textbf{\quad White:} & White \\ \textbf{\quad Yellow:} & Yellow, Golden, Orange \\ \textbf{\quad Red:} & Red \\ \textbf{\quad Pink:} & Pink \\ \textbf{\quad Purple:} & Purple\\ \textbf{\quad Blue:} & Blue, DarkBlue, SkyBlue \\ \textbf{\quad Green:} & Green, DarkGreen, Aquamarine \\ \textbf{\quad Grey:} & Grey, Silver, DarkGray\\ \textbf{\quad Brown:} & Brown \\ \textbf{\quad Black:} & Black\\ \underline{APP FUNCTIONALITY} \\ \textbf{\quad Music:} & Music, Musicplayer, MusicApp \\ \textbf{\quad Food \& Drink:} & Food, Restaurant, Drink \\ \textbf{\quad Game:} & Game, Videogame \\ \textbf{\quad Health \& Fitness:} & Fitness, Health \\ \textbf{\quad News:} & News\\ \textbf{\quad Sport:} & Sport, Gym, Workout\\ \textbf{\quad E-commerce:} & E-commerce, Store, OnlineShop\\ \textbf{\quad Social Networking:} & SocialNetwork, Blog, Messenger, Facebook, Instagram, Dating, Chat\\ \textbf{\quad Travel:} & Travel, Trip, Tourism\\ \textbf{\quad Weather:} & WeatherApp, Temperature\\ \textbf{\quad Lifestyle:} & Fashion, Furniture, Real Estate\\ \textbf{\quad Education:} & Education, E-learning\\ \textbf{\quad Reference:} & Dictionary, Atlas, Encyclopedia\\ \textbf{\quad Entertainment:} & Movie, TV, Netflix, Youtube\\ \textbf{\quad Medical:} & Medical, Healthcare, Hospital \\ \textbf{\quad Books:} & DigitalReading, DigitalBookstroe\\ \textbf{\quad Kids:} & Kids, Children\\ \textbf{\quad Finance:} & Finance, Wallet, Bank, Business, Insurance, Marketing\\ \textbf{\quad Utilities:} & Calculator, Clock, Measurement, WebBrowser\\ \textbf{\quad Navigation:} & DrivingAssistance, TopographicalMaps, PublicTransitMaps\\ \underline{SCREEN FUNCTIONALITY} \\ \textbf{\quad Landing Page:} & LandingPage\\ \textbf{\quad Login:} & Login, Signin\\ \textbf{\quad Signup:} & Signup, Registration\\ \textbf{\quad Checkout:} & Checkout, Payment\\ \textbf{\quad Search:} & Search\\ \textbf{\quad Profile:} & Profile\\ \textbf{\quad Contact Page:} & Contact, ContactPage\\ \underline{SCREEN LAYOUT} \\ \textbf{\quad Dashboard:} & Dashboard\\ \textbf{\quad Form:} & Form\\ \textbf{\quad Table:} & Table\\ \textbf{\quad List:} & List \\ \textbf{\quad Grid:} & Grid\\ \textbf{\quad Gallery:} & Gallery\\ \textbf{\quad Toolbar:} & Toolbar, Toolbox\\ \textbf{\quad Chart:} & Chart\\ \textbf{\quad Map:} & Map, MapView\\ \bottomrule \end{tabular} \end{minipage} \hfill \begin{minipage}[b]{0.49\hsize}\centering \scriptsize \caption{The 40 most frequent UI related tags with their abbreviations and synonyms and in brackets indicate the number of occurrences.} \label{tab:morphologicalForm} \begin{tabular}{>{\bfseries}p{2.3cm} >{}p{3.7cm}} \toprule \textbf{STANDARD(\#)} & \bf{ABBREVIATION \& SYNONYMS}\\ \midrule ui (61309): & user interface, user\_interface, user-interface design, uidesign\\ website (28009): & web, websites, webpage, website development, web design\\ ux (24209): & user experience, uxdesign, ux\_design\\ mobile (8554): & mobiledesign, mobile phone, mobile\_design, smartphone\\ illustration (7159): & illustation, digital\_illustration, kids\_illustration \\ app (5887): & apps, application, app development, app design\\ landing page (5536): & landing-page, landingpage, landing page design\\ minimal (4938): & minimalism, minimalistic, minimalist\\ ios (4741): & ios8, ios9, ios11, ios\_design \\ iphone (4736): & iphone x, iphonex, iphone 7, iphone\_8\\ icon (4230): & icons, icon design, icon pack\\ logo (3704): & logo design, logos, logotype\\ food (2881): & fastfood, food\_blog, junk\_food, doughnut\\ clean (2723):& clear, clean\_design\\ flat (2481): & flat design, flat-design, flat-art\\ interaction (2402): & interactive, microinteraction, interaction design, user interaction\\ dashboard (2141): & dashboard design, dashboards\\ branding (2071): & branding design, rebranding, selfbranding\\ sketch (2060): & sketching, sketches, adobe\_sketch \\ ecommerce (1974): & e-commerce, online commerce, shopping\\ vector (1940): & vectors, vector art\\ product (1841): & products, product page, product detail\\ typography (1820): & interface typography, 3d\_typography\\ gradient (1671): & gradients, gradient design, blue gradient\\ gif (1441): & gifs, looping\_gif\\ layout (1400): & layout design, layouts\\ concept (1378): & conceptual, concepts, concept art\\ motion (1361): & motion graphics, motion design\\ responsive (1347): & responsive design, response\\ music (1251): & music player, musician, musical, concert\\ restaurant (1221): & restaurants\\ profile (1204): & profiles, user\_profile, userprofile\\ travel (1197): & travelling, travel agency, travel guide\\ animation (1194): & animations, 3danimation, 2danimation\\ simple (1108): & simply, simplistic, simple\_design\\ graphic (1047): & graphics, graphic design, graphicdesigner\\ color (1000): & colors, colorful\\ white (988): & whitelabel, white design, white theme\\ login (919): & log\_in, sign\_in, login screen\\ modern (915): & modernistic, fashionable\\ \bottomrule \end{tabular} \end{minipage} }} \end{table*} As seen in Figure~\ref{fig:communitydetection}, many related tags are linked together such as (``travel'', ``hotel''), (``minimal'', ``simple''), (``ecommerce'', ``shop''), etc. To identify the set of frequently occurred UI tag categories, we adopted a consensus-driven, iterative approach to combine the observed tag landscape generated by our method with existing expert knowledge documented in books and websites such as \textit{Mobile Design Pattern Gallery}~\cite{neil2014mobile} and \textit{Google's Material Design}~\cite{web:googlematerial}. We also performed an iterative open coding of 1,000 most frequent co-occurring tags with tag ``ui'' in Dribbble, or approximately 8.2\% of the dataset (12,244 in total). Two researchers from our team independently coded the categories of these tags, noting any part of the initial vocabulary. Note that both researchers have UI design experience in both mobile apps and websites. After the initial coding, the researchers met and discussed discrepancies and the set of new tag categories until consensus was reached. This process yielded 5 main semantic UI categories: PLATFORM, COLOR, APP FUNCTIONALITY, SCREEN FUNCTIONALITY, SCREEN LAYOUT. Each main category also contains some sub-categories as seen in Table~\ref{tab:tagCategory}. For example, the APP FUNCTIONALITY category contains ``MUSIC'', ``FOOD \& DRINK'', ``GAME'', and the subcategory ``FOOD \& DRINK'' contains UI design tagged with ``Food'', ``Restaurant'', ``Drink'', etc. \subsection{Do designers use consistent tagging vocabulary?} \label{sec:tagNormalization} During the process of open coding the categories of UI semantic, we find that one tag can be written in different styles. For example, the tag ``visualization'' not only has its standard format, but also its derivations including its synonyms like ``visualisation'', ``visualizations'', and even misspelling ``vizualization''. As the UI design tagging process is informal and they are contributed by thousands of designers with very diverse technical and linguistic backgrounds, the same concept may be mentioned in many \textit{morphological forms} including \textit{abbreviations, synonyms, and misspellings}. The wide presence of morphological forms poses a serious challenge to information retrieval and also vocabulary construction. For example, the query ``ecommerce app'' may not find the UI design tagged with ``e-commerce'', ``e commerce design''. To extract these morphological forms of the same words, we adopt a semi-automatic method~\cite{chen2017unsupervised} which leverages both the semantic and lexical information within the word. We first train a word embedding~\cite{mikolov2013distributed} model to convert each tag into a vector that encodes its semantic. The tag with semantic similarity will be spotted such as ``minimal'' and ``minimalistic'', ``ui'' and ``user interface'', ``travel'' and ``hotel''. Then we define a lexical similarity threshold based on the string edit distance~\cite{levenshtein1966binary} to further check if two semantically-related words are similar enough in the form. So the synonyms are extracted like ``minimal'' and ``minimalistic''. To discriminate the abbreviations from semantically-related words, we define a set of rules e.g., the character of the abbreviation must be in the same order as they appear in the full name (ui, \textbf{u}ser \textbf{i}nterface), and the length of the abbreviation must be shorter than that of the full name, etc. Although the automatic approach can generate many possible pairs of morphological forms, some of them may still be wrong. Therefore, two researchers from our team manually check all of these pairs independently, and only take the morphological forms into consideration when the consensus is reached. Examples of some most frequent morphological forms are listed in Table~\ref{tab:morphologicalForm}. \begin{figure*} \centering \subfigure[Complete]{ \includegraphics[width = 0.23\textwidth]{figures/complete1.png} \label{fig:complete_1}} \hfill \subfigure[Complete]{ \includegraphics[width = 0.23\textwidth]{figures/complete2.png} \label{fig:complete_2}} \hfill \subfigure[Incomplete]{ \includegraphics[width = 0.23\textwidth]{figures/incomplete1.png} \label{fig:incomplete_1}} \hfill \subfigure[Incomplete]{ \includegraphics[width = 0.23\textwidth]{figures/incomplete2.png} \label{fig:incomplete_2}} \vspace{-1.1em} \caption{Examples of UI examples with complete $\&$ incomplete tags.} \label{fig:UIexamples} \end{figure*} \subsection{How do designers share and search UI designs in the design sharing site?} After quantitatively spotting the issues of collaborative tagging for the design sharing site, we further qualitatively get some feedback from informal interviews with four professional UI designers, including one interaction designer and one visual designer from Google, and the other two visual designers from Huawei. These designers acknowledge that they regularly (at least once weekly) visit design sharing websites like Dribbble. They appreciate the creativity and aesthetics of high-quality UI design artworks on Dribbble, which inspire their own design work. However, they also pinpoint several information needs in their work which demand us to think beyond existing content sharing mechanisms. First, as the contributors of the Dribbble site, some designers do not pay much attention to their tagging, though it is crucial for the GUI index and searching. One designer from Huawei mentioned to us that he did not intentionally use the semantic words (e.g., functionality, layout) to annotate his design works, as he did not know much what tags are there and which tags to use. Instead, he attached his UI design with some fancy tags like ``2019trending'' to make his design more attractive to other designers. A structured vocabulary of available tags is needed to assist designers in efficiently annotating their design works for other designers' retrieval. Second, there is a gap between existing UI tags and the query due to two reasons. On the one hand, some UIs are missing relevant semantic tags. For example, one Google designer was designing a website about Yoga. When she searched ``yoga``, there are many different kinds of returning results from Dribbble including the icons, charts, illustration which are not related to her designed UI or website. She had to manually filter out irrelevant ones, and that process took much time. But when she zoomed in a more specific query like ``yoga website``, only very few results were returned by Dribbble. On the other hand, designers may adopt different words to tag the same GUI, resulting in the difficulty of retrieval. Another designer in Google mentioned that he would use different words in the same meaning for searching such as both ``travel`` and ``trip`` for related GUI, but that process is inefficient as many results from two queries overlap, and he may miss some potential synonyms. Some effective mechanisms have to be devised to help retrieve more results by not only adding more semantic tags to the GUI design, but also organizing existing tags. Some example UIs with complete or incomplete tags from these designers can be seen in Figure~\ref{fig:UIexamples}. \textbf{Summary:} Design sharing site with diverse UI designs is crucial for inspiring professional designers. The collaborative tagging provides a way for designers to search for their UI design of interest. However, there are several limitations with current UI design tagging including using different same-meaning tags for the same UI design based on their own background knowledge, missing highly related tags for describing the UI design. Such limitations may hinder their potential utility as navigational cues for searchers. Therefore, an automated tag augmentation model is needed to recommend missing tags and keep existing tags consistent across different UI designs. \section{Retrieval Evaluation} The experiments in the last section demonstrate the accuracy of our model. We conduct a pilot user study in this section to further evaluate the usefulness of the predicted addition tags for bootstrapping the UI design retrieval. \subsection{Procedures for User Study} The number of words in each query is 2.35 on average, according to an analysis of an AltaVista search engine query log for almost 1 billion search requests from approximately 285 million users over six weeks~\cite{silverstein1999analysis}. Therefore, based on the five main categories of tags in Table~\ref{tab:tagCategory}, we randomly selected three tags from three categories respectively as the query. To mimic the real queries from designers, the query contains one platform tag and two tags from the other two random categories. We obtain 5 queries as seen in Table~\ref{tab:query}. We set up two groups for each query, i.e., control group and experimental group. The query database contains 61,700 UI designs collected from Section~\ref{sec:empiricalStudy}. For the control group, we directly retrieved the UI without tag augmentation in the database, which is regarded as a baseline for comparison. For experimental group, we searched the UI design database in which UI tags have been normalized by using the extracted abbreviations and synonyms in Section~\ref{sec:tagNormalization} and complemented with additional predicted tags as described in Section~\ref{sec:tagAugmentation}. Note that the UI can only be retrieved if it contains all keywords in the query. As there may be too many results from the experimental group (as seen in Table~\ref{tab:query}), we randomly take 10, 30, 50 retrieval candidates as the experimental groups so that it is fair to compare with the control group. We recruit 10 Master and final-year Bachelor students from our school, and each of them is assigned the results of five queries from one control group and three experimental groups. Note that they do not know which result is from the experimental or control group. Given each query, they individually mark each result as related to the query or not and for each query, we will randomly shuffle the order of candidates to avoid potential bias. After marking results for each query, they are asked to rate how satisfied they are with the retrieval results in a five-point likert scale (1: not satisfied at all and 5:highly satisfied), and how diverse also in five-point likert scale. \begin{comment} We conducted 30 semi-structured interviews with Master and final-year Bachelor students from April 2020 to May 2020. Two authors first developed the interview protocol, and conducted pilot studies with three participants. Based on the pilot studies, they refined the interview protocol and conducted 10 interviews formally. We recruited interviewees through direct contact and snowball sampling. All interviewees were participated voluntarily without compensation. To mimic the real queries from designers, the query contains one platform tag and two tags from the other two random categories. We set up two groups for each query, control group and experimental group. For control group, we directly retrieved the UI without tag augmentation in the database, which regards as a baseline for comparison. For the experimental group, we searched the UI design database including 61,700 UI designs whose tags have been normalized by using the extracted abbreviations and synonyms in Section~\ref{sec:tagNormalization} and complemented with additional predicted tags as described in Section~\ref{sec:tagAugmentation}. Note that the UI can only be retrieved if it contains all keywords in the query. As there may be too many results from the experimental group (as seen in Table~\ref{tab:query}), we randomly take 10, 30, 50 retrieval results as the experimental groups. From the pilot studies, we discovered that the number of tags from the UI design has significant impact to user evaluation. To guarantee the participants can objectively mark the result, we did not show any information except the query (such as tags, title, description, etc. ). The interviews were conducted through those five queries. For each query, we provided the interviewees two groups of results, the control group and one experimental group (i.e., 10, 30, 50). To be fair, interviewees did not know which one is from the experimental or control group and we also randomized before being presented to them for evaluation. We first asked them to evaluate each result in five-point likert scale (1: strongly related to the query and 5:strongly unrelated). We then asked them to rate the overall results for both groups, in terms of satisfaction and diversity. \end{comment} \begin{comment} For each query, we first search the collected database including 61,700 UI designs with original tags (control group). Then we also search the UI design database obtained by tag normalization as described in Section~\ref{sec:tagNormalization}) and tag \textcolor{red}{complementation ??this word seems to be used only for Genetics. maybe just tag augmentation} from our classifiers as described in Section~\ref{sec:tagPrediction} (experimental group). We recruit six Master and final-year Bachelor students from our school with \textcolor{red}{at least one-year experience about software UI design and implementation ??what does one-year experience mean? i do not think participants must have UI experience for this study}. Each of them is assigned the results of five queries from the control group and experimental group, and they do not know which one is from experimental or control group. They will individually mark each result as related to the query or not. Note that we have retrieved too many results from the \textcolor{red}{control group ??experimental group?}, so we only randomly take 50 of them for manual checking. After marking results for each query, they are asked to rate how satisfied they are with the retrieval results in five-point likert scale (1: not satisfied at all and 5:highly satisfied). \end{comment} \begin{table*} \caption{The random queries for searching UI designs} \vspace{-3mm} \label{tab:query} \begin{tabular}{llcc} \toprule \bf{ID} & \bf{Query} &\textbf{\#UI (control group)} & \textbf{\#UI (experimental)}\\ \midrule 1 & iphone+e-commerce+checkout & 3 & 604 \\ 2 & mobile+food\&drink+listview & 4 & 510\\ 3 & website+blue+landing page & 9 & 1838\\ 4 & ios+finance+chart & 4 & 1018\\ 5 & web+sign up+form & 10 & 440\\ \bottomrule \end{tabular} \end{table*} \begin{table*} \caption{The comparison of the experiment and control groups. $^*$denotes $p<$ 0.01, $^{**}$denotes $p<$ 0.05.} \vspace{-3mm} \label{tab:score_Tabel} \begin{tabular}{lcccc} \toprule \textbf{Measures} & \textbf{Control} & \textbf{Experiment 10} & \textbf{Experiment 30} & \textbf{Experiment 50}\\ \midrule \#Related Candidate & 3.2/6 (53.3\%) & 7.5/10 (75.6\%)$^{**}$ & 25.2/30 (84.1\%)$^*$ & 45/50 (90\%)$^*$\\ Satisfaction score & 2.8 & 3.56$^{**}$ & 4.28$^{**}$ & 4.8$^*$\\ Diversity score & 2.22 & 2.68$^*$ & 4.16$^*$ & 4.7$^*$\\ \bottomrule \end{tabular} \vspace{-3mm} \end{table*} \subsection{Results of Retrieval Effectiveness} Table~\ref{tab:score_Tabel} shows that the experimental group retrieves many more related candidates than the control group in both the absolute the number and relative percentage (75.6\%, 84.1\%, 90\% compared with 53.3\%). That is the biggest strength of our approach i.e., recovering the missing tags, resulting in more relevant UI designs given the query. Compared with the baseline, most participants admit that our method can provide more satisfactory and diverse results for them to choose from. And with the increase of the candidate number in the experimental group, participants give higher satisfaction and diversity scores (3.56, 4.28, 4.8 in satisfaction score, and 2.68, 4.16, 4.7 in diversity score) which are significantly higher than that (2.8, 2.22) of the control group. It is consistent with human perception, as more results lead to a higher possibility to see the serendipitous idea. The detailed results can be seen in our site\footnote{\url{https://sites.google.com/view/uitagpredictionuserstudy/home}}. \begin{comment} On average, the overall satisfaction ratings for the experiment group is 4.21, which is 89.6\% higher than the control group (2.22) in Table~\ref{tab:score_Tabel}. In contrast, the baseline can only achieve the average diversity score as 2.5. Experiment 10 is the most comparable group to control group as most of the control group can only retrieve less or equal to 10 results. Our experiment 10 can still achieve better user experience than control group in all of three measurements. As more results are retrieved (Experiment 30 and 50), we achieve higher satisfaction and diversity. Circling back to Table ~\ref{tab:query}, we reliably believe that our method can surpass control group by a large margin. \end{comment} To understand the significance of such differences, we carry out the Mann-Whitney U test~\cite{fay2010wilcoxon} (specifically designed for small samples) on the number of useful candidate, satisfactory, and diversity ratings between the experiment and the control group respectively. The test results suggest that our method does significantly outperform the baseline in terms of these metrics with $p < 0.01$ or $p < 0.05$. Although by no means conclusive, this user study provides initial evidence of the usefulness of our method for enhancing the performance of the tagging-based search. \begin{comment} \subsection{Results of Retrieval Effectiveness} Box plot in Figure~\ref{fig:user_study_evaluation} shows that the experimental group retrieves many more related candidates than the control group (with an average of 45 designs versus 3.24 designs for five queries). On average, the overall satisfaction ratings for the experiment group is 4.8, which is 71.4\% higher than the control group (2.8) in Table~\ref{tab:score_Tabel}. Most participants admit that our method can provide more diverse results for them to choose. In contrast, the baseline can only achieve the diversity score as 2.2. The detailed results can be seen on our site\footnote{\url{https://sites.google.com/view/userstudy/user-study-results}}. To understand the significance of the differences, we carry out the Mann-Whitney U test~\cite{fay2010wilcoxon} (specifically designed for small samples) on the number of useful candidate, satisfactory, and diversity ratings between the experiment and the control group respectively. The test results suggest that our method does significantly outperform the baseline in terms of these metrics with $p < 0.01$. Although by no means conclusive, this user study provides initial evidence of the usefulness of our method for enhancing the performance of the tagging-based search. \end{comment} \section{Introduction} Graphical User Interface (GUI) is ubiquitous which provides a visual bridge between a software application and end users through which they can interact with each other. Good GUI designs are essential to the success of a software application and can gain loyalty from the software users~\cite{jansen1998graphical}. However, designing good GUI is challenging and time-consuming, even for professional designers. On one hand, GUI designers must follow many design principles and constraints, such as fluent interactivity, universal usability, clear readability, aesthetic appearance, consistent styles~\cite{galitz2007essential, clifton2015android, web:appleDesign}. On the other hand, they also strive to be creative and come up with unique, original ideas. One way to design good UI is to learn from each other, and as a result, many design sharing websites such as Dribbble~\cite{web:dribble}, Behance~\cite{web:behance}, Coroflot~\cite{web:coroflot}, etc. have emerged and gained significant popularity among designers' community. Successful design sharing sites have become repositories of knowledge with millions of professional design artworks. For example, Dribbble has over 3.6 million designs~\cite{web:dribbble2018}. As most GUI designs are in image format which is difficult to organize or search, textual tags are one way that users sift through this volume of information. When tags are integrated into platform tools, they can be used to filter and retrieve relevant content. On Dribbble, tags can be used to set up the notification, personalize the design feed appearing on the homepage, annotate the design trend, and search for specific content. Tags are also used internally for the algorithms for recommending a list of related or potentially interesting GUI designs. Collaborative tagging systems~\cite{choi2018will, golder2006usage, macgregor2006collaborative} allow sites to distribute the work of categorization across the entire community. It has now been utilized by many sites to help organize large online repositories. For example, on Dribbble, designers are asked to apply up to 20 tags to describe their uploaded GUI designs. Collaborative tagging systems empower users to actively participate in the organization of the community content and distribute the effort of categorizing content across many users. As a result, more content can be labeled, making it easier to discover. \begin{comment} However, despite the enormous amount of UI designs existed online (e.g, 5.8 million designs in Dribble~\cite{web:dribble}, and 2 million designs in Coroflot~\cite{web:coroflot})), it is difficult for designers to efficiently find what they want~\cite{bernal2019guigle}. One major reason behind this phenomenon is the inability of today's search interface to translate design requirements (often specified in words) into design components in various interface examples (often specified in graphics). In existing platforms (such as Dribble~\cite{web:dribble}), matching GUI interfaces to search query is typically supported using image tagging\footnote{It is also widely known as image annotation or labeling} which is referred to the process of assigning a set of keywords to images to describe their content on semantic or syntactic levels. In an ideal world, the tags can be directly used to index images, and the desired data can thus be retrieved with a textual query i.e., matching the query with the existing tags. \end{comment} While tagging one UI design may seem relatively easy, prior work suggests that tagging involves a complex set of cognitive tasks~\cite{fu2008microstructures}. Tagging with others in a collaborative tagging system involves sharing and negotiating concepts or understanding from many different people. Collaborative tagging can be regarded as a collective sensemaking~\cite{golder2006usage} or a distributed cognitive system~\cite{fu2008microstructures}. But some issues emerge during this collaborative tagging~\cite{golder2006usage}, especially in design sharing sites. First, users may use different words to describe the same UI design based on their own background knowledge. As there are no rules for how a tag applies to one UI design, the tags provided by different designers for even similar meaning can be different, resulting in a very organic vocabulary, especially for designers who are new to the website. The increase in the use of incoherent tags may hinder content searching or navigation. For example, when designers want to search for UI designs with ``user interface'', the UI design tagged with ``ui'' or ``uidesign'' will be omitted. Second, users may extract different topics from the same design according to their own understanding, hence missing some closely related tags associated with the GUI design images. When tagging the UI design, users tend to provide only a few keywords that describe the most obvious visual or semantic contents, while content in other aspects may be simply omitted. Such an issue is further aggravated due to the gap for transforming the visual GUI design information to textual tags. \begin{comment} For example, the design in Figure~\ref{fig:missingTag} shows the sign-in page of a mobile application. Although it also contains a map view and a list of items, this design isn't tagged with any related keywords, resulting in the unsuccess of potential retrieval. \end{comment} For example, the design in Figure~\ref{fig:missingTag} shows the UI design of a food app. Although it contains a food view and a checkout page, this design isn't tagged with such related keywords, resulting in the potential failure of the retrieval. Once designers search it with ``user interface'', it may not appear in the returning result, though ``ui'' is the abbreviation of it. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/figure1.png} \caption{An example design from the design sharing website {\tt www.dribbble.com} of which tags illustrate the two problems with the tagging-based search.} \label{fig:missingTag} \vspace{-10pt} \end{figure*} Therefore, in addition to users' tagging, we also need a more proactive mechanism of tag assurance which could check the tag completeness of one UI design before it is uploaded, and remind the UI designers to fix issues if any. The goal of our work is to develop such a proactive policy assurance mechanism which can complement the existing collaborative tagging mechanism to augment existing tags of the GUI design, hence benefiting the GUI search and management in the design sharing sites. Our work is data driven and built on top of existing collaborative editing patterns by users. Therefore, our research questions are two-fold: 1) \textit{what kinds of issues are there with tagging in design sharing sites?} 2) \textit{does a deep-learning model help designers recover missing tags for UI designs?} To answer the first research question, we conduct an empirical study of tags attached to tens of thousands of GUI designs on Dribbble. By analyzing the existing tags, we find that users adopt incoherent tags with a large inconsistent vocabulary according to their own preferences. But some frequently used tags which convey the main semantic of the GUI design images emerge including tags related to the GUI platform, color, software functionality, screen functionality, screen layout, etc. Interviews with professional designers (UI design creators and uses of design sharing sites) from big companies also confirm the tag usage issues (i.e., inconsistency, tag missing). Considering the wide range of missing tags, it would require significant manual effort to develop a complete set of rules for guiding collaborative tagging. This challenge motivates us to develop a deep-learning based tag completeness assurance janitor to recommend to design owners or other users the potential missing tags that may be needed to augment existing tags. This janitor can also justify its prediction by pointing out the specific part of GUI designs relevant to the predicted tags. \begin{comment} These two problems can severely degrade the performance of the tagging-based UI design search. To solve these two problems, this paper presents an automated approach for recommending tags for both existing and new UI designs, leading to efficient retrieval of related UI design. We first construct a vocabulary of UI semantics by analyzing the existing tags for UI deign in Dribbble~\cite{web:dribble}. The vocabulary not only contains the high-level tag semantic category, but also merge tag abbreviations and synonyms into groups. Based on the vocabulary, we further develop a deep-learning model to automatically recover the missing tags to the UI design. To construct the vocabulary of UI semantics, we collected 61,700 UI designs from Dribbble. First, we carry out an empirical study about what tags designer use to annotate their UI design. Second, we group all UI-related tags into 5 major categories including the platform (e.g., \textit{mobile, website}), color (e.g., \textit{black, blue}), app functionality (e.g., \textit{music, game}), screen functionality (e.g., \textit{login, payment}), and screen layout (e.g., \textit{form, list}). As users may use different tags for the same meaning, we propose an unsupervised method to extract all morphological forms including abbreviations, synonyms and even misspellings. Through this iterative process and following manual check, we identify 369 abbreviations and 5646 synonyms and misspellings for the most frequent UI related tags. \end{comment} To recommend missing tags for UIs, we employ a hybrid approach that leverages both the visual and textual information. We train a binary classifier with UI design images from Dribbble labeled with this tag as positive data, while UI design images labeled with other tags in the same category as negative data. The trained model can help recommend tags for not only the new UI designs before sharing, but also remind designers about adding more tags for existing UI designs. The experiments demonstrate that our model with the average accuracy as 0.8272 significantly outperforms the other machine learning based models. To demonstrate the usefulness of our model, we also carry out a user study to show if our model for recovering missing tags can help retrieve more related UI designs compared with the default Dribbble search. After analyzing ten participants' feedback, we find that our model can provide more related and larger number of UI candidates given the queries than the baselines. The contributions of this work are threefold. \begin{itemize} \item We systematically investigate the collaborative tagging problems of the design sharing site including incoherent tag usage and missing tags. The informal interviews with professional designers also confirm these issues qualitatively. \item Based on the emerging tag categories, we develop a customized deep-learning based method for specifically recommending missing semantic tags to the existing design by leveraging both visual and textual information according to the UI design characteristics. We have released the source code, experiment results, and tag categorization to the public\footnote{\url{https://github.com/UITagPrediction/CSCW2020}} for replication and further extension. \item We conduct large-scale experiments to evaluate the performance and limitations of our approach. Our approach achieves good accuracy compared with baselines on a large-scale UI design dataset. The evaluation of our method for improving searching performance also demonstrates the usefulness of our model \end{itemize} \section{Dribbble UI Dataset} \label{sec:dataset} Dribbble is an online design sharing community which contains over 5.8 million uploaded artworks covering graphic design, user interface design, illustration, photography, and other creative areas. Only professional designers can be invited to upload their design works for sharing with the community, leading to the high-quality design within the site. Since its foundation in 2009, it has become one of the largest networking platform for designers to share their own designs and get inspirations from others'. For each design work, the graphical design is attached with the corresponding meta data including a title, a short description, tags specified by the designer, and comments from other users as seen in Figure~\ref{fig:missingTag}. In order to collect designs and associated metadata from Dribbble, we build a web crawler based on the Breadth-First search strategy~\cite{najork2001breadth} i.e., collecting a queue of URLs from a seed list, and putting the queue as the seed in the second stage while iterating. Apart from the graphical design (always in png, jpeg format), our crawler also obtains the corresponding meta data including title, description, tags, uploading date, number of likes, saves, views, etc. The crawling process continued from December 27, 2018 to March 19, 2019 with a collection of 226,000 graphical design. Note that these graphical designs are diverse including UI design, logo, icon, clip art, branding, typography etc. In this work, as we are concerned with the UI related design, we only select the UI attached with related tags such as ``user interface'', ``ui'', ``ux'', ``app design'', ``website design'', etc. Finally, we obtain a dataset of 61,700 UI design and their metadata. \begin{comment} 1) Introduce Dribbble\footnote{\url{https://dribbble.com/}}.\\ \ruiqi{ Founded in 2009 by Dan Cederholm and Rich Thornett, Dribbble has become one of the largest networking platform for designers to share their own designs and to explore and discover the work of others. When a design is uploaded onto Dribbble, it is defined by a title, a short descirption and several tags which are specified by the designer (see Figure 1 for a sample design). Members of Dribbble can comment, save, like and share designs. For designers who want to use Dribbble for inspiration, Dribbble allows users to browse and search designs by ``Popular shots'', ``Recent shots'', ``Designers'', ``Teams'', ``Colors'' and ``Tags''. } 2) Tell the crawling method \\ \ruiqi{In order to collect designs and associated metadata from Dribbble, we build a web crawler and implement the Breadth-First search strategy. The web crawler first builds a queue of URLs from a seed list, which is a list of Dribbble design ids. Then at each stage of the crawling process, the crawler dequeues a URL and requests the corresponding page. Once a webpage is retrieved, it is parsed and the metadata is fetched. During the parsing process, all sub URLs found in the webpage are extracted and added to the queue.} \\ 3) What data are we collecting? How much data do we collect?\ruiqi{Among all the information on Dribbble, we collect designs along with their metadata: title, short description, designer, the design team or company that the designer works for, a list of tags, attachments, the uploaded date and the numbers of Views, Likes, Saves. We have also collected a list of reviews for each design, as well as the reviewer's name and the number of Likes for each review.} \end{comment} \section{Modifications} \begin{acks} We appreciate the initial exploration by Ruiqi Wang of this work. This project is partially supported by Facebook gift funding and ANU-Data61 Collaborative Research Project CO19314. \end{acks} \bibliographystyle{ACM-Reference-Format} \section{Related Works} Our work is problem driven, rather than approach driven. As our study is to recommend missing tags for UI design images, we are introducing related works in three aspects, i.e., works for helping UI design, collaborative tagging and tag prediction. \subsection{UI Design} GUI provides a visual bridge between apps and users through which they can interact with each other. To assist the mobile UI design, many studies are working on large-scale design mining including investigating the UI design patterns~\cite{alharbi2015collect}, color evolution~\cite{jahanian2017colors, jahanian2017mining}, UI design testing including usability~\cite{zhao2020seenomaly, liu2020owl} and accessibility~{chen2020unblind}, UI decomposition~\cite{chen2020object} and design implementation~\cite{chen2018ui}. Liu et al~\cite{liu2018learning} follow the design rules from Material Design to annotate the mobile GUI design to represent its semantics. Swearngin et al~\cite{swearngin2018rewire} adopt the image processing method to help designs with converting the mobile UI screenshots into editable files in Photoshop, so that designers can take it as a starting point for further customization. To render inspirations to the designer, Chen et al~\cite{chen2019storyboard} propose a program-analysis method to efficiently generate the storyboard with UI screenshots, given one app executable file. Fischer et al~\cite{fischerimaginenet} transfer the style from fine art to GUI. All of these works are helping simplify the design process for professional design. In contrast, our study is to assist with searching the existing UI design to render designers some inspirations. Retrieval-based methods~\cite{chen2019gallery, chen2020wireframe} are also used to develop user interfaces. Reiss~\cite{reiss2018seeking} parses developers' sketch into structured queries to search related UIs of Java-based desktop software in the database. GUIfetch~\cite{behrang2018guifetch} customizes Reiss's method~\cite{reiss2018seeking} into the Android app UI search by considering the transitions between UIs. Deka et al~\cite{deka2017rico} leverage auto-encoder to support UI searching by inputting the rough sketch. Similar to Reiss's work~\cite{reiss2018seeking}, Zheng et al~\cite{zheng2019faceoff} parse the DOM tree of one user-created rough website to locate similar well-designed websites by measuring tree distance. Note that all of these works either take the wireframe/sketch or partial source code as the input for searching the UI design. Different from them, we are annotating UI design with high-level natural-language semantic tags which can help textual queries for UI design retrieval. \subsection{Collaborative Tagging System} Tagging is to summarize the content with several compact keywords~\cite{golder2006usage, macgregor2006collaborative} and collaborative tagging allows individual users to create and apply tags to online items. Collaborative tagging systems are widely adopted by different sharing sites including Q\&A (e.g., Quora~\cite{web:quora}), picture sharing (e.g., Flickr~\cite{web:flickr}), web bookmarking sharing (e.g., Delicious~\cite{web:delicious}), etc. Instead of central authority, collaborative tagging systems constitute an entirely new method of information organization, which allows the entire community to generate tags and label content, typically to make the content easier for themselves or others to find later. Creating and applying tags in order to organize content requires the cognitive process of categorization~\cite{fu2008microstructures, fu2010semantic}. Although tags provide a way for sites to organize and for users to search the content, there are still some problems with it. So many research works have aimed to study on human tagging behavior. For example, Suchanek et al~\cite{suchanek2008social} examine whether tags are applied accurately by humans. Multiple empirical studies~\cite{golder2006usage, halpin2007complex, wetzker2010tag} conduct to evaluate human categorization consistency. Fu et al~\cite{fu2010semantic} study on whether users are influenced by others' tags. The conflict and divisions in collaborative tagging have been further spotted~\cite{choi2018will}. The empirical study in our work also confirms those tagging issues in design sharing sites. But different from existing works which mostly focus on the empirical study of such phenomenon, we further develop a method to help recover the missing tags and keep the consistency of tags across the site. Categorization of tags can analogously facilitate navigation and searching in the now-booming collaborative tagging system. A number of papers deal with exploring plenty of tag type categories for online resources of different kinds, such as book~\cite{golder2006usage}, movie~\cite{sen2006tagging}, TV program~\cite{melenhorst2007usefulness}, music~\cite{bischoff2008can}, blog~\cite{li2017types}. To the best of our knowledge, our work is the first to build a UI tag categorization using data mining and semi-automatic techniques. \begin{comment} To extend the prior works, our research aims to enable users to collaborate tagging systems on pictures, especially on GUI design. If the user apply a tag to an entity, then this entity is assumed to form a group with other entities with the same tag, in other words, they become a category. Recent works have aimed to study on human categorization. This includes Suchanek et al~\cite{suchanek2008social} examines whether tags are applied accurately by human; multiple empirical studies~\cite{golder2006usage, halpin2007complex, wetzker2010tag} conduct to evaluate on human categorization consistency; and the Fu et al~\cite{fu2010semantic} studies on whether users are influenced by others’ tags. While these studies show the effectiveness of human categorization, our study here focuses on automatic categorization, in which we automatically group ideas and objects together based on shared characteristics (i.e., visual and textual characteristics). \end{comment} \subsection{Tagging Prediction} Automatic image annotation (also known as automatic image tagging or linguistic indexing) is the process by which a computer system automatically assigns metadata in the form of captioning or keywords to a digital image~\cite{web:imageAnnotation}. Most work has focused on personalized tag recommendation, suggesting tags to the user, bookmarking a new resource using collaborative filtering, taking into account similarities between users and tags~\cite{mishne2006autotag, xu2006towards, tso2008tag, liang2008collaborative}. As pointed out in~\cite{eom2011improving} that the visual content of images are a valuable information source, some researchers propose conventional machine learning methods for tag recommendation based on manually-crafted features~\cite{sigurbjornsson2008flickr, chen2013fast, kalayeh2014nmf}. \begin{comment} For example, Mishne ~\cite{mishne2006autotag} introduced an approach to recommend tags for weblogs, based on similar weblogs tagged by the same user. Xu et al.~\cite{xu2006towards} proposed a TF-IDF based method for collaborative tag suggestion that takes into account the reputation of users and a number of criteria for good tags, including high coverage, high popularity, least effort, and uniformity. Tso-Sutter et al.~\cite{tso2008tag} proposed a collaborative filtering tag-recommendation algorithm by integrating user and tag information. Liang et al.~\cite{liang2008collaborative} realized this idea for UI designs retrieval, recommending tags by using three derived user-item, user-tag and tag-item sub matrixes. \end{comment} Apart from the image, the text attached to the image (e.g., existing tags) may be another resource for tag recommendation. Murthy et al.~\cite{murthy2015automatic} explored a k-nearest-neighbor-based canonical correlation analysis (CCA) method for tag recommendation, which not only utilizes the convolutional neural network visual features but also explicitly incorporates the word embedding semantic information. Ma et al.~\cite{ma2017image} proposed a joint visual-semantic propagation model to the tag image and introduced a visual-guided LSTM to capture the co-occurrence relation of the tags. Bylinskii et al.~\cite{bylinskii2017understanding} recommended tags for infographics by adopting patch learning to select representative textual and visual elements from an infographic. Rawat et al.~\cite{rawat2016contagnet} proposed a context-aware model to integrate context information with image content for multi-label hashtag prediction. But note that different from prior works about tag recommendations for natural images on social-media platforms (e.g., Flickr), we are specifically targeting at uncovering semantic tags of UI design images for assisting designers in effectively seeking others' UI design. Inspired by the existing works on tag recommendation, we customize the off-the-shelf model for modeling both visual and textual information in three aspects. First, we adopt binary classifiers to boost the performance of the classification model. Previous works formulating this tag-recommendation problem as a multi-class multi-label classification task, but it always leads to data imbalance issues~\cite{liu2019synthetic} as the occurrence number of each tag differs significantly. Instead, according to our observation, most related (frequent) tags attached to the UI design are exclusive with each other, such as ``black vs red'', ``login page vs checkout page'', ``music app vs sport app''. Therefore, we develop a novel binary classifier for each tag and that method naturally solves the problem of data sparsity and imbalance. Second, to support the construction of binary classifiers, we carry out an empirical study of existing tags of 61,700 UI designs for distilling exclusive tags. Based on a series of methods including association rule mining and merging abbreviations and synonyms, we obtain a categorization of most frequent UI-related tags. Tags within the same category are exclusive from each other, enabling the consecutive construction of binary classifiers. Third, we also develop a data visualization method to help designers understand why we recommend certain tags for their UI designs. For each recommended tag, we draw a saliency map highlighting the conclusive features captured by our model. Compared with just a simple prediction, this explainability can help post owners or post editors judge the validity of the recommended post edits and may encourage them to accept the tool's recommendation. Making the prediction criteria more explicit is crucial for the acceptance of our deep learning based approach for tag recommendation. \begin{comment} Compared with these works, our work has two novelty. First, these research works have formulated tag recommendation as a multi-class multi-label classification task. Different from these works, we formulate it as a binary classification problem for each tag. This method can avoid two problems which frequently appear in previous works. First, the multi-class task always faces the data-unbalance problem i.e., the training data size for each class may vary significantly. Second, the multi-label task cannot specify the detailed number of assigned labels to one image i.e., one UI design image may be assigned 2 or 10 tags. To solve these two problems, instead of training one complex multi-class multi-label classifier, we propose to train a relatively simpler binary classifier for each tag. Second, these research works have focused on natural images, infographics, posters. In contrast, our target is to recommend tags for UI designs. Compared with natural images such as that from Flickr~\cite{web:flickr}, Facebook~\cite{web:facebook}, UI designs are artificial and created by human, leading to the needs of domain-specific data for the training. Different from infographic, poster which is a collection of imagery, charts, and text that gives an overview of a topic, UI design is designed to be easy to use and pleasant, with less information. In other words, UI design is hard to train??? As far as we know, our work is the first deep learning attempt to recommend tags for UI designs. Furthermore, our work identifies UI tag recommendation as a binary classification task, a simple but efficient way to overcome the fundamental limitations in prior works of using multi-class multi-label classification. \end{comment} \section*{Appendix} \chen{Move all these results to our website, as this makes the paper too long.} \label{sec:appendix} \begin{table*}[htb] \caption{Tag classification accuracy for five categories in different methods(70$\%$ training, 15$\%$ validation, 15$\%$ testing).} \label{tab:Result_715} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.6848 &{0.6182} & 0.6303 & 0.7879 & 0.8061 & \textbf{0.8303}\\ food\&drink&{0.6181}&{0.5866} &0.6969 & {0.7480} & \textbf{0.7638} & 0.7559\\ ecommerce & 0.5672 &{0.5457} & 0.6452& {0.7312} & 0.8118 & \textbf{0.8199}\\ finance&{0.6255}&{0.5618} &0.5976& {0.7171} & \textbf{0.8486}&0.7928\\ travel&{0.5825}&{0.5789} &0.5754& {0.6632} & 0.7474 &\textbf{0.7895}\\ game&{0.5521}&{0.5625} &0.6979& {0.7500} & 0.7552 &\textbf{0.7917}\\ weather&{0.6571}&{0.5286} &0.7000& {0.7571} & \textbf{0.8143} &0.7714\\ sport&{0.5549}&{0.5915} &0.5976& {0.6463} & 0.7500 & \textbf{0.7744}\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5613}&0.5097 & 0.7742 & \textbf{0.8258}&0.6839 & 0.7806 \\ red&{0.5780}&{0.5046} & 0.7706 & \textbf{0.8257}& 0.5963 &0.8073\\ pink&{0.6232}&{0.5652} & \textbf{0.8261} & {0.7536} & 0.5797 &0.7971\\ blue&{0.5302}&{0.5772} & \textbf{0.7651} & {0.6779}& 0.6644 & 0.7383\\ green&{0.5189}& 0.5283 & \textbf{0.8679} & {0.7830} & 0.6132 & {0.8019} \\ white&{0.6370}&{0.5481} & 0.7111 & \textbf{0.7704}& 0.6519 & \textbf{0.7704} \\ black&{0.6450}&{0.5500} & 0.7850 & \textbf{0.8350} & 0.6050 & 0.8250\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.5840}&{0.5920} &{0.6704}&{0.7168}& 0.8144 & \textbf{0.8368}\\ signup&{0.6006}&0.5820&{0.6161}&{0.6966}& 0.7059 &\textbf{0.7183}\\ checkout&{0.5818}&0.5212&{0.5697}&{0.6364}& \textbf{0.8061} &0.7152\\ profile&{0.5822}&{0.5719} &{0.5925}&{0.6507}&\textbf{0.7089} & 0.6986 \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.7265 & 0.6592 &{0.7309}&0.8655& 0.7803 & \textbf{0.8700}\\ chart&{0.5300}&{0.5200} &{0.5800}&{0.7800}& 0.8300 & \textbf{0.8600}\\ form&{0.6321}&{0.6226} &{0.6132}&{0.6698}& \textbf{0.6887} & 0.6792 \\ list&{0.6462}&{0.5538} &{0.5538}&\textbf{0.7077}& 0.5846 & 0.6923\\ grid&{0.5676}&{0.5766} &{0.6126}&{0.5946}& \textbf{0.7748} & 0.7027\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7719}&{0.7775} & 0.8328 & {0.8003} & 0.9409 & \textbf{0.9481}\\ website&{0.7603}&{0.7596} & 0.8388 & {0.8153} & 0.8894 & \textbf{0.9085}\\ \midrule \textbf{Average} & {0.6123} & {0.5805} & {0.6866} & {0.7387} & 0.7391 & {\textbf{0.7875}}\\ \bottomrule \end{tabular} \end{table*} \begin{table*} \caption{Tag classification accuracy for five categories in different methods(60$\%$ training, 20$\%$ validation, 20$\%$ testing).} \label{tab:Result_622} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.6409 &{0.5364} & 0.6182 & 0.7955 & 0.7864 & \textbf{0.8455}\\ food\&drink&{0.6154}&{0.5178} &0.6864 & {0.7604} & 0.7574& \textbf{0.8225}\\ ecommerce & 0.5755 &{0.5163} &0.6286& {0.7449} & 0.7837 & \textbf{0.8102}\\ finance&{0.5493}&{0.5463} &0.6000& {0.7731} & \textbf{0.8179}&\textbf{0.8179}\\ travel&{0.6069}&{0.5567} &0.5937& {0.7361} & 0.7652 &\textbf{0.8311}\\ game&{0.5882}&{0.5412} &0.6078& {0.7098} & 0.7647 &\textbf{0.7922}\\ weather&{0.6344}&{0.5269} &0.5806& {0.7097} & 0.6882 &\textbf{0.7742}\\ sport&{0.5367}&{0.5688} &0.5550& {0.6147} & \textbf{0.7706} & 0.7477\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5096}&0.5240 & 0.7356 & {0.7404}&0.6538 & \textbf{0.7692} \\ red&{0.5385}&{0.5385} & 0.7902 & \textbf{0.8601}& 0.6084 &\textbf{0.8601}\\ pink&{0.5543}&{0.5435} & \textbf{0.8913} & {0.6848} & 0.7391 &0.7826\\ blue&{0.5450}&{0.5200} & \textbf{0.7750} & {0.7300}& 0.6500 & 0.7700\\ green&{0.5571}& 0.5500 & \textbf{0.8429} & {0.7571} & 0.6000 & {0.7857} \\ white&{0.6056}&{0.5333} & 0.7389 & \textbf{0.8056}& 0.7000 & 0.7944 \\ black&{0.6312}&{0.5361} & 0.8289 & {0.8289} & 0.6236 & \textbf{0.8441}\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.6345}&{0.5826} &{0.6622}&{0.7226}& 0.8082 & \textbf{0.8227}\\ signup&{0.6419}&0.6163&{0.6023}&{0.7047}& 0.7116 &\textbf{0.7512}\\ checkout&{0.5409}&0.5318&{0.5773}&{0.6636}& 0.7273 &\textbf{0.7455}\\ profile&{0.5426}&{0.5530} &{0.5762}&{0.6150}&\textbf{0.6951} & 0.6822 \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.7033 & 0.6333 &{0.7533}&\textbf{0.8467}& 0.7400 &0.8267\\ chart&{0.6439}&{0.4924} &{0.6591}&{0.7652}&\textbf{0.8258} & 0.7424\\ form&{0.6214}&{0.5357} &{0.6214}&{0.6786}& 0.6429 &\textbf{0.7000}\\ list&{0.6364}&{0.5909} &{0.5909}&\textbf{0.7045}& 0.6136 & 0.6591\\ grid&{0.5850}&{0.5374} &{0.5850}&{0.6803}& \textbf{0.7279} & 0.7143\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7757}&{0.7691} & 0.8377 & {0.7993} & \textbf{0.9368} & 0.8236\\ website&{0.7452}&{0.7377} & 0.8117 & {0.8134} & \textbf{0.8824} & 0.8396\\ \midrule \textbf{Average} & {0.6061} & {0.5629} & {0.6827} & {0.7402} & 0.7316 & {\textbf{0.7829}}\\ \bottomrule \end{tabular} \end{table*} \begin{table*} \caption{Tag classification accuracy for five categories in different methods(50$\%$ training, 25$\%$ validation, 25$\%$ testing).} \label{tab:Result_622} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.5782 & 0.5164 & 0.6582 & \textbf{0.7709} & \textbf{0.7709} & {0.7491}\\ food\&drink&{0.6306}&{0.5482} &0.6894 & {0.7624} & 0.7576& \textbf{0.7694}\\ ecommerce & 0.5684 &{0.5342} &0.6596& {0.7182} & 0.8143 & \textbf{0.8306}\\ finance&{0.5971}&{0.5444} &0.6139& {0.6954} & \textbf{0.7986} & 0.7890\\ travel&{0.6118}&{0.5823} &0.6350& {0.7363} & 0.7616 &\textbf{0.8143}\\ game&{0.6176}&{0.6113} &0.7367& {0.7680} & \textbf{0.7806} &0.7712\\ weather&{0.6174}&{0.5478} &0.6174& {0.7217} & \textbf{0.7739} & 0.7304\\ sport&{0.5277}&{0.5129} &0.5646& {0.6162} & 0.7491 & \textbf{0.7823}\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5405}&0.5135 & 0.7104 & {0.7181}&0.6718 & \textbf{0.7259} \\ red&{0.5611}&{0.5167} & 0.7556 & 0.7944& 0.6000 &\textbf{0.8056}\\ pink&{0.6228}&{0.5175} & 0.8246 & {0.7544} & 0.6140 & \textbf{0.8421}\\ blue&{0.5360}&{0.5000} & \textbf{0.7320} & {0.6800}& 0.6400 & 0.7240\\ green&{0.5575}& 0.5230 & {0.7989} & {0.8276} & 0.6667 & \textbf{0.8506} \\ white&{0.5422}&{0.5556} & 0.7556 & {0.7333}& 0.7111 & \textbf{0.8000} \\ black&{0.5964}&{0.4789} & \textbf{0.8554} & {0.8313} & 0.5753 & 0.8464\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.6143}&{0.5757} &{0.6403}&{0.7194}& 0.7772 & \textbf{0.8129}\\ signup&{0.5651}&0.5279&{0.6115}&{0.7138}& 0.7138 &\textbf{0.7491}\\ checkout&{0.5401}&0.5438&{0.5219}&{0.6752}& 0.7117 &\textbf{0.7664}\\ profile&{0.6058}&{0.5477} &{0.5643}&{0.6701}& 0.6618 & \textbf{0.6971} \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.7005 & 0.5963 &{0.7299}&{0.8262}& 0.7326 & \textbf{0.8289}\\ chart&{0.6606}&{0.5152} &{0.6909}&{0.7939}&{0.8182} & \textbf{0.8303}\\ form&{0.6571}&{0.5714} &{0.6000}&{0.7314}& 0.6743 &\textbf{0.7714}\\ list&{0.5545}&{0.5364} &{0.6455}&0.7182& 0.7091 & \textbf{0.7364}\\ grid&{0.5351}&{0.4919} &{0.5676}&{0.6595}& 0.7081 & \textbf{0.7730}\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7581}&{0.7522} & 0.8015 & {0.8036} & 0.9295 & \textbf{0.9426}\\ website&{0.7270}&{0.7201} & 0.8046 & {0.8256} & 0.8745 & \textbf{0.9068} \\ \midrule \textbf{Average} & {0.6009} & {0.5531} & {0.6841} & {0.7410} & 0.7306 & {\textbf{0.7940}}\\ \bottomrule \end{tabular} \end{table*} \section{Conclusion \& Future Works} UI is crucial for the success of the software especially for mobile apps in the market. Albeit a large number of UI designs online with human tags, many UIs are still missing some closely related keywords for retrieval. To assist designers with better UI design retrieval, we adopt a deep learning method to automatically recommend additional tags that convey the semantics of the UI. Based on the systematical analysis of the existing large-scale UI designs, our model can achieve the accuracy as 0.827 which significantly outperforms other baselines. The user study also demonstrates the usefulness of our model in UI retrieval. In the future, we are extending our research works into three different directions. On the one hand, we are diving into the model to improve the current accuracy performance. Currently, we only evaluate our model on tags which have many related UI as the training data, and we will also customize our model for achieving good performance on tags with only small datasets. On the other hand, we are exploring the searching for dynamic animation UI designs. According to our observation, apart from the static UI design images, there are also some animation designs in GIF format which show how users interact with the UI dynamically. We will leverage the video analysis method to analyze the human actions and design interactions within those GIFs, so that designers can search the animation with textual queries. Furthermore, to understand the usefulness of our technology in a real design context, we hope to cooperate with professional designers and design sharing sites by deploying our model. We will explore how designers actually make use of the retrieved UIs, and collect valuable feedback to improve our technology and evaluation methods. \section{Dribbble UI Dataset} \label{sec:dataset} Dribbble is an online design sharing community which contains over 5.8 million uploaded artworks covering graphic design, user interface design, illustration, photography, and other creative areas. Only professional designers can be invited to upload their design works for sharing with the community, leading to the high-quality design within the site. Since its foundation in 2009, it has become one of the largest networking platform for designers to share their own designs and get inspirations from others'. For each design work, the graphical design is attached with the corresponding meta data including a title, a short description, tags specified by the designer, and comments from other users as seen in Figure~\ref{fig:missingTag}. In order to collect designs and associated metadata from Dribbble, we build a web crawler based on the Breadth-First search strategy~\cite{najork2001breadth} i.e., collecting a queue of URLs from a seed list, and putting the queue as the seed in the second stage while iterating. Apart from the graphical design (always in png, jpeg format), our crawler also obtains the corresponding meta data including title, description, tags, uploading date, number of likes, saves, views, etc. The crawling process continued from December 27, 2018 to March 19, 2019 with a collection of 226,000 graphical design. Note that these graphical designs are diverse including UI design, logo, icon, clip art, branding, typography etc. In this work, as we are concerned with the UI related design, we only select the UI attached with related tags such as ``user interface'', ``ui'', ``ux'', ``app design'', ``website design'', etc. Finally, we obtain a dataset of 61,700 UI design and their metadata. \begin{comment} 1) Introduce Dribbble\footnote{\url{https://dribbble.com/}}.\\ \ruiqi{ Founded in 2009 by Dan Cederholm and Rich Thornett, Dribbble has become one of the largest networking platform for designers to share their own designs and to explore and discover the work of others. When a design is uploaded onto Dribbble, it is defined by a title, a short descirption and several tags which are specified by the designer (see Figure 1 for a sample design). Members of Dribbble can comment, save, like and share designs. For designers who want to use Dribbble for inspiration, Dribbble allows users to browse and search designs by ``Popular shots'', ``Recent shots'', ``Designers'', ``Teams'', ``Colors'' and ``Tags''. } 2) Tell the crawling method \\ \ruiqi{In order to collect designs and associated metadata from Dribbble, we build a web crawler and implement the Breadth-First search strategy. The web crawler first builds a queue of URLs from a seed list, which is a list of Dribbble design ids. Then at each stage of the crawling process, the crawler dequeues a URL and requests the corresponding page. Once a webpage is retrieved, it is parsed and the metadata is fetched. During the parsing process, all sub URLs found in the webpage are extracted and added to the queue.} \\ 3) What data are we collecting? How much data do we collect?\ruiqi{Among all the information on Dribbble, we collect designs along with their metadata: title, short description, designer, the design team or company that the designer works for, a list of tags, attachments, the uploaded date and the numbers of Views, Likes, Saves. We have also collected a list of reviews for each design, as well as the reviewer's name and the number of Likes for each review.} \end{comment} \section{Discussion} \label{sec:discussion} In this section, we discuss the implication of our work on designers, design sharing platform, and the generalization of our approach. \textbf{On designers:} Designing good UI is a challenging task and the design taste of users is changing dynamically. To continually follow the trend, designers always resort to the online sharing resources such as design kits, blogs, design sharing websites for inspirations. Apart from browsing others' designs, many designers also actively share their own designs into the platform. Despite that the generosity is appreciated, more meta information related to the UI is also welcomed. The precise and complete tags attached to the UI can attract more designers, potentially leading to the popularity and reputation of you and your design. So, it is necessary for designers to add as many and precise tags to their design before uploading. \textbf{On design sharing platform:} To ensure the quality of UI design tags for supporting effective retrieval, the design sharing platform should develop a proactive mechanism. Although our model can recommend missing tags for indexing the UI semantics which further benefits the community with textural retrieval and management, there are still some limitations using it solely. First, without the support of the design platform, we can only implement our model as an extension of the browser like Chrome. Then it works as a reactive way for adding tags to the existing UI design, but missing tags may already harm the designers who want to search before our tag recommendation. Second, although our model can achieve good accuracy, there are still some error predictions that need some human efforts to confirm the recommended tags. Therefore, in addition to the reactive addition of tags to the existing UI design from our side, we also need a more proactive mechanism of tag assurance which could check a UI design before it is uploaded by spotting the potential missing tags, and reminding the design owner to confirm the recommended tags and add them. The simplest way is to list the vocabulary of existing tags aside when designers are filling in tags for their sharing design. We also hope that our model can be embedded into the design sharing sites, behaving as a proactive mechanism to not only automatically recommend designers with potential tags for choosing, but also warn them about wrong tags they adopt initially such as inconsistent tagging vocabulary (i.e., morphological forms). We can also leverage the crowd source i.e., the peer designers in the community to ensure the completeness and correctness of tags, and that mechanism is widely used in content generation sites like Wikipedia and Stack Overflow. The design sharing site should also allow and encourage moderators to edit community-generated tags. Previous studies~\cite{li2015good, chen2017community, choi2018will} indicate that experienced moderators are able to improve content consistency and quality by making lasting edits to low-quality posts, especially content curated by novices in Q\&A sites. There may be extra benefits to emphasize the role moderators can play at standardizing content across the site. \textbf{On the generalization of our approach}: We report and analyze the performance of our CNN-based model for predicting missing UI tags in Section \ref{third:evaluation}. One limitation with our model is that we current only test our model on 26 tags with enough corresponding UI designs. But note that given a new tag, our model just needs to collect all GUI designs with/without that tags as the training data after normalizing the tags. We then can train a specific binary classifier for amending that tags to the GUI design. Another limitation with our evaluation is that due to the time limit, we only take a single split of the dataset to plot the evaluation accuracy which may bring some noise or bias. In the future, we will try to mitigate that effect by adopting K-fold cross evaluation. In addition, our approach is not limited to UI designs. In fact, we do similar experiments in other tag categories with high frequency and large instances (20000 $\sim$ 60000 images) in Dribbble, including tag ``illustration'', ``icon'' and ``logo''. Table \ref{tab:ResultsForNonUI} shows that our model also achieves high accuracy in non-UI-related tags. The result demonstrates that our deep-learning method can be generalized to a broader range of graphic designs. \begin{table*} \caption{Tag classification model accuracy for non-UI-related tags} \vspace{-3mm} \label{tab:ResultsForNonUI} \begin{tabular}{lc} \toprule \textbf{Classes} & \textbf{Tag+Image accuracy}\\ \midrule illustration & 0.9336 \\ icon & 0.9296\\ logo & 0.9478\\ \bottomrule \end{tabular} \vspace{-5mm} \end{table*} \begin{comment} \subsection{Proactive Semantic Tag Assurance of UI Design} Based on the large-scale UI design and its corresponding tags, we develop a deep learning model to recommend additional tags for indexing the UI semantics. Although our model can benefit the design community with the textural retrieval, there are still some problems with that mechanism. First, our model now works as a reactive way for adding tags to the existing UI design, but missing tags may already harm the designers who want to search before our tag recommendation. Second, although our model can achieve good accuracy, there are still some error predictions which need some human efforts to confirm the recommended tags. Therefore, in addition to the reactive addition of tags to the existing UI design, we also need a more proactive mechanism of tag assurance which could check a UI design before it is uploaded, spot the potential missing tags, and remind the design owner to confirm the recommended tags and add them. We hope that our model can be embedded into the design sharing sites, behaving as a proactive mechanism to not only recommend designers with potential tags for choosing, but also warn them about wrong tags they adopt initially. \subsection{Serendipitous Designs} \begin{figure} \centering \subfigure[Mood board]{ \begin{minipage}[h]{0.33\linewidth} \centering \label{fig:moodboard} \includegraphics[height = 1.2in, width=1in]{figures/s2.jpg} \end{minipage}% }% \subfigure[Cartoon]{ \begin{minipage}[h]{0.33\linewidth} \centering \label{fig:foodList} \includegraphics[height = 1.2in, width=1in]{figures/s1.png} \end{minipage}% }% \subfigure[3D]{ \begin{minipage}[h]{0.33\linewidth} \centering \label{fig:3d} \includegraphics[height = 1.2in, width=1in]{figures/s3.png} \end{minipage} }% \captionsetup{labelfont = {bf,small}, textfont={bf,small}} \caption{Examples of the serendipitous designs.} \vspace{-5mm} \label{fig:serendipitous_design} \end{figure} Apart from the students who label if the candidate UI is related to the query, we also invite a professional UI designer from Google to see the results from our model informally. She was impressed by the number, and the accuracy of UI results given the queries. She mentioned that as a designer, she always searched the UI on Dribbble iteratively, i.e., after the initial query, she would continuously refine the queries according to the inspiration of the retrieved results, until getting the final most inspiring one. With the assistance of our model, she can obtain more related results from the query, leading to higher possibilities of getting the inspirations and refining more appropriate queries. Besides related candidates for each query, she also found some serendipities from the results. For example, for the query ``\textit{website, blue, landing page}'', there is a mood board~\cite{garner2001problem} of things from photos to various textures so that they could visualize ideas and concepts. Figure~\ref{fig:moodboard} showcases font, button, and layout stylings without the limitations of adhering to a particular wireframed page for inspiration. For the query ``mobile, food\&drink, listview'', different from other UIs with the real dishes, Figure~\ref{fig:foodList} shows a cute UI design which uses some cartoon objects to represent the real food and drink. Such UI design may be more attractive to children customers. For the query ``ios finance chart'', Figure~\ref{fig:3d} not only contains the 2D financial line charts which frequently appear in other results, but also includes a 3D bar chart to highlight the number distributions. She acknowledged these results retrieved by our method, and these results may inspire her in the real-world design works. \end{comment} \begin{comment} Maybe we can discuss the implication of this work to the website design like how to maintain the tagging system like Stack Overflow. 1) help retrieval 2) proactively remind designers about the missing tag. 3) help remove some wrong tags \end{comment} \section{Empirical Study of Design Sharing} \label{sec:empiricalStudy} In this work, we select Dribbble as our study subject, not only because of its popularity and large user base, but also due to its support for collaborative tagging. Dribbble is an online design sharing community which contains over 3.6 million uploaded artworks covering graphic design, user interface design, illustration, photography, and other creative areas. Only professional designers can be invited to upload their design works for sharing with the community, leading to high-quality design within the site. Since its foundation in 2009, Dribbble has become one of the largest networking platforms for designers to share their own designs and get inspirations from others'. For each design work, the graphical design is attached with the corresponding metadata including a title, a short description, tags specified by the designer, and comments from other users as seen in Figure~\ref{fig:missingTag}. To collect designs and associated metadata from Dribbble, we build a web crawler based on the Breadth-First search strategy~\cite{najork2001breadth} i.e., collecting a queue of URLs from a seed list, and putting the queue as the seed in the second stage while iterating. Apart from the graphical design (always in png, jpeg format), our crawler also obtains the corresponding metadata including title, description, tags, uploading date, number of likes, saves, views, etc. The crawling process continued from December 27, 2018 to March 19, 2019 with a collection of 226,000 graphical designs. Note that these graphical designs are diverse including UI design, logo, icon, clip art, branding, typography, etc. In this work, as we are concerned with the UI related design, we only select the UI attached with related tags such as ``user interface'', ``ui'', ``ux'', ``app design'', ``website design'', etc. Finally, we obtain a dataset of 61,700 UI design and their metadata. Based on this large dataset, we carry out an empirical study of collaborative tagging in Dribbble to understand its characteristics for motivating the required tool support. \subsection{What are designers sharing?} \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/communitydetection.pdf} \caption{The UI-related tag associative graph from December 27, 2018 to March 19, 2019.} \label{fig:communitydetection} \vspace{-1.0em} \end{figure*} Within the Dribbble site, the design creators can add at most 20 tags for their design work. These natural-language tags convey the semantics of the UI design such as internal structural information (e.g., ``dashboard'', ``list'', ``chart'') and belonging-software information (e.g., ``ecommerce'', ``food'', ``travel''). To provide readers with a better understanding of detailed semantic embedded in the UI design, we adopt the association rule mining~\cite{agrawal1994fast} and community detection~\cite{blondel2008fast} for visualizing the landscape of collected tags. \subsubsection{Overview of UI semantics} We first collect all the UI designs with tags $t$, and tags of each design figure are correlated. In the example of Fig.~\ref{fig:missingTag}, \textit{iphone} is one kind of \textit{mobile} phones. Each design is considered as a record and the design tags as the items in the record. We use association rule mining~\cite{agrawal1994fast} to discover tag correlations from tag co-occurrences in designs. As we want to mine the pair-wise correlation of tags and construct the landscape graph, we find frequent pairs of tags. A pair of tags is frequent if the percentage of how many designs are tagged with this pair of tags compared with all the designs is above the minimum support threshold $t_{sup}$. Given a frequent pair of tags $\{t_1, t_2\}$, association rule mining generates an association rule $t_1 \Rightarrow t_2$ if the confidence of the rule is above the minimum confidence threshold $t_{conf}$. The confidence of the rule $t_1 \Rightarrow t_2$ is computed as the percentage of how many designs are tagged with the pair of tags compared with the designs that are tagged with the antecedent tag $t_1$. Note that the original tags for filtering out non-UI designs like ``ui'', ``user interface'' are removed from the figure, as they are related to all tags in our dataset. Given the mined tag association rules, we construct an undirected graph $G(V, E)$, where the node set $V$ contains the tags (i.e., technologies) appearing in the association rules, and the edge set $E$ contains undirected edges $<t_1, t_2>$ (i.e., tag associations) if the two tags have the association $t_1 \Rightarrow t_2$ or $t_2 \Rightarrow t_1$\footnote{The edge is undirected because association rules indicate only the correlations between antecedent and consequent.} i.e., the confidence of either $\{t_1, t_2\}$ or $\{t_2, t_1\}$ larger than the threshold. Each edge has a confidence attribute indicating the strength of the technology association. Considering the balance between the information coverage and overload, we set the $t_{sup}$ as 0.001 and $t_{conf}$ as 0.2, resulting in the 197 nodes and 246 edges. We then carry out community detection~\cite{blondel2008fast} to group highly related nodes in the graph. In graph theory, a set of highly correlated nodes is referred to as a community (cluster) in the network. In this work, we use the Louvain method~\cite{blondel2008fast} implemented in the Gephi~\cite{bastian2009gephi} tool to detect communities. We visualize different communities with different colors and the nodes with higher frequency as large size as seen in Fig.~\ref{fig:communitydetection}. \subsubsection{Vocabulary of UI semantics} \begin{table*} \centering \makebox[0pt][c]{\parbox{1\textwidth}{% \begin{minipage}[b]{0.49\hsize}\centering \scriptsize \caption{The categorization of some most frequent UI-related tags.} \label{tab:tagCategory} \begin{tabular}{>{}p{2.5cm} >{}p{3.8cm}} \toprule \bf{CATEGORY} & \bf{ASSOCIATED TAG NAME}\\ \midrule \underline{PLATFORM} \\ \bf{\quad Website:} & Website, Web, Mac, Macbook\\ \textbf{\quad Mobile:} & Mobile, Phone, IOS, Iphone, Android\\ \textbf{\quad Tablet:} & Tablet, Ipad, Ipadpro\\ \underline{COLOR} \\ \textbf{\quad White:} & White \\ \textbf{\quad Yellow:} & Yellow, Golden, Orange \\ \textbf{\quad Red:} & Red \\ \textbf{\quad Pink:} & Pink \\ \textbf{\quad Purple:} & Purple\\ \textbf{\quad Blue:} & Blue, DarkBlue, SkyBlue \\ \textbf{\quad Green:} & Green, DarkGreen, Aquamarine \\ \textbf{\quad Grey:} & Grey, Silver, DarkGray\\ \textbf{\quad Brown:} & Brown \\ \textbf{\quad Black:} & Black\\ \underline{APP FUNCTIONALITY} \\ \textbf{\quad Music:} & Music, Musicplayer, MusicApp \\ \textbf{\quad Food \& Drink:} & Food, Restaurant, Drink \\ \textbf{\quad Game:} & Game, Videogame \\ \textbf{\quad Health \& Fitness:} & Fitness, Health \\ \textbf{\quad News:} & News\\ \textbf{\quad Sport:} & Sport, Gym, Workout\\ \textbf{\quad E-commerce:} & E-commerce, Store, OnlineShop\\ \textbf{\quad Social Networking:} & SocialNetwork, Blog, Messenger, Facebook, Instagram, Dating, Chat\\ \textbf{\quad Travel:} & Travel, Trip, Tourism\\ \textbf{\quad Weather:} & WeatherApp, Temperature\\ \textbf{\quad Lifestyle:} & Fashion, Furniture, Real Estate\\ \textbf{\quad Education:} & Education, E-learning\\ \textbf{\quad Reference:} & Dictionary, Atlas, Encyclopedia\\ \textbf{\quad Entertainment:} & Movie, TV, Netflix, Youtube\\ \textbf{\quad Medical:} & Medical, Healthcare, Hospital \\ \textbf{\quad Books:} & DigitalReading, DigitalBookstroe\\ \textbf{\quad Kids:} & Kids, Children\\ \textbf{\quad Finance:} & Finance, Wallet, Bank, Business, Insurance, Marketing\\ \textbf{\quad Utilities:} & Calculator, Clock, Measurement, WebBrowser\\ \textbf{\quad Navigation:} & DrivingAssistance, TopographicalMaps, PublicTransitMaps\\ \underline{SCREEN FUNCTIONALITY} \\ \textbf{\quad Landing Page:} & LandingPage\\ \textbf{\quad Login:} & Login, Signin\\ \textbf{\quad Signup:} & Signup, Registration\\ \textbf{\quad Checkout:} & Checkout, Payment\\ \textbf{\quad Search:} & Search\\ \textbf{\quad Profile:} & Profile\\ \textbf{\quad Contact Page:} & Contact, ContactPage\\ \underline{SCREEN LAYOUT} \\ \textbf{\quad Dashboard:} & Dashboard\\ \textbf{\quad Form:} & Form\\ \textbf{\quad Table:} & Table\\ \textbf{\quad List:} & List \\ \textbf{\quad Grid:} & Grid\\ \textbf{\quad Gallery:} & Gallery\\ \textbf{\quad Toolbar:} & Toolbar, Toolbox\\ \textbf{\quad Chart:} & Chart\\ \textbf{\quad Map:} & Map, MapView\\ \bottomrule \end{tabular} \end{minipage} \hfill \begin{minipage}[b]{0.49\hsize}\centering \scriptsize \caption{The 40 most frequent UI related tags with their abbreviations and synonyms and in brackets indicate the number of occurrences.} \label{tab:morphologicalForm} \begin{tabular}{>{\bfseries}p{2.3cm} >{}p{3.7cm}} \toprule \textbf{STANDARD(\#)} & \bf{ABBREVIATION \& SYNONYMS}\\ \midrule ui (61309): & user interface, user\_interface, user-interface design, uidesign\\ website (28009): & web, websites, webpage, website development, web design\\ ux (24209): & user experience, uxdesign, ux\_design\\ mobile (8554): & mobiledesign, mobile phone, mobile\_design, smartphone\\ illustration (7159): & illustation, digital\_illustration, kids\_illustration \\ app (5887): & apps, application, app development, app design\\ landing page (5536): & landing-page, landingpage, landing page design\\ minimal (4938): & minimalism, minimalistic, minimalist\\ ios (4741): & ios8, ios9, ios11, ios\_design \\ iphone (4736): & iphone x, iphonex, iphone 7, iphone\_8\\ icon (4230): & icons, icon design, icon pack\\ logo (3704): & logo design, logos, logotype\\ food (2881): & fastfood, food\_blog, junk\_food, doughnut\\ clean (2723):& clear, clean\_design\\ flat (2481): & flat design, flat-design, flat-art\\ interaction (2402): & interactive, microinteraction, interaction design, user interaction\\ dashboard (2141): & dashboard design, dashboards\\ branding (2071): & branding design, rebranding, selfbranding\\ sketch (2060): & sketching, sketches, adobe\_sketch \\ ecommerce (1974): & e-commerce, online commerce, shopping\\ vector (1940): & vectors, vector art\\ product (1841): & products, product page, product detail\\ typography (1820): & interface typography, 3d\_typography\\ gradient (1671): & gradients, gradient design, blue gradient\\ gif (1441): & gifs, looping\_gif\\ layout (1400): & layout design, layouts\\ concept (1378): & conceptual, concepts, concept art\\ motion (1361): & motion graphics, motion design\\ responsive (1347): & responsive design, response\\ music (1251): & music player, musician, musical, concert\\ restaurant (1221): & restaurants\\ profile (1204): & profiles, user\_profile, userprofile\\ travel (1197): & travelling, travel agency, travel guide\\ animation (1194): & animations, 3danimation, 2danimation\\ simple (1108): & simply, simplistic, simple\_design\\ graphic (1047): & graphics, graphic design, graphicdesigner\\ color (1000): & colors, colorful\\ white (988): & whitelabel, white design, white theme\\ login (919): & log\_in, sign\_in, login screen\\ modern (915): & modernistic, fashionable\\ \bottomrule \end{tabular} \end{minipage} }} \end{table*} As seen in Figure~\ref{fig:communitydetection}, many related tags are linked together such as (``travel'', ``hotel''), (``minimal'', ``simple''), (``ecommerce'', ``shop''), etc. To identify the set of frequently occurred UI tag categories, we adopted a consensus-driven, iterative approach to combine the observed tag landscape generated by our method with existing expert knowledge documented in books and websites such as \textit{Mobile Design Pattern Gallery}~\cite{neil2014mobile} and \textit{Google's Material Design}~\cite{web:googlematerial}. We also performed an iterative open coding of 1,000 most frequent co-occurring tags with tag ``ui'' in Dribbble, or approximately 8.2\% of the dataset (12,244 in total). Two researchers from our team independently coded the categories of these tags, noting any part of the initial vocabulary. Note that both researchers have UI design experience in both mobile apps and websites. After the initial coding, the researchers met and discussed discrepancies and the set of new tag categories until consensus was reached. This process yielded 5 main semantic UI categories: PLATFORM, COLOR, APP FUNCTIONALITY, SCREEN FUNCTIONALITY, SCREEN LAYOUT. Each main category also contains some sub-categories as seen in Table~\ref{tab:tagCategory}. For example, the APP FUNCTIONALITY category contains ``MUSIC'', ``FOOD \& DRINK'', ``GAME'', and the subcategory ``FOOD \& DRINK'' contains UI design tagged with ``Food'', ``Restaurant'', ``Drink'', etc. \subsection{Do designers use consistent tagging vocabulary?} \label{sec:tagNormalization} During the process of open coding the categories of UI semantic, we find that one tag can be written in different styles. For example, the tag ``visualization'' not only has its standard format, but also its derivations including its synonyms like ``visualisation'', ``visualizations'', and even misspelling ``vizualization''. As the UI design tagging process is informal and they are contributed by thousands of designers with very diverse technical and linguistic backgrounds, the same concept may be mentioned in many \textit{morphological forms} including \textit{abbreviations, synonyms, and misspellings}. The wide presence of morphological forms poses a serious challenge to information retrieval and also vocabulary construction. For example, the query ``ecommerce app'' may not find the UI design tagged with ``e-commerce'', ``e commerce design''. To extract these morphological forms of the same words, we adopt a semi-automatic method~\cite{chen2017unsupervised} which leverages both the semantic and lexical information within the word. We first train a word embedding~\cite{mikolov2013distributed} model to convert each tag into a vector that encodes its semantic. The tag with semantic similarity will be spotted such as ``minimal'' and ``minimalistic'', ``ui'' and ``user interface'', ``travel'' and ``hotel''. Then we define a lexical similarity threshold based on the string edit distance~\cite{levenshtein1966binary} to further check if two semantically-related words are similar enough in the form. So the synonyms are extracted like ``minimal'' and ``minimalistic''. To discriminate the abbreviations from semantically-related words, we define a set of rules e.g., the character of the abbreviation must be in the same order as they appear in the full name (ui, \textbf{u}ser \textbf{i}nterface), and the length of the abbreviation must be shorter than that of the full name, etc. Although the automatic approach can generate many possible pairs of morphological forms, some of them may still be wrong. Therefore, two researchers from our team manually check all of these pairs independently, and only take the morphological forms into consideration when the consensus is reached. Examples of some most frequent morphological forms are listed in Table~\ref{tab:morphologicalForm}. \begin{figure*} \centering \subfigure[Complete]{ \includegraphics[width = 0.23\textwidth]{figures/complete1.png} \label{fig:complete_1}} \hfill \subfigure[Complete]{ \includegraphics[width = 0.23\textwidth]{figures/complete2.png} \label{fig:complete_2}} \hfill \subfigure[Incomplete]{ \includegraphics[width = 0.23\textwidth]{figures/incomplete1.png} \label{fig:incomplete_1}} \hfill \subfigure[Incomplete]{ \includegraphics[width = 0.23\textwidth]{figures/incomplete2.png} \label{fig:incomplete_2}} \vspace{-1.1em} \caption{Examples of UI examples with complete $\&$ incomplete tags.} \label{fig:UIexamples} \end{figure*} \subsection{How do designers share and search UI designs in the design sharing site?} After quantitatively spotting the issues of collaborative tagging for the design sharing site, we further qualitatively get some feedback from informal interviews with four professional UI designers, including one interaction designer and one visual designer from Google, and the other two visual designers from Huawei. These designers acknowledge that they regularly (at least once weekly) visit design sharing websites like Dribbble. They appreciate the creativity and aesthetics of high-quality UI design artworks on Dribbble, which inspire their own design work. However, they also pinpoint several information needs in their work which demand us to think beyond existing content sharing mechanisms. First, as the contributors of the Dribbble site, some designers do not pay much attention to their tagging, though it is crucial for the GUI index and searching. One designer from Huawei mentioned to us that he did not intentionally use the semantic words (e.g., functionality, layout) to annotate his design works, as he did not know much what tags are there and which tags to use. Instead, he attached his UI design with some fancy tags like ``2019trending'' to make his design more attractive to other designers. A structured vocabulary of available tags is needed to assist designers in efficiently annotating their design works for other designers' retrieval. Second, there is a gap between existing UI tags and the query due to two reasons. On the one hand, some UIs are missing relevant semantic tags. For example, one Google designer was designing a website about Yoga. When she searched ``yoga``, there are many different kinds of returning results from Dribbble including the icons, charts, illustration which are not related to her designed UI or website. She had to manually filter out irrelevant ones, and that process took much time. But when she zoomed in a more specific query like ``yoga website``, only very few results were returned by Dribbble. On the other hand, designers may adopt different words to tag the same GUI, resulting in the difficulty of retrieval. Another designer in Google mentioned that he would use different words in the same meaning for searching such as both ``travel`` and ``trip`` for related GUI, but that process is inefficient as many results from two queries overlap, and he may miss some potential synonyms. Some effective mechanisms have to be devised to help retrieve more results by not only adding more semantic tags to the GUI design, but also organizing existing tags. Some example UIs with complete or incomplete tags from these designers can be seen in Figure~\ref{fig:UIexamples}. \textbf{Summary:} Design sharing site with diverse UI designs is crucial for inspiring professional designers. The collaborative tagging provides a way for designers to search for their UI design of interest. However, there are several limitations with current UI design tagging including using different same-meaning tags for the same UI design based on their own background knowledge, missing highly related tags for describing the UI design. Such limitations may hinder their potential utility as navigational cues for searchers. Therefore, an automated tag augmentation model is needed to recommend missing tags and keep existing tags consistent across different UI designs. \section{Accuracy Evaluation} \label{sec:AccurayEvaluation} \subsection{Dataset} Given all the data assigned to each tag, we prepare the dataset as discussed in Section~\ref{sec:trainingData}. The foundation of the deep learning model is the big data, so we only select tags (including its derived tags) with frequency larger than 300 in Table~\ref{tab:tagCategory} for training the model. Therefore, there are 26 tags (e.g., ``music'', ``signup''\footnote{The full list of tags and their frequency can be seen at \url{https://github.com/UITagPrediction/CSCW2020}}) left with the number of UI designs ranging from 312 to 13,233. Note when splitting the dataset, we only carry out a single split into training, validation, and testing set which may cause some bias. We discuss this limitation in the end of the paper and propose the improvement in the future work. Note that as the splitting ratio may influence the final results, we experiment four splitting ratio (training : validation : testing), 50\%:25\%:25\%, 60\%:20\%:20\%, 70\%:15\%:15\% and 80\%:10\%:10\% for each model respectively. \begin{comment} and randomly take 80\% of them as the training data, 10\% for validation and the other 10\% as the testing data. \sidong{I think that this part can be merged with dataset preparing in Section~\ref{sec:trainingData}. This part looks confused in Accuracy evaluation.} \subsection{The influence of training dataset} \label{influenceOfTrainingDataset} \zhengyang{ We compare our deep-learning based model with other several approaches with respect to different dataset splitting ratio. Specifically, we use the ratio (training : validation : tesing) 50\%:25\%:25\%, 60\%:20\%:20\%, 70\%:15\%:15\% and 80\%:10\%:10\% for each model respectively. The average accuracy of five classes for each approach is presented in table \ref{tab:DatasetSplittingRatio} and some detailed evaluation results are shown in appendix. The result shows that the performances are not much different but in general the ratio 80\%:10\%:10\% dominants others. Therefore, we take the 80\% training 10\% testing and 10\% validation which is also commonly used in deep-learning experiments.} \end{comment} \begin{table} \centering \caption{Tag classification accuracy for four dataset splitting ratios in different methods.} \label{tab:DatasetSplittingRatio} \resizebox{1\textwidth}{!}{ \begin{tabular}{ccccccc} \toprule \textbf{Dataset splitting ratio} & \multicolumn{6}{c}{\textbf{ACCURACY} } \\ \cline{2-7} \multicolumn{1}{l}{\begin{tabular}[c]{@{}c@{}}\textbf{(train:validation:test)}\\\end{tabular}} & \begin{tabular}[c]{@{}c@{}}\textbf{Histo }\\\textbf{ +SVM} \end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{Histo }\\\textbf{ +DT} \end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{ResNet }\\\textbf{ -pretraind} \end{tabular} & \begin{tabular}[c]{@{}c@{}}\textbf{ResNet }\\\textbf{ +pretraind} \end{tabular} & \textbf{Tag only} & \textbf{Tag+Image} \\ \hline \textbf{50\%:25\%:25\%} & 0.6009 & 0.5531 & 0.6841 & 0.7410 & 0.7306 & \textbf{0.7940} \\ \textbf{60\%:20\%:20\%} & {0.6061} & {0.5629} & {0.6827} & {0.7402} & 0.7316 & {\textbf{0.7829}}\\ \textbf{70\%:15\%:15\%} & {0.6123} & {0.5805} & {0.6866} & {0.7387} & 0.7391 & {\textbf{0.7875}}\\ \textbf{80\%:10\%:10\%} & {0.5965} & {0.6249} & {0.7342} & {0.7545} & 0.7522 & {\textbf{0.8272}}\\ \bottomrule \end{tabular}} \end{table} \subsection{Baselines} We first set up several basic machine-learning baselines including the feature extraction (e.g., color histogram~\cite{wang2010robust}) with machine-learning classifiers (e.g., decision tree~\cite{quinlan1983learning}, SVM~\cite{cortes1995support}). Color histogram (Histo) is a simple image feature that represents the distribution of colors in each RGB (red, green, blue) channel. Based on these hand-crafted features, we adopt the support vector machine (SVM) and decision tree (DT) as the classifiers. Apart from these conventional machine learning based baselines, we also set up several derivations of our model as baselines to test the importance of different inputs of our approach including with or without pretrained model (ResNet-pretained, ResNet+pretained), only using UI design image, existing tags or both of them (ResNet+pretained, Tag only, Tag+Image). The training and testing configurations for these baselines are the same as that of our CNN model. \begin{table*} \caption{Tag classification accuracy for five categories in different methods.} \label{tab:Result} \footnotesize \setlength{\tabcolsep}{0.3em} \begin{tabular}{lcccccc} \toprule \multirow{2}{*}{\textbf{CLASSES}} & \multicolumn{6}{c}{\textbf{ACCURACY}} \\ \cmidrule(r){2-7} & \textbf{\makecell{Histo+SVM}} & \textbf{\makecell{Histo+DT}} & \textbf{\makecell{ResNet-pretrain}} & \textbf{\makecell{ResNet+pretrain}} & \textbf{Tag only} & \textbf{Tag+Image} \\ \midrule \textbf{App Function} & & & & & & \\ music & 0.6636 &{0.5545} & 0.6727 & 0.7909 & 0.8545 & \textbf{0.8909}\\ food\&drink&{0.5765}&{0.6294} &0.7529 & {0.7882} & 0.7706& \textbf{0.8294}\\ ecommerce & 0.5565 &{0.5726} &0.6895& {0.7460} & 0.8306 & \textbf{0.8710}\\ finance&{0.5655}&{0.5833} &0.6964& {0.7500} & 0.8274&\textbf{0.8512}\\ travel&{0.5211}&{0.5842} &0.7316& {0.7053} & 0.8053 &\textbf{0.8474}\\ game&{0.5814}&{0.5814} &0.8062& {0.7984} & 0.7597 &\textbf{0.8605}\\ weather&{0.5745}&{0.7021} &0.7447& {0.7872} & 0.8085 &\textbf{0.8298}\\ sport&{0.4220}&{0.6147} &0.6147& {0.6239} & 0.7064 & \textbf{0.7798}\\ \cmidrule(r){0-0} \textbf{Color} & & & & & & \\ yellow&{0.5865}&\textbf{0.7596} & 0.7404 & {0.7404}&0.6442 &0.7500 \\ red&{0.6667}&{0.7083} & 0.8194 & \textbf{0.8472}& 0.6111 &\textbf{0.8472}\\ pink&{0.7609}&{0.6522} & 0.7826 & {0.7391} & 0.6522 &\textbf{0.8261}\\ blue&{0.6600}&{0.6800} & 0.7700 & {0.7400}& 0.6800 & \textbf{0.8700}\\ green&{0.7000}&\textbf{0.8714} & 0.8286 & {0.7714} & 0.6571 & {0.7857} \\ white&{0.6111}&{0.6111} & 0.7778 & {0.7333}& 0.7333 & \textbf{0.7888} \\ black&{0.6241}&{0.6015} & 0.8496 & {0.8271} & 0.6617 & \textbf{0.8571}\\ \cmidrule(r){0-0} \textbf{Screen Function} & & & & & & \\ landing page&{0.5465}&{0.5346} &{0.7106}&{0.7017}& 0.7947 & \textbf{0.8115}\\ signup&{0.4907}&0.5556&{0.7731}&{0.7130}& 0.7361 &\textbf{0.7778}\\ checkout&{0.5545}&0.4182&{0.6000}&{0.7091}& 0.7545 &\textbf{0.8000}\\ profile&{0.4667}&{0.5538} &{0.5487}&{0.6513}&\textbf{0.9026} & 0.7590 \\ \cmidrule(r){0-0} \textbf{Screen Layout} & & & & & & \\ dashboard & 0.5867 & 0.6067 &{0.7600}&{0.7933}& 0.7867 &\textbf{0.8800}\\ chart&{0.6061}&{0.6667} &{0.7121}&{0.7424}&\textbf{0.8485} & 0.8030\\ form&{0.5429}&{0.5000} &{0.6857}&{0.7429}& 0.5714 &\textbf{0.7714}\\ list&{0.6136}&{0.5909} &{0.7045}&\textbf{0.9091}& 0.6364 & 0.8182\\ grid&{0.5000}&{0.5811} &{0.6351}&{0.6486}& 0.7162 &\textbf{0.7432}\\ \cmidrule(r){0-0} \textbf{Platform} & & & & & & \\ mobile&{0.7785}&{0.7847} & 0.8356 & {0.7954} & 0.9250 & \textbf{0.9402}\\ website&{0.7513}&{0.7481} & 0.8418 & {0.8224} & 0.8837 & \textbf{0.9171}\\ \midrule \textbf{Average} & {0.5965} & {0.6249} & {0.7342} & {0.7545} & 0.7522 & {\textbf{0.8272}}\\ \bottomrule \end{tabular} \end{table*} \subsection{Evaluation Results} \label{third:evaluation} As we train a binary classifier for each tag, we adopt the accuracy as the evaluation metric for the model. In different settings of data splitting, our model can still achieve the best performance compared with all baselines with average accuracy as 0.7875, 0.7829, 0.7940 (Table~\ref{tab:DatasetSplittingRatio}). It also demonstrates the robustness of our model in the scenario of the small training dataset. Due to space limitations, we introduce more detailed performance only in one setting\footnote{More detailed results in other settings can be seen at \url{https://github.com/UITagPrediction/CSCW2020}} (80\% training, 10\% validation and 10\% testing) which can be seen in Table~\ref{tab:Result}. For comparison, the first 4 models (i.e., Histo+SVM, Histo+DT, ResNet-pretrain and ResNet+pretrain) only use images as input, while only textual information is used in ``tag only'' model. Our model (Tag+Image) combine both images and tags. The traditional machine learning method based on the human-crafted features can only achieve about 0.6 average accuracy, while our model can achieve the average accuracy as 0.8272 i.e., the 32.4\% boost than the best baseline. The good performance of our model is due to two factors. First, the usage of the pretrained ResNet based on the ImageNet dataset increases the accuracy from 0.7342 to 0.7545. Second, combining both the visual information and textual information can lead to better prediction accuracy than using any single information. \begin{comment} Compared with the other baselines, our model achieves the best performance with the average accuracy as 0.8272. First, the fine-tune process makes the ResNet model have 2.36\% boost in accuracy. Second, the best baseline method is DT with Histo which can only obtain 0.6101 accuracy. In contrast, the performance of our model is 22.56\% better than the best baseline. It shows that the conventional machine learning based methods are not capable to deal with the complexity of the UI design images. \end{comment} \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/tagpredict.pdf} \vspace{-3mm} \caption{The predicted tags by our model for complementing the original tags.} \label{fig:UItagPrediction} \vspace{-0.8em} \end{figure*} Figure~\ref{fig:UItagPrediction} shows some predicted additional tags for example UI designs by our model. It shows that our models can help locate the platform (e.g., ``website'' for the second UI), screen color (e.g, ``blue'' for the fifth UI), app functionality (e.g., ``food'' for the first UI), screen functionality (e.g., ``checkout'' for the third UI), and screen layout (e.g., ``grid'' for the fourth example). All of these predicted tags are not appearing in the original tag set, and these additional tags can complement with the original ones for more effective UI retrieval. Besides, once our method can be incorporated into the real site like Dribbble, our model can recommend users with potential tags before their design upload which proactively ensures the quality of design tags. To show how our deep learning model works well for predicting the tag for the given UI design, we visualize the features learned in our model in Figure~\ref{fig:deepvisualization}. For example, our model spots the play button which widely appears in the music player apps and highlights the "player" in the words in Figure~\ref{fig:deepvisualization}.(c) when predicting tag ``music''. \begin{comment} For the predicted tag ``game'', we can see that our model pays much attention to the game controller in the UI, and "controller", "control panel" in the words. For the predicted tag ``music'', our model spots the play button which widely appears in the music player apps and highlights the "player" in the words. For the predicted tag ``chart'', our model not only can recognize the line-chart and pie-chart position, but also highlight words related to the chart related words like "analyse" and user-defined "analysticschart". \end{comment} The visualization results reveal that our model does capture the visual and textual semantics of different UI designs. \begin{figure*} \centering \subfigure[Predicted tag: game]{ \includegraphics[width = 0.475\textwidth]{figures/vis1.png} \label{fig:vis1}} \hfill \subfigure[Predicted tag: travel]{ \includegraphics[width = 0.475\textwidth]{figures/vis2.png} \label{fig:vis2}} \hfill \subfigure[Predicted tag: music]{ \includegraphics[width = 0.475\textwidth]{figures/vis3.png} \label{fig:vis3}} \hfill \subfigure[Predicted tag: chart]{ \includegraphics[width = 0.475\textwidth]{figures/vis4.png} \label{fig:vis4}} \vspace{-3mm} \caption{Visualization of the salient features in our model leading to the final predictions.} \label{fig:deepvisualization} \vspace{-5mm} \end{figure*} Albeit the good performance of our model, we still make wrong predictions for some UI designs. To identify the common causes of prediction errors, we then further manually check the wrong predictions in the test dataset. According to our observation, there are two main reasons leading to the wrong prediction. First, some UI designs are too complicated for the model to recognize the right tag for it. For example, the design in Figure ~\ref{fig:predicterror_1} is tagged with a ``music'' class. However, there is no notable feature for our classifier to understand it correctly. Second, some negative data is not really negative data due to the different preferences of designers. Our way to collect negative data assumes that one UI design image that does not contain the target tags but contains other same-category tags should not be attached to the target tag. Although it works for most cases, the collected negative data still contains some ``noisy'' UI designs i.e., UI design not attached with the target tags (maybe due to the designers' neglect) should be attached with tag. As seen in Figure~\ref{fig:predicterror_2}, although the main color is white, the designers still assign the tag ``blue'' to highlight the selected date in the calendar. It also applies to Figure ~\ref{fig:predicterror_3} whose label is ``sport'' while our model recognizes it as the ``e-commerce'' app. Although our prediction does not match the label, it still makes sense. \begin{comment} Third, there is ambiguity in the tag vocabulary since a tag may have multiple meanings. For example, the tag ``sport'' is usually associated with fitness applications, but it can also indicate sports wears. As in Figure ~\ref{fig:predicterror}(c), the design is clearly a e-commerce app, but it is tagged with ``sport'' without any ``e-commerce'' related tags. \end{comment} \begin{figure*} \centering \subfigure[No notable feature for the classifier to understand it correctly (missing "music" tag)]{ \includegraphics[width = 0.3\textwidth]{figures/new_p1.png} \label{fig:predicterror_1}} \hfill \subfigure[Some negative data is not really negative data (original design is tagged as "blue")]{ \includegraphics[width = 0.3\textwidth]{figures/new_p2.png} \label{fig:predicterror_2}} \hfill \subfigure[Different preferences of designers (the design is tagged as "sport" while our model predict it as "e-commerce")]{ \includegraphics[width = 0.3\textwidth]{figures/new_p3.png} \label{fig:predicterror_3}} \vspace{-5mm} \caption{Examples of the three kinds of prediction errors.} \label{fig:predicterror} \end{figure*} \section{Introduction} Graphical User Interface (GUI) is ubiquitous which provides a visual bridge between a software application and end users through which they can interact with each other. Good GUI designs are essential to the success of a software application and can gain loyalty from the software users~\cite{jansen1998graphical}. However, designing good GUI is challenging and time-consuming, even for professional designers. On one hand, GUI designers must follow many design principles and constraints, such as fluent interactivity, universal usability, clear readability, aesthetic appearance, consistent styles~\cite{galitz2007essential, clifton2015android, web:appleDesign}. On the other hand, they also strive to be creative and come up with unique, original ideas. One way to design good UI is to learn from each other, and as a result, many design sharing websites such as Dribbble~\cite{web:dribble}, Behance~\cite{web:behance}, Coroflot~\cite{web:coroflot}, etc. have emerged and gained significant popularity among designers' community. Successful design sharing sites have become repositories of knowledge with millions of professional design artworks. For example, Dribbble has over 3.6 million designs~\cite{web:dribbble2018}. As most GUI designs are in image format which is difficult to organize or search, textual tags are one way that users sift through this volume of information. When tags are integrated into platform tools, they can be used to filter and retrieve relevant content. On Dribbble, tags can be used to set up the notification, personalize the design feed appearing on the homepage, annotate the design trend, and search for specific content. Tags are also used internally for the algorithms for recommending a list of related or potentially interesting GUI designs. Collaborative tagging systems~\cite{choi2018will, golder2006usage, macgregor2006collaborative} allow sites to distribute the work of categorization across the entire community. It has now been utilized by many sites to help organize large online repositories. For example, on Dribbble, designers are asked to apply up to 20 tags to describe their uploaded GUI designs. Collaborative tagging systems empower users to actively participate in the organization of the community content and distribute the effort of categorizing content across many users. As a result, more content can be labeled, making it easier to discover. \begin{comment} However, despite the enormous amount of UI designs existed online (e.g, 5.8 million designs in Dribble~\cite{web:dribble}, and 2 million designs in Coroflot~\cite{web:coroflot})), it is difficult for designers to efficiently find what they want~\cite{bernal2019guigle}. One major reason behind this phenomenon is the inability of today's search interface to translate design requirements (often specified in words) into design components in various interface examples (often specified in graphics). In existing platforms (such as Dribble~\cite{web:dribble}), matching GUI interfaces to search query is typically supported using image tagging\footnote{It is also widely known as image annotation or labeling} which is referred to the process of assigning a set of keywords to images to describe their content on semantic or syntactic levels. In an ideal world, the tags can be directly used to index images, and the desired data can thus be retrieved with a textual query i.e., matching the query with the existing tags. \end{comment} While tagging one UI design may seem relatively easy, prior work suggests that tagging involves a complex set of cognitive tasks~\cite{fu2008microstructures}. Tagging with others in a collaborative tagging system involves sharing and negotiating concepts or understanding from many different people. Collaborative tagging can be regarded as a collective sensemaking~\cite{golder2006usage} or a distributed cognitive system~\cite{fu2008microstructures}. But some issues emerge during this collaborative tagging~\cite{golder2006usage}, especially in design sharing sites. First, users may use different words to describe the same UI design based on their own background knowledge. As there are no rules for how a tag applies to one UI design, the tags provided by different designers for even similar meaning can be different, resulting in a very organic vocabulary, especially for designers who are new to the website. The increase in the use of incoherent tags may hinder content searching or navigation. For example, when designers want to search for UI designs with ``user interface'', the UI design tagged with ``ui'' or ``uidesign'' will be omitted. Second, users may extract different topics from the same design according to their own understanding, hence missing some closely related tags associated with the GUI design images. When tagging the UI design, users tend to provide only a few keywords that describe the most obvious visual or semantic contents, while content in other aspects may be simply omitted. Such an issue is further aggravated due to the gap for transforming the visual GUI design information to textual tags. \begin{comment} For example, the design in Figure~\ref{fig:missingTag} shows the sign-in page of a mobile application. Although it also contains a map view and a list of items, this design isn't tagged with any related keywords, resulting in the unsuccess of potential retrieval. \end{comment} For example, the design in Figure~\ref{fig:missingTag} shows the UI design of a food app. Although it contains a food view and a checkout page, this design isn't tagged with such related keywords, resulting in the potential failure of the retrieval. Once designers search it with ``user interface'', it may not appear in the returning result, though ``ui'' is the abbreviation of it. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{figures/figure1.png} \caption{An example design from the design sharing website {\tt www.dribbble.com} of which tags illustrate the two problems with the tagging-based search.} \label{fig:missingTag} \vspace{-10pt} \end{figure*} Therefore, in addition to users' tagging, we also need a more proactive mechanism of tag assurance which could check the tag completeness of one UI design before it is uploaded, and remind the UI designers to fix issues if any. The goal of our work is to develop such a proactive policy assurance mechanism which can complement the existing collaborative tagging mechanism to augment existing tags of the GUI design, hence benefiting the GUI search and management in the design sharing sites. Our work is data driven and built on top of existing collaborative editing patterns by users. Therefore, our research questions are two-fold: 1) \textit{what kinds of issues are there with tagging in design sharing sites?} 2) \textit{does a deep-learning model help designers recover missing tags for UI designs?} To answer the first research question, we conduct an empirical study of tags attached to tens of thousands of GUI designs on Dribbble. By analyzing the existing tags, we find that users adopt incoherent tags with a large inconsistent vocabulary according to their own preferences. But some frequently used tags which convey the main semantic of the GUI design images emerge including tags related to the GUI platform, color, software functionality, screen functionality, screen layout, etc. Interviews with professional designers (UI design creators and uses of design sharing sites) from big companies also confirm the tag usage issues (i.e., inconsistency, tag missing). Considering the wide range of missing tags, it would require significant manual effort to develop a complete set of rules for guiding collaborative tagging. This challenge motivates us to develop a deep-learning based tag completeness assurance janitor to recommend to design owners or other users the potential missing tags that may be needed to augment existing tags. This janitor can also justify its prediction by pointing out the specific part of GUI designs relevant to the predicted tags. \begin{comment} These two problems can severely degrade the performance of the tagging-based UI design search. To solve these two problems, this paper presents an automated approach for recommending tags for both existing and new UI designs, leading to efficient retrieval of related UI design. We first construct a vocabulary of UI semantics by analyzing the existing tags for UI deign in Dribbble~\cite{web:dribble}. The vocabulary not only contains the high-level tag semantic category, but also merge tag abbreviations and synonyms into groups. Based on the vocabulary, we further develop a deep-learning model to automatically recover the missing tags to the UI design. To construct the vocabulary of UI semantics, we collected 61,700 UI designs from Dribbble. First, we carry out an empirical study about what tags designer use to annotate their UI design. Second, we group all UI-related tags into 5 major categories including the platform (e.g., \textit{mobile, website}), color (e.g., \textit{black, blue}), app functionality (e.g., \textit{music, game}), screen functionality (e.g., \textit{login, payment}), and screen layout (e.g., \textit{form, list}). As users may use different tags for the same meaning, we propose an unsupervised method to extract all morphological forms including abbreviations, synonyms and even misspellings. Through this iterative process and following manual check, we identify 369 abbreviations and 5646 synonyms and misspellings for the most frequent UI related tags. \end{comment} To recommend missing tags for UIs, we employ a hybrid approach that leverages both the visual and textual information. We train a binary classifier with UI design images from Dribbble labeled with this tag as positive data, while UI design images labeled with other tags in the same category as negative data. The trained model can help recommend tags for not only the new UI designs before sharing, but also remind designers about adding more tags for existing UI designs. The experiments demonstrate that our model with the average accuracy as 0.8272 significantly outperforms the other machine learning based models. To demonstrate the usefulness of our model, we also carry out a user study to show if our model for recovering missing tags can help retrieve more related UI designs compared with the default Dribbble search. After analyzing ten participants' feedback, we find that our model can provide more related and larger number of UI candidates given the queries than the baselines. The contributions of this work are threefold. \begin{itemize} \item We systematically investigate the collaborative tagging problems of the design sharing site including incoherent tag usage and missing tags. The informal interviews with professional designers also confirm these issues qualitatively. \item Based on the emerging tag categories, we develop a customized deep-learning based method for specifically recommending missing semantic tags to the existing design by leveraging both visual and textual information according to the UI design characteristics. We have released the source code, experiment results, and tag categorization to the public\footnote{\url{https://github.com/UITagPrediction/CSCW2020}} for replication and further extension. \item We conduct large-scale experiments to evaluate the performance and limitations of our approach. Our approach achieves good accuracy compared with baselines on a large-scale UI design dataset. The evaluation of our method for improving searching performance also demonstrates the usefulness of our model \end{itemize} \section{Information Needs Beyond Design Sharing} We interviewed four professional UI designers, including one interaction designers and one visual designer from Google, and the other two visual designers from Huawei. These designers acknowledge that they regularly (at least once weekly) visit design sharing websites like Dribbble. They appreciate the creativity and aesthetics of high-quality UI design artworks on Dribbble, which inspire their own design work. However, they also pinpoint several information needs in their work which demand us to think beyond existing content sharing mechanisms. First, as the contributors of Dribbble site, some designers do not pay much attention to their tagging, though it is crucial for the GUI index and searching. One designer from Huawei mentioned us that he did not intentionally use the semantic words (e.g., functionality, layout) to annotate his design works, as he did not know much what tags are there and which tags to use. Instead, he attached his UI design with some fancy tags like ``2019trending'' to make his design more attractive to other designers. A structured vocabulary of available tags is needed to assist designers in efficiently annotating their design works for other designers' retrieval. Second, there is a gap between existing UI tags and the query due to two reasons. On the one hand, some UIs are missing important semantic tags. For example, one Google designer was designing a website about Yoga. When she searched ``yoga``, there are many different kinds of returning results from Dribbble including the icons, charts, illustration which are not related to her designed UI or website. She had to manually filter out irrelevant ones, and that process took much time. But when she zoomed into a more specific query like ``yoga website``, only very few results were returned by Dribble. On the other hand, designers may adopt different words to tag the same GUI, resulting in the difficulty of retrieval. Another designer in Google mentioned that he would use different words in the same meaning for searching such as both ``travel`` and ``trip`` for related GUI, but that process is inefficient as many results from two queries overlap, and he may miss some potential synonyms. Some effective mechanism have to be devised to help retrieve more results by not only adding more semantic tags to the GUI design, but also organizing existing tags. \section{Related Works} Our work is problem driven, rather than approach driven. As our study is to recommend missing tags for UI design images, we are introducing related works in three aspects, i.e., works for helping UI design, collaborative tagging and tag prediction. \subsection{UI Design} GUI provides a visual bridge between apps and users through which they can interact with each other. To assist the mobile UI design, many studies are working on large-scale design mining including investigating the UI design patterns~\cite{alharbi2015collect}, color evolution~\cite{jahanian2017colors, jahanian2017mining}, UI design testing including usability~\cite{zhao2020seenomaly, liu2020owl} and accessibility~{chen2020unblind}, UI decomposition~\cite{chen2020object} and design implementation~\cite{chen2018ui}. Liu et al~\cite{liu2018learning} follow the design rules from Material Design to annotate the mobile GUI design to represent its semantics. Swearngin et al~\cite{swearngin2018rewire} adopt the image processing method to help designs with converting the mobile UI screenshots into editable files in Photoshop, so that designers can take it as a starting point for further customization. To render inspirations to the designer, Chen et al~\cite{chen2019storyboard} propose a program-analysis method to efficiently generate the storyboard with UI screenshots, given one app executable file. Fischer et al~\cite{fischerimaginenet} transfer the style from fine art to GUI. All of these works are helping simplify the design process for professional design. In contrast, our study is to assist with searching the existing UI design to render designers some inspirations. Retrieval-based methods~\cite{chen2019gallery, chen2020wireframe} are also used to develop user interfaces. Reiss~\cite{reiss2018seeking} parses developers' sketch into structured queries to search related UIs of Java-based desktop software in the database. GUIfetch~\cite{behrang2018guifetch} customizes Reiss's method~\cite{reiss2018seeking} into the Android app UI search by considering the transitions between UIs. Deka et al~\cite{deka2017rico} leverage auto-encoder to support UI searching by inputting the rough sketch. Similar to Reiss's work~\cite{reiss2018seeking}, Zheng et al~\cite{zheng2019faceoff} parse the DOM tree of one user-created rough website to locate similar well-designed websites by measuring tree distance. Note that all of these works either take the wireframe/sketch or partial source code as the input for searching the UI design. Different from them, we are annotating UI design with high-level natural-language semantic tags which can help textual queries for UI design retrieval. \subsection{Collaborative Tagging System} Tagging is to summarize the content with several compact keywords~\cite{golder2006usage, macgregor2006collaborative} and collaborative tagging allows individual users to create and apply tags to online items. Collaborative tagging systems are widely adopted by different sharing sites including Q\&A (e.g., Quora~\cite{web:quora}), picture sharing (e.g., Flickr~\cite{web:flickr}), web bookmarking sharing (e.g., Delicious~\cite{web:delicious}), etc. Instead of central authority, collaborative tagging systems constitute an entirely new method of information organization, which allows the entire community to generate tags and label content, typically to make the content easier for themselves or others to find later. Creating and applying tags in order to organize content requires the cognitive process of categorization~\cite{fu2008microstructures, fu2010semantic}. Although tags provide a way for sites to organize and for users to search the content, there are still some problems with it. So many research works have aimed to study on human tagging behavior. For example, Suchanek et al~\cite{suchanek2008social} examine whether tags are applied accurately by humans. Multiple empirical studies~\cite{golder2006usage, halpin2007complex, wetzker2010tag} conduct to evaluate human categorization consistency. Fu et al~\cite{fu2010semantic} study on whether users are influenced by others' tags. The conflict and divisions in collaborative tagging have been further spotted~\cite{choi2018will}. The empirical study in our work also confirms those tagging issues in design sharing sites. But different from existing works which mostly focus on the empirical study of such phenomenon, we further develop a method to help recover the missing tags and keep the consistency of tags across the site. Categorization of tags can analogously facilitate navigation and searching in the now-booming collaborative tagging system. A number of papers deal with exploring plenty of tag type categories for online resources of different kinds, such as book~\cite{golder2006usage}, movie~\cite{sen2006tagging}, TV program~\cite{melenhorst2007usefulness}, music~\cite{bischoff2008can}, blog~\cite{li2017types}. To the best of our knowledge, our work is the first to build a UI tag categorization using data mining and semi-automatic techniques. \begin{comment} To extend the prior works, our research aims to enable users to collaborate tagging systems on pictures, especially on GUI design. If the user apply a tag to an entity, then this entity is assumed to form a group with other entities with the same tag, in other words, they become a category. Recent works have aimed to study on human categorization. This includes Suchanek et al~\cite{suchanek2008social} examines whether tags are applied accurately by human; multiple empirical studies~\cite{golder2006usage, halpin2007complex, wetzker2010tag} conduct to evaluate on human categorization consistency; and the Fu et al~\cite{fu2010semantic} studies on whether users are influenced by others’ tags. While these studies show the effectiveness of human categorization, our study here focuses on automatic categorization, in which we automatically group ideas and objects together based on shared characteristics (i.e., visual and textual characteristics). \end{comment} \subsection{Tagging Prediction} Automatic image annotation (also known as automatic image tagging or linguistic indexing) is the process by which a computer system automatically assigns metadata in the form of captioning or keywords to a digital image~\cite{web:imageAnnotation}. Most work has focused on personalized tag recommendation, suggesting tags to the user, bookmarking a new resource using collaborative filtering, taking into account similarities between users and tags~\cite{mishne2006autotag, xu2006towards, tso2008tag, liang2008collaborative}. As pointed out in~\cite{eom2011improving} that the visual content of images are a valuable information source, some researchers propose conventional machine learning methods for tag recommendation based on manually-crafted features~\cite{sigurbjornsson2008flickr, chen2013fast, kalayeh2014nmf}. \begin{comment} For example, Mishne ~\cite{mishne2006autotag} introduced an approach to recommend tags for weblogs, based on similar weblogs tagged by the same user. Xu et al.~\cite{xu2006towards} proposed a TF-IDF based method for collaborative tag suggestion that takes into account the reputation of users and a number of criteria for good tags, including high coverage, high popularity, least effort, and uniformity. Tso-Sutter et al.~\cite{tso2008tag} proposed a collaborative filtering tag-recommendation algorithm by integrating user and tag information. Liang et al.~\cite{liang2008collaborative} realized this idea for UI designs retrieval, recommending tags by using three derived user-item, user-tag and tag-item sub matrixes. \end{comment} Apart from the image, the text attached to the image (e.g., existing tags) may be another resource for tag recommendation. Murthy et al.~\cite{murthy2015automatic} explored a k-nearest-neighbor-based canonical correlation analysis (CCA) method for tag recommendation, which not only utilizes the convolutional neural network visual features but also explicitly incorporates the word embedding semantic information. Ma et al.~\cite{ma2017image} proposed a joint visual-semantic propagation model to the tag image and introduced a visual-guided LSTM to capture the co-occurrence relation of the tags. Bylinskii et al.~\cite{bylinskii2017understanding} recommended tags for infographics by adopting patch learning to select representative textual and visual elements from an infographic. Rawat et al.~\cite{rawat2016contagnet} proposed a context-aware model to integrate context information with image content for multi-label hashtag prediction. But note that different from prior works about tag recommendations for natural images on social-media platforms (e.g., Flickr), we are specifically targeting at uncovering semantic tags of UI design images for assisting designers in effectively seeking others' UI design. Inspired by the existing works on tag recommendation, we customize the off-the-shelf model for modeling both visual and textual information in three aspects. First, we adopt binary classifiers to boost the performance of the classification model. Previous works formulating this tag-recommendation problem as a multi-class multi-label classification task, but it always leads to data imbalance issues~\cite{liu2019synthetic} as the occurrence number of each tag differs significantly. Instead, according to our observation, most related (frequent) tags attached to the UI design are exclusive with each other, such as ``black vs red'', ``login page vs checkout page'', ``music app vs sport app''. Therefore, we develop a novel binary classifier for each tag and that method naturally solves the problem of data sparsity and imbalance. Second, to support the construction of binary classifiers, we carry out an empirical study of existing tags of 61,700 UI designs for distilling exclusive tags. Based on a series of methods including association rule mining and merging abbreviations and synonyms, we obtain a categorization of most frequent UI-related tags. Tags within the same category are exclusive from each other, enabling the consecutive construction of binary classifiers. Third, we also develop a data visualization method to help designers understand why we recommend certain tags for their UI designs. For each recommended tag, we draw a saliency map highlighting the conclusive features captured by our model. Compared with just a simple prediction, this explainability can help post owners or post editors judge the validity of the recommended post edits and may encourage them to accept the tool's recommendation. Making the prediction criteria more explicit is crucial for the acceptance of our deep learning based approach for tag recommendation. \begin{comment} Compared with these works, our work has two novelty. First, these research works have formulated tag recommendation as a multi-class multi-label classification task. Different from these works, we formulate it as a binary classification problem for each tag. This method can avoid two problems which frequently appear in previous works. First, the multi-class task always faces the data-unbalance problem i.e., the training data size for each class may vary significantly. Second, the multi-label task cannot specify the detailed number of assigned labels to one image i.e., one UI design image may be assigned 2 or 10 tags. To solve these two problems, instead of training one complex multi-class multi-label classifier, we propose to train a relatively simpler binary classifier for each tag. Second, these research works have focused on natural images, infographics, posters. In contrast, our target is to recommend tags for UI designs. Compared with natural images such as that from Flickr~\cite{web:flickr}, Facebook~\cite{web:facebook}, UI designs are artificial and created by human, leading to the needs of domain-specific data for the training. Different from infographic, poster which is a collection of imagery, charts, and text that gives an overview of a topic, UI design is designed to be easy to use and pleasant, with less information. In other words, UI design is hard to train??? As far as we know, our work is the first deep learning attempt to recommend tags for UI designs. Furthermore, our work identifies UI tag recommendation as a binary classification task, a simple but efficient way to overcome the fundamental limitations in prior works of using multi-class multi-label classification. \end{comment} \section{Modifications} \begin{acks} We appreciate the initial exploration by Ruiqi Wang of this work. This project is partially supported by Facebook gift funding and ANU-Data61 Collaborative Research Project CO19314. \end{acks} \bibliographystyle{ACM-Reference-Format} \section{Retrieval Evaluation} The experiments in the last section demonstrate the accuracy of our model. We conduct a pilot user study in this section to further evaluate the usefulness of the predicted addition tags for bootstrapping the UI design retrieval. \subsection{Procedures for User Study} The number of words in each query is 2.35 on average, according to an analysis of an AltaVista search engine query log for almost 1 billion search requests from approximately 285 million users over six weeks~\cite{silverstein1999analysis}. Therefore, based on the five main categories of tags in Table~\ref{tab:tagCategory}, we randomly selected three tags from three categories respectively as the query. To mimic the real queries from designers, the query contains one platform tag and two tags from the other two random categories. We obtain 5 queries as seen in Table~\ref{tab:query}. We set up two groups for each query, i.e., control group and experimental group. The query database contains 61,700 UI designs collected from Section~\ref{sec:empiricalStudy}. For the control group, we directly retrieved the UI without tag augmentation in the database, which is regarded as a baseline for comparison. For experimental group, we searched the UI design database in which UI tags have been normalized by using the extracted abbreviations and synonyms in Section~\ref{sec:tagNormalization} and complemented with additional predicted tags as described in Section~\ref{sec:tagAugmentation}. Note that the UI can only be retrieved if it contains all keywords in the query. As there may be too many results from the experimental group (as seen in Table~\ref{tab:query}), we randomly take 10, 30, 50 retrieval candidates as the experimental groups so that it is fair to compare with the control group. We recruit 10 Master and final-year Bachelor students from our school, and each of them is assigned the results of five queries from one control group and three experimental groups. Note that they do not know which result is from the experimental or control group. Given each query, they individually mark each result as related to the query or not and for each query, we will randomly shuffle the order of candidates to avoid potential bias. After marking results for each query, they are asked to rate how satisfied they are with the retrieval results in a five-point likert scale (1: not satisfied at all and 5:highly satisfied), and how diverse also in five-point likert scale. \begin{comment} We conducted 30 semi-structured interviews with Master and final-year Bachelor students from April 2020 to May 2020. Two authors first developed the interview protocol, and conducted pilot studies with three participants. Based on the pilot studies, they refined the interview protocol and conducted 10 interviews formally. We recruited interviewees through direct contact and snowball sampling. All interviewees were participated voluntarily without compensation. To mimic the real queries from designers, the query contains one platform tag and two tags from the other two random categories. We set up two groups for each query, control group and experimental group. For control group, we directly retrieved the UI without tag augmentation in the database, which regards as a baseline for comparison. For the experimental group, we searched the UI design database including 61,700 UI designs whose tags have been normalized by using the extracted abbreviations and synonyms in Section~\ref{sec:tagNormalization} and complemented with additional predicted tags as described in Section~\ref{sec:tagAugmentation}. Note that the UI can only be retrieved if it contains all keywords in the query. As there may be too many results from the experimental group (as seen in Table~\ref{tab:query}), we randomly take 10, 30, 50 retrieval results as the experimental groups. From the pilot studies, we discovered that the number of tags from the UI design has significant impact to user evaluation. To guarantee the participants can objectively mark the result, we did not show any information except the query (such as tags, title, description, etc. ). The interviews were conducted through those five queries. For each query, we provided the interviewees two groups of results, the control group and one experimental group (i.e., 10, 30, 50). To be fair, interviewees did not know which one is from the experimental or control group and we also randomized before being presented to them for evaluation. We first asked them to evaluate each result in five-point likert scale (1: strongly related to the query and 5:strongly unrelated). We then asked them to rate the overall results for both groups, in terms of satisfaction and diversity. \end{comment} \begin{comment} For each query, we first search the collected database including 61,700 UI designs with original tags (control group). Then we also search the UI design database obtained by tag normalization as described in Section~\ref{sec:tagNormalization}) and tag \textcolor{red}{complementation ??this word seems to be used only for Genetics. maybe just tag augmentation} from our classifiers as described in Section~\ref{sec:tagPrediction} (experimental group). We recruit six Master and final-year Bachelor students from our school with \textcolor{red}{at least one-year experience about software UI design and implementation ??what does one-year experience mean? i do not think participants must have UI experience for this study}. Each of them is assigned the results of five queries from the control group and experimental group, and they do not know which one is from experimental or control group. They will individually mark each result as related to the query or not. Note that we have retrieved too many results from the \textcolor{red}{control group ??experimental group?}, so we only randomly take 50 of them for manual checking. After marking results for each query, they are asked to rate how satisfied they are with the retrieval results in five-point likert scale (1: not satisfied at all and 5:highly satisfied). \end{comment} \begin{table*} \caption{The random queries for searching UI designs} \vspace{-3mm} \label{tab:query} \begin{tabular}{llcc} \toprule \bf{ID} & \bf{Query} &\textbf{\#UI (control group)} & \textbf{\#UI (experimental)}\\ \midrule 1 & iphone+e-commerce+checkout & 3 & 604 \\ 2 & mobile+food\&drink+listview & 4 & 510\\ 3 & website+blue+landing page & 9 & 1838\\ 4 & ios+finance+chart & 4 & 1018\\ 5 & web+sign up+form & 10 & 440\\ \bottomrule \end{tabular} \end{table*} \begin{table*} \caption{The comparison of the experiment and control groups. $^*$denotes $p<$ 0.01, $^{**}$denotes $p<$ 0.05.} \vspace{-3mm} \label{tab:score_Tabel} \begin{tabular}{lcccc} \toprule \textbf{Measures} & \textbf{Control} & \textbf{Experiment 10} & \textbf{Experiment 30} & \textbf{Experiment 50}\\ \midrule \#Related Candidate & 3.2/6 (53.3\%) & 7.5/10 (75.6\%)$^{**}$ & 25.2/30 (84.1\%)$^*$ & 45/50 (90\%)$^*$\\ Satisfaction score & 2.8 & 3.56$^{**}$ & 4.28$^{**}$ & 4.8$^*$\\ Diversity score & 2.22 & 2.68$^*$ & 4.16$^*$ & 4.7$^*$\\ \bottomrule \end{tabular} \vspace{-3mm} \end{table*} \subsection{Results of Retrieval Effectiveness} Table~\ref{tab:score_Tabel} shows that the experimental group retrieves many more related candidates than the control group in both the absolute the number and relative percentage (75.6\%, 84.1\%, 90\% compared with 53.3\%). That is the biggest strength of our approach i.e., recovering the missing tags, resulting in more relevant UI designs given the query. Compared with the baseline, most participants admit that our method can provide more satisfactory and diverse results for them to choose from. And with the increase of the candidate number in the experimental group, participants give higher satisfaction and diversity scores (3.56, 4.28, 4.8 in satisfaction score, and 2.68, 4.16, 4.7 in diversity score) which are significantly higher than that (2.8, 2.22) of the control group. It is consistent with human perception, as more results lead to a higher possibility to see the serendipitous idea. The detailed results can be seen in our site\footnote{\url{https://sites.google.com/view/uitagpredictionuserstudy/home}}. \begin{comment} On average, the overall satisfaction ratings for the experiment group is 4.21, which is 89.6\% higher than the control group (2.22) in Table~\ref{tab:score_Tabel}. In contrast, the baseline can only achieve the average diversity score as 2.5. Experiment 10 is the most comparable group to control group as most of the control group can only retrieve less or equal to 10 results. Our experiment 10 can still achieve better user experience than control group in all of three measurements. As more results are retrieved (Experiment 30 and 50), we achieve higher satisfaction and diversity. Circling back to Table ~\ref{tab:query}, we reliably believe that our method can surpass control group by a large margin. \end{comment} To understand the significance of such differences, we carry out the Mann-Whitney U test~\cite{fay2010wilcoxon} (specifically designed for small samples) on the number of useful candidate, satisfactory, and diversity ratings between the experiment and the control group respectively. The test results suggest that our method does significantly outperform the baseline in terms of these metrics with $p < 0.01$ or $p < 0.05$. Although by no means conclusive, this user study provides initial evidence of the usefulness of our method for enhancing the performance of the tagging-based search. \begin{comment} \subsection{Results of Retrieval Effectiveness} Box plot in Figure~\ref{fig:user_study_evaluation} shows that the experimental group retrieves many more related candidates than the control group (with an average of 45 designs versus 3.24 designs for five queries). On average, the overall satisfaction ratings for the experiment group is 4.8, which is 71.4\% higher than the control group (2.8) in Table~\ref{tab:score_Tabel}. Most participants admit that our method can provide more diverse results for them to choose. In contrast, the baseline can only achieve the diversity score as 2.2. The detailed results can be seen on our site\footnote{\url{https://sites.google.com/view/userstudy/user-study-results}}. To understand the significance of the differences, we carry out the Mann-Whitney U test~\cite{fay2010wilcoxon} (specifically designed for small samples) on the number of useful candidate, satisfactory, and diversity ratings between the experiment and the control group respectively. The test results suggest that our method does significantly outperform the baseline in terms of these metrics with $p < 0.01$. Although by no means conclusive, this user study provides initial evidence of the usefulness of our method for enhancing the performance of the tagging-based search. \end{comment}
{'timestamp': '2020-10-06T02:09:39', 'yymm': '2008', 'arxiv_id': '2008.06895', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06895'}
arxiv
\section{Introduction} Please follow the steps outlined below when submitting your manuscript to the IEEE Computer Society Press. This style guide now has several important modifications (for example, you are no longer warned against the use of sticky tape to attach your artwork to the paper), so all authors should read this new version. \subsection{Language} All manuscripts must be in English. \subsection{Dual submission} Please refer to the author guidelines on the WACV 2021 web page (\url{http://wacv2021.thecvf.com/submission/}) for a discussion of the policy on dual submissions. \subsection{Paper length} Papers, excluding the references section, must be no longer than eight pages in length. The references section will not be included in the page count, and there is no limit on the length of the references section. For example, a paper of eight pages with two pages of references would have a total length of 10 pages. {\bf There will be no extra page charges for WACV 2021.} Overlength papers will simply not be reviewed. This includes papers where the margins and formatting are deemed to have been significantly altered from those laid down by this style guide. Note that this \LaTeX\ guide already sets figure captions and references in a smaller font. The reason such papers will not be reviewed is that there is no provision for supervised revisions of manuscripts. The reviewing process cannot determine the suitability of the paper for presentation in eight pages if it is reviewed in eleven. \subsection{The ruler} The \LaTeX\ style defines a printed ruler which should be present in the version submitted for review. The ruler is provided in order that reviewers may comment on particular lines in the paper without circumlocution. If you are preparing a document using a non-\LaTeX\ document preparation system, please arrange for an equivalent ruler to appear on the final output pages. The presence or absence of the ruler should not change the appearance of any other content on the page. The camera ready copy should not contain a ruler. (\LaTeX\ users may uncomment the \verb'\wacvfinalcopy' command in the document preamble.) Reviewers: note that the ruler measurements do not align well with lines in the paper --- this turns out to be very difficult to do well when the paper contains many figures and equations, and, when done, looks ugly. Just use fractional references (e.g.\ this line is $087.5$), although in most cases one would expect that the approximate location will be adequate. \subsection{Mathematics} Please number all of your sections and displayed equations. It is important for readers to be able to refer to any particular equation. Just because you didn't refer to it in the text doesn't mean some future reader might not need to refer to it. It is cumbersome to have to use circumlocutions like ``the equation second from the top of page 3 column 1''. (Note that the ruler will not be present in the final copy, so is not an alternative to equation numbers). All authors will benefit from reading Mermin's description of how to write mathematics: \url{http://www.pamitc.org/documents/mermin.pdf}. \subsection{Blind review} Many authors misunderstand the concept of anonymizing for blind review. Blind review does not mean that one must remove citations to one's own work---in fact it is often impossible to review a paper unless the previous citations are known and available. Blind review means that you do not use the words ``my'' or ``our'' when citing previous work. That is all. (But see below for techreports.) Saying ``this builds on the work of Lucy Smith [1]'' does not say that you are Lucy Smith; it says that you are building on her work. If you are Smith and Jones, do not say ``as we show in [7]'', say ``as Smith and Jones show in [7]'' and at the end of the paper, include reference 7 as you would any other cited work. An example of a bad paper just asking to be rejected: \begin{quote} \begin{center} An analysis of the frobnicatable foo filter. \end{center} In this paper we present a performance analysis of our previous paper [1], and show it to be inferior to all previously known methods. Why the previous paper was accepted without this analysis is beyond me. [1] Removed for blind review \end{quote} An example of an acceptable paper: \begin{quote} \begin{center} An analysis of the frobnicatable foo filter. \end{center} In this paper we present a performance analysis of the paper of Smith \etal [1], and show it to be inferior to all previously known methods. Why the previous paper was accepted without this analysis is beyond me. [1] Smith, L and Jones, C. ``The frobnicatable foo filter, a fundamental contribution to human knowledge''. Nature 381(12), 1-213. \end{quote} If you are making a submission to another conference at the same time, which covers similar or overlapping material, you may need to refer to that submission in order to explain the differences, just as you would if you had previously published related work. In such cases, include the anonymized parallel submission~\cite{Authors20} as additional material and cite it as \begin{quote} [1] Authors. ``The frobnicatable foo filter'', F\&G 2020 Submission ID 324, Supplied as additional material {\tt fg324.pdf}. \end{quote} Finally, you may feel you need to tell the reader that more details can be found elsewhere, and refer them to a technical report. For conference submissions, the paper must stand on its own, and not {\em require} the reviewer to go to a techreport for further details. Thus, you may say in the body of the paper ``further details may be found in~\cite{Authors20b}''. Then submit the techreport as additional material. Again, you may not assume the reviewers will read this material. Sometimes your paper is about a problem which you tested using a tool which is widely known to be restricted to a single institution. For example, let's say it's 1969, you have solved a key problem on the Apollo lander, and you believe that the WACV 70 audience would like to hear about your solution. The work is a development of your celebrated 1968 paper entitled ``Zero-g frobnication: How being the only people in the world with access to the Apollo lander source code makes us a wow at parties'', by Zeus \etal. You can handle this paper like any other. Don't write ``We show how to improve our previous work [Anonymous, 1968]. This time we tested the algorithm on a lunar lander [name of lander removed for blind review]''. That would be silly, and would immediately identify the authors. Instead write the following: \begin{quotation} \noindent We describe a system for zero-g frobnication. This system is new because it handles the following cases: A, B. Previous systems [Zeus et al. 1968] didn't handle case B properly. Ours handles it by including a foo term in the bar integral. ... The proposed system was integrated with the Apollo lunar lander, and went all the way to the moon, don't you know. It displayed the following behaviours which show how well we solved cases A and B: ... \end{quotation} As you can see, the above text follows standard scientific convention, reads better than the first version, and does not explicitly name you as the authors. A reviewer might think it likely that the new paper was written by Zeus \etal, but cannot make any decision based on that guess. He or she would have to be sure that no other authors could have been contracted to solve problem B. \medskip \noindent FAQ\medskip\\ {\bf Q:} Are acknowledgements OK?\\ {\bf A:} No. Leave them for the final copy.\medskip\\ {\bf Q:} How do I cite my results reported in open challenges? {\bf A:} To conform with the double blind review policy, you can report results of other challenge participants together with your results in your paper. For your results, however, you should not identify yourself and should not mention your participation in the challenge. Instead present your results referring to the method proposed in your paper and draw conclusions based on the experimental comparison to other results.\medskip\\ \begin{figure}[t] \begin{center} \fbox{\rule{0pt}{2in} \rule{0.9\linewidth}{0pt}} \end{center} \caption{Example of caption. It is set in Roman so that mathematics (always set in Roman: $B \sin A = A \sin B$) may be included without an ugly clash.} \label{fig:long} \label{fig:onecol} \end{figure} \subsection{Miscellaneous} \noindent Compare the following:\\ \begin{tabular}{ll} \verb'$conf_a$' & $conf_a$ \\ \verb'$\mathit{conf}_a$' & $\mathit{conf}_a$ \end{tabular}\\ See The \TeX book, p165. The space after \eg, meaning ``for example'', should not be a sentence-ending space. So \eg is correct, {\em e.g.} is not. The provided \verb'\eg' macro takes care of this. When citing a multi-author paper, you may save space by using ``et alia'', shortened to ``\etal'' (not ``{\em et.\ al.}'' as ``{\em et}'' is a complete word.) However, use it only when there are three or more authors. Thus, the following is correct: `` Frobnication has been trendy lately. It was introduced by Alpher~\cite{Alpher02}, and subsequently developed by Alpher and Fotheringham-Smythe~\cite{Alpher03}, and Alpher \etal~\cite{Alpher04}.'' This is incorrect: ``... subsequently developed by Alpher \etal~\cite{Alpher03} ...'' because reference~\cite{Alpher03} has just two authors. If you use the \verb'\etal' macro provided, then you need not worry about double periods when used at the end of a sentence as in Alpher \etal. For this citation style, keep multiple citations in numerical (not chronological) order, so prefer \cite{Alpher03,Alpher02,Authors20} to \cite{Alpher02,Alpher03,Authors20}. \begin{figure*} \begin{center} \fbox{\rule{0pt}{2in} \rule{.9\linewidth}{0pt}} \end{center} \caption{Example of a short caption, which should be centered.} \label{fig:short} \end{figure*} \section{Formatting your paper} All text must be in a two-column format. The total allowable width of the text area is $6\frac78$ inches (17.5 cm) wide by $8\frac78$ inches (22.54 cm) high. Columns are to be $3\frac14$ inches (8.25 cm) wide, with a $\frac{5}{16}$ inch (0.8 cm) space between them. The main title (on the first page) should begin 1.0 inch (2.54 cm) from the top edge of the page. The second and following pages should begin 1.0 inch (2.54 cm) from the top edge. On all pages, the bottom margin should be 1-1/8 inches (2.86 cm) from the bottom edge of the page for $8.5 \times 11$-inch paper; for A4 paper, approximately 1-5/8 inches (4.13 cm) from the bottom edge of the page. \subsection{Margins and page numbering} All printed material, including text, illustrations, and charts, must be kept within a print area 6-7/8 inches (17.5 cm) wide by 8-7/8 inches (22.54 cm) high. Page numbers should be in footer with page numbers, centered and .75 inches from the bottom of the page and make it start at the correct page number rather than the 9876 in the example. To do this find the secounter line (around line 33 in this file) and update the page number as \begin{verbatim} \setcounter{page}{123} \end{verbatim} where the number 123 is your assigned starting page. \subsection{Type-style and fonts} Wherever Times is specified, Times Roman may also be used. If neither is available on your word processor, please use the font closest in appearance to Times to which you have access. MAIN TITLE. Center the title 1-3/8 inches (3.49 cm) from the top edge of the first page. The title should be in Times 14-point, boldface type. Capitalize the first letter of nouns, pronouns, verbs, adjectives, and adverbs; do not capitalize articles, coordinate conjunctions, or prepositions (unless the title begins with such a word). Leave two blank lines after the title. AUTHOR NAME(s) and AFFILIATION(s) are to be centered beneath the title and printed in Times 12-point, non-boldface type. This information is to be followed by two blank lines. The ABSTRACT and MAIN TEXT are to be in a two-column format. MAIN TEXT. Type main text in 10-point Times, single-spaced. Do NOT use double-spacing. All paragraphs should be indented 1 pica (approx. 1/6 inch or 0.422 cm). Make sure your text is fully justified---that is, flush left and flush right. Please do not place any additional blank lines between paragraphs. Figure and table captions should be 9-point Roman type as in Figures~\ref{fig:onecol} and~\ref{fig:short}. Short captions should be centred. \noindent Callouts should be 9-point Helvetica, non-boldface type. Initially capitalize only the first word of section titles and first-, second-, and third-order headings. FIRST-ORDER HEADINGS. (For example, {\large \bf 1. Introduction}) should be Times 12-point boldface, initially capitalized, flush left, with one blank line before, and one blank line after. SECOND-ORDER HEADINGS. (For example, { \bf 1.1. Database elements}) should be Times 11-point boldface, initially capitalized, flush left, with one blank line before, and one after. If you require a third-order heading (we discourage it), use 10-point Times, boldface, initially capitalized, flush left, preceded by one blank line, followed by a period and your text on the same line. \subsection{Footnotes} Please use footnotes\footnote {This is what a footnote looks like. It often distracts the reader from the main flow of the argument.} sparingly. Indeed, try to avoid footnotes altogether and include necessary peripheral observations in the text (within parentheses, if you prefer, as in this sentence). If you wish to use a footnote, place it at the bottom of the column on the page on which it is referenced. Use Times 8-point type, single-spaced. \subsection{References} List and number all bibliographical references in 9-point Times, single-spaced, at the end of your paper. When referenced in the text, enclose the citation number in square brackets, for example~\cite{Authors20}. Where appropriate, include the name(s) of editors of referenced books. \begin{table} \begin{center} \begin{tabular}{|l|c|} \hline Method & Frobnability \\ \hline\hline Theirs & Frumpy \\ Yours & Frobbly \\ Ours & Makes one's heart Frob\\ \hline \end{tabular} \end{center} \caption{Results. Ours is better.} \end{table} \subsection{Illustrations, graphs, and photographs} All graphics should be centered. Please ensure that any point you wish to make is resolvable in a printed copy of the paper. Resize fonts in figures to match the font in the body text, and choose line widths which render effectively in print. Many readers (and reviewers), even of an electronic copy, will choose to print your paper in order to read it. You cannot insist that they do otherwise, and therefore must not assume that they can zoom in to see tiny details on a graphic. When placing figures in \LaTeX, it's almost always best to use \verb+\includegraphics+, and to specify the figure width as a multiple of the line width as in the example below {\small\begin{verbatim} \usepackage[dvips]{graphicx} ... \includegraphics[width=0.8\linewidth] {myfile.eps} \end{verbatim} } \subsection{Color} Please refer to the author guidelines on the WACV 2021 web page (\url{http://wacv2021.thecvf.com/submission/}) for a discussion of the use of color in your document. \section{Final copy} You must include your signed IEEE copyright release form when you submit your finished paper. We MUST have this form before your paper can be published in the proceedings. Please direct any questions to the production editor in charge of these proceedings at the IEEE Computer Society Press: \url{https://www.computer.org/about/contact}. {\small \bibliographystyle{ieee_fullname} \section{Introduction} \begin{figure*}[t] \begin{center} \includegraphics[clip,width=\textwidth]{figure1.png} \end{center} \caption{\textit{SMPLpix Neural Rendering Pipeline.} Training SMPLpix requires a set of 3D vertices with the corresponding RGB colors as input $X^+$, along with ground truth camera parameters $(\mathbf{K}, \mathbf{R}, \mathbf{t})$. Our training data is obtained by registering a SMPL model to 3D scans. Using SMPL also allows us to control the coordinates of $X^+$ via a small set of pose parameters $\theta$. RGB-d training images are created by projecting the vertices, $X^+$ onto an image plane using a camera model. This image is then fed into a UNet-type network that reconstructs surfaces from projected vertices \emph{directly in the pixel space}. It is trained to minimize a combination of perceptual and adversarial losses w.r.t.~the ground truth image. Once trained, this neural rendering module generalizes to unseen subjects $X^+$, body poses $\theta$ and camera parameters $(\mathbf{K}, \mathbf{R}, \mathbf{t})$. } \label{fig:fig1} \vspace{-5mm} \end{figure*} Traditional graphics pipelines for human body and face synthesis benefit from explicit, parameterized, editable representations of 3D shape and the ability to control pose, lighting, material properties, and the camera, to animate 3D models in 3D scenes. While photorealism is possible with classical methods, this typically comes at the expense of complex systems to capture detailed shape and reflectance or heavy animator input. In contrast, recent developments in deep learning and the evolution of graphics processing units are rapidly bringing new tools for human modeling, animation and synthesis. Models based on generative adversarial networks \cite{goodfellow2014generative} reach new levels of realism in synthesizing human faces \cite{karras2019style,karras2019analyzing} and various models can repose humans \cite{chan2019everybody}, swap identities and appearance, etc. While promising, particularly in terms of their realism, these new ``neural" approaches to synthesizing humans have several drawbacks relative to classical methods. Specifically, a key advantage of classical graphics methods \cite{pharr2016physically} is the ability to fully and flexibly control the generative process, e.g. change the camera view, the light or even the pose or shape of the subject. These methods, however, have two main limitations relative to learning-based image synthesis. First, until recently \cite{kato2018neural,liu2019soft}, rendering engines were not fully integrated into deep learning pipelines. Second, explicit mesh-based rendering methods are limited when it comes to rendering complex, high-frequency geometry (e.g. hair or fur, wrinkles on clothing, etc.) and dealing with complex, changing, topology. The future of graphics is likely a synthesis of classical and neural models, combining the best properties of both. Here we make a step in this direction by combining the parameterized control of 3D body shape and pose with neural point-based rendering, which replaces the classical rendering pipeline. Point-based rendering has a long history in computer graphics \cite{gross2011point,kobbelt2004survey}. Recently, point-based rendering has been successfully coupled with the neural network pipeline via learning per-point neural descriptors that are interpreted by the neural renderer \cite{aliev2019neural}. This approach produces photo-realistic novel views of a scene from a captured point cloud. However, this pipeline has been demonstrated for rendering static scenes with dense point clouds as inputs, with the need of re-learning point descriptors for every novel scene. Our approach is influenced by \cite{aliev2019neural} and \cite{martin2018lookingood}. However, along with the technical novelties and simplifications we describe in the follow-up sections, our main aim is to extend these approaches to enable efficient rendering of human avatars \emph{under novel subject identities and human poses}. We accomplish this by introducing SMPL \cite{loper2015smpl}, a deformable 3D body model, into the neural rendering loop. This provides us full control over body pose and shape variation. However, instead of relying on mesh connectivity for explicit rendering, we simply use mesh vertices and their colors projected onto the image plane as inputs for the neural rendering module. This provides the benefits of a parameterized body model, while greatly improving the rendering quality, without the complexity of classical methods. The overall pipeline, called \textit{SMPLpix}, is outlined in Figure \ref{fig:fig1}. During training, our framework operates on the data obtained from a commercially available 3D scanner \cite{treedys}. The SMPL model is registered to the raw scans \cite{bogo2014faust,loper2015smpl}; other parametric models can be used in principle \cite{joo2018total,pavlakos2019expressive}. The result of this process is a set of mesh vertices $X \in \mathbb{R}^{6890\times3}$, the RGB color of each vertex, and the body pose parameters $\theta$. It is important to mention that the registration process has inherent limitations like fitting hair (due to the irregularity of hair and low resolution of the SMPL model) or fitting clothing (due to the form-fitting topology of SMPL). The advantage of using the registered vertices over raw scans, however, is that we can control the pose of the vertices $X$ by varying a small set of inferred pose parameters $\theta$. We project the vertices of the body model using ground truth scanner camera locations $(\mathbf{K}, \mathbf{R}, \mathbf{t})$ and obtain an RGB-d image of the projected vertices. This image is processed by a UNet-like neural rendering network to produce the rasterized output RGB image that should match the ground truth image from a scanner camera. At test time, we are given novel mesh vertices $X$, their colors, body poses $\theta$ and camera locations $(\mathbf{K}, \mathbf{R}, \mathbf{t})$. Note that this input can also come from the real images using methods like \cite{alldieck2019learning}. \textbf{Intuition.} Our proposed method can be seen as a middle ground between mesh-based and point-based renderers. While we use the structured nature of mesh vertices to control the generative process, we ignore the mesh connectivity and treat vertices simply as unstructured point clouds. Compared with explicit mesh rasterization, the main advantage of this vertices-as-points approach, along with its computational and conceptual simplicity, is the ability of the trained neural renderer to reproduce complex high frequency surfaces \emph{directly in the pixel space}, as we will show in the experimental section. Our approach is also potentially applicable in cases when no explicit mesh connectivity information is available whatsoever and only a set of 3D anchor points is given. \textbf{Contributions.} The proposed work offers the following contributions: \begin{itemize} \item \emph{Deep controlled human image synthesis}: apart from the classic mesh-based renderers, to the best of our knowledge, the presented approach is the first one that can render novel human subjects under novel poses and camera views. The proposed framework produces photo-realistic images with complex geometry that are hard to reproduce with these classic renderers; \item \emph{Sparse point set neural rendering}: we show how popular image-to-image translation frameworks can be adapted to the task of translating a sparse set of 3D points to RGB images, combining several steps (geometric occlusion reasoning, rasterization and image enhancement) into a single neural network module. \end{itemize} \section{Related work} \label{sec:related} Our method is connected to several broad branches of 3D modeling and image synthesis techniques. Here we focus on the most representative work in the field. \textbf{3D human models.} Our method is based on the idea of modeling humans bodies and their parts via deformable 3D models \cite{anguelov2005scape,blanz1999morphable,joo2018total}, and in particular SMPL \cite{loper2015smpl}. Such models are controllable (essential for graphics) and interpretable (important for analysis). Extensions of SMPL exist that also model hands \cite{romero2017embodied}, faces \cite{li2017learning,pavlakos2019expressive} and clothing \cite{ma2019learning}. Separate models exist for capturing and modeling clothing, wrinkles, and hair \cite{hu2017simulation,zhou2018hairnet}. While powerful, rendering such models requires high-quality textures and accurate 3D geometry, which can be hard to acquire. Even then, the resulting rendered images may look smooth and fail to model details that are not properly captured by the model or surface reconstruction algorithms. \textbf{Neural avatars.} Recently, a new work focuses learning to render high-fidelity digital avatars \cite{lombardi2018deep,shysheya2019textured,thies2019deferred,wei2019vr}. While these works provide a great level of photo-realism, they are mostly tailored to accurately \emph{modeling a single subject}, and part or the whole system needs to be retrained in case of a new input. In contrast, our system is trained in a multi-person scenario and can render unseen subjects at test time. Another advantage is that it takes a relatively compact generic input (a set of 3D mesh vertices and their RGB colors) that can be also inferred from multiple sources at test time, including from real-world images \cite{alldieck2019learning}. \textbf{Pixel-space image translation and character animation.} The second part of our system, neural human renderer, is based on the recent success of pixel-to-pixel image translation techniques \cite{esser2018variational,isola2017image,wang2018high}. Two particular variations of this framework have the most resemblance to our model. First, \cite{chan2019everybody} uses a set of sparse body keypoints (inferred from a source actor) as input to produce an animated image sequence of a target actor. However, as with the neural avatars discussed above, the system needs to be retrained in order to operate on a novel target subject. Our work also resembles the sketch-to-image translation regime, where an edge image is used in order to produce a photo-realistic image of the person's head \cite{zakharov2019few} or generic objects \cite{chen2018sketchygan}. Our approach can also be viewed as translating a sparse set of key points into an image. However, our keypoints come from a structured 3D template and therefore convey more information about the rendered subject appearance; since they exist in 3D, they can be projected to an image plane under different camera views. Finally, another advantage of using SMPL topology as input to our image translation framework is its non-uniform vertex density according to region importance (i.e.~faces and hands are more densely sampled). This makes detailed rendering of these regions easier, without the need for a specific attention mechanism in the neural renderer itself. \textbf{Differentiable mesh (re-)rendering.} There are several available solutions that incorporate the mesh rendering step into fully differentiable learning pipelines \cite{kato2018neural,liu2019soft,loper2015smpl}. However, these methods follow a different line of work: they aim at constructing better gradients for the mesh rasterization step, while keeping the whole procedure of mesh face rendering and occlusion reasoning deterministic. This applies also to a soft rasterizer \cite{liu2019soft} that substitutes the discrete rasterization step with a probabilistic alternative. While this proves useful for the flow of gradients, the rendering procedure still lacks the flexibility that would allow it to fix artifacts of the original input geometry. One potential solution is to enhance the produced incomplete noisy renders by the additional neural re-rendering module \cite{liu2020neural,martin2018lookingood}. Our framework can be seen as the one that combines standard mesh rendering step with a follow-up neural image enhancement into one task-specific neural rendering module. Considering the original target application of \cite{martin2018lookingood}, another potential advantage of our framework for online conferencing is the reduced amount of data that needs to be transferred over the network channel to produce the final image. \textbf{Point-based rendering.} Point-based rendering \cite{gross2011point,kobbelt2004survey,levoy1985use,pfister2000surfels,rusinkiewicz2000qsplat} offers a well-established, scalable alternative to rendering scenes that can be hard to model with surface meshing approaches. We take inspiration from these methods, however, we substitute the fixed logic of rendering (e.g.~surfel-based \cite{pfister2000surfels}) with a neural module in order to adapt to sparse point sets with highly non-uniform densities, as well as to generate photorealistic pixel-space textures. \textbf{Rendering from deep 3D descriptors.} Another promising direction for geometry-aware image synthesis aims to learn some form of deep 3D descriptors from a 2D or 3D inputs \cite{aliev2019neural,lombardi2019neural,sitzmann2019deepvoxels,sitzmann2019srns}. These descriptors are processed by a trainable neural renderer to generate novel views. These methods, however, are limited when it comes to controlling the generative process; shapes are represented as voxels \cite{lombardi2019neural,sitzmann2019deepvoxels}, unstructured point clouds \cite{aliev2019neural} or neural network weights \cite{sitzmann2019srns}. This makes parameterized control of human pose difficult. \textbf{Neural point-based graphics.} The closest work to ours is \cite{aliev2019neural}. An obvious difference with respect to this work is that our input comes from a deformable model, which allows us to modify the render in a generative and intuitive way. Moreover, our model contains two additional differences. First, our inputs are considerably sparser and less uniform than the point clouds considered in \cite{aliev2019neural}. Second, instead of point neural descriptors that need to be relearned for every novel scene or subject, our rendering network obtains the specific details of a subject through the RGB colors it consumes as input \emph{at test time}. This alleviates the need for retraining the system for every novel scene. In summary, SMPLpix fills an important gap in the literature, combining the benefits of parameterized models like SMPL with the power of neural rendering. The former gives controllability, while the latter provides realism that is difficult to obtain with classical graphics pipelines. \section{Method} \label{sec:method} As is common in deep learning systems, our system has two key parts: the data used for training our model, and the model itself. We describe those two parts in the following sections. \subsection{Data} \label{subsec:smpl} \textbf{Scans.} Our renderer transforms sparse RGB-D images obtained from the 2D projections of SMPL~\cite{loper2015smpl} vertices. We take a supervised training approach with ground-truth images that correspond to the projected vertices of the SMPL model. Although it would be ideal to collect such a dataset from images in the wild, the inaccuracies in methods that infer SMPL bodies from images (e.g.~\cite{kanazawa2018end}) currently make this data ineffective. Instead, we use scan data collected in the lab. To that end, we collected more than a thousand scans with a commercially available 3D scanner (Treedy's, Brussels, Belgium \cite{treedys}) and photogrammetry software (Agisoft Photoscan~\cite{agisoft}). This results in raw 3D point clouds (\emph{scans}) $S \in \mathbb{R}^{M \times 6}, M \approx 10^6$, representing the body geometry, together with camera calibration $(\mathbf{K}, \mathbf{R}, \mathbf{t})$ compatible with a pinhole camera model. Note that the subjects are scanned in a neutral A-pose. Unlike most other image generation methods, this is not a problem for our system since the strong guidance provided by the input images prevents our method from overfitting to the input pose, as it can be seen in Section~\ref{subsec:qualitative}. \textbf{Registrations.} While these scans could potentially undergo a rendering process like~\cite{aliev2019neural}, it would not be possible to deform them in a generative manner, i.e. changing their shape or pose. To achieve that, we transform those unstructured point clouds into a set of points $X \in \mathbb{R}^{N \times 3}, N=6890$ with fixed topology that correspond to a reshapeable and reposeable model, SMPL \cite{loper2015smpl}. In its essence, SMPL is a linear blend skinned (LBS) model that represents the observed body vertices $X$ as a function of identity-dependent and pose-dependent mesh deformations, driven by two corresponding compact sets of shape $\Vec{\beta} \in \mathbb{R}^{10}$ and pose $\Vec{\theta} \in \mathbb{R}^{72}$ parameters: \begin{eqnarray} X = W(T_{P}(\Vec{\beta}, \Vec{\theta}), J(\Vec{\beta}), \Vec{\theta}, \mathcal{W}), \label{eq:smpl_lbs}\\ T_{P}(\Vec{\beta}, \Vec{\theta}) = \mathbf{\bar{T}} + B_S(\Vec{\beta}) + B_P(\Vec{\theta}), \label{eq:smpl_temp} \end{eqnarray} where $T_{P}(\Vec{\beta}, \Vec{\theta})$ models shape and pose dependent deformation of the template mesh in the canonical T pose via linear functions $B_S$ and $B_P$, and $W$ corresponds to the LBS function that takes the T-pose template $T_{P}$, set of shape-dependent $K$ body joint locations $J(\Vec{\beta}) \in \mathbb{R}^{3K}, K=23$ and applies the LBS function $W$ with weights $\mathcal{W}$ to produce the final posed mesh. We refer to the original publication \cite{loper2015smpl} for more details on the SMPL skinning function. Note that other versions of deformable 3D models \cite{anguelov2005scape,joo2018total} or topologies could be used, including the ones that additionally model hands and faces \cite{li2017learning,pavlakos2019expressive,romero2017embodied}, as well as clothing deformations \cite{ma2019learning}. In fact, in Section~\ref{subsec:results} we show experiments with two topologies of different cardinality. The SMPL registration process optimizes the location of the registration vertices and the underlying model, so that the distance between the point cloud and the surface entailed by the registration is minimized, while the registration vertices remain close to the optimized model. It is inspired by the registration in~\cite{bogo2014faust} although the texture matching term is not used. It is worth emphasizing that these registrations, as in~\cite{bogo2014faust}, can contain details about the clothing of the person since their vertices are optimized as free variables. This does not prevent us from reposing those subjects after converting them into SMPL templates $\mathbf{\bar{T}}^*$ through unposing, as explained and shown in Section~\ref{subsec:qualitative}. However, these extra geometric details are far from perfect, e.g.~they are visibly wrong in the case of garments with non-anthropomorphic topology, like skirts. \textbf{Color.} Finally, the registered mesh is used in Agisoft Photoscan together with the original image and camera calibration to extract a high-resolution texture image $I_{tex} \in \mathbb{R}^{8192 \times 8192 \times 3}$. This texture image is a flattened version of the SMPL mesh, in which every 3D triangle in SMPL corresponds to a 2D triangle in the texture image. Therefore, each triangle contains thousands of color pixels representing the appearance of that body portion. These textures can be used directly by the classic renderer to produce detailed images, as can be seen in Section~\ref{subsec:results}. Although it would be possible to exploit the detail in those textures by a neural renderer, that would slow it down and make it unnecessarily complex. Instead, we propose to use the sparse set of colors $X^c \in [0,1]^{6890\times 3}$ sampled at the SMPL vertex locations. These colors can be easily extracted from the texture image, since they are in full correspondence with the mesh topology. \textbf{Projections.} Having an input colored vertex set $X^+=[X, X^c] \in \mathbf{R}^{6890 \times 6}$ and camera calibration parameters $(\mathbf{K}, \mathbf{R}, \mathbf{t})$, we obtain image plane coordinates for every vertex $x \in X$ using a standard pinhole camera model \cite{hartley2003multiple}: \begin{eqnarray} \begin{pmatrix}u\\v\\d\end{pmatrix} = \mathbf{K}(\mathbf{R}x + \mathbf{t}). \label{eq:camera} \end{eqnarray} Next, we form an RGB-D vertex projection image. The projection image $P_X \in \mathbb{R}^{w \times h \times 4}$ is initialized to a value that can be identified as background by its depth value. Since depth values collected in the scanner have a range between $0.1$ and $0.7$ meters, a default value of $1$ is used to initialize both RGB and depth in $P_X$. Then, for every vertex $x \in X$, its image plane coordinates $(u, v, d)$ and color values $(r, g, b) \in X^c$ we assign: \begin{eqnarray} P_X[\lfloor u \rfloor, \lfloor v \rfloor] = (r, g, b, d). \label{eq:projection} \end{eqnarray} In order to resolve collisions during the projection phase (\ref{eq:projection}), when different vertices from $X$ end up sharing the same pixel-space coordinates $\lfloor u \rfloor, \lfloor v \rfloor$, we sort the vertices according to their depth and eliminate all the duplicate consecutive elements of the depth-wise sorted array of $\lfloor u \rfloor, \lfloor v \rfloor$ coordinates of X. Note that, since the number of vertices is much smaller than the full resolution of the image plane, these collisions rarely happen in practice. The whole vertex projection operation (\ref{eq:camera})-(\ref{eq:projection}) can be easily and efficiently implemented within modern deep learning frameworks \cite{paszke2017automatic} and, therefore, seamlessly integrated into bigger pipelines. \subsection{Neural rendering} \label{subsec:rasterization} Given our training data consisting of pairs of RGB-D projection images $P_X$ and segmented output images $I_X$, we train a UNet-type \cite{ronneberger2015u} neural network $G$ with parameters $\Theta$ to map initial point projections to final output images: \begin{eqnarray} G_{\Theta}: P_X \rightarrow I_X . \label{eq:unet} \end{eqnarray} In our experiments, we use one of the publicly available UNet architecture designs~\cite{unetpytorch}, to which we apply only minor changes to adapt it to our types of input and output. The network consists of 4 layers of $downconv$ and $upconv$ double convolutional layers [Conv2d, BatchNorm, ReLU] $\times 2$, with convolutional layers having the kernel size of 3. In case of $downconv$, this double convolutional layer is preceded by max pooling operation with kernel size 2; in case of $upconv$, it is preceded by bilinear upsampling and concatenation with the output of a corresponding $downconv$ layer. In general, the particular design of this module can be further optimized and tailored to a specific target image resolution and hardware requirements; we leave this optimization and further design search for a future work. Having the ground truth image $I_{gt}$ for a given subject and camera pose, we optimize our rendering network $G_{\Theta}$ for the weighted combination of perceptual VGG-loss \cite{johnson2016perceptual}, multi-scale, patch-based GAN loss and feature matching GAN loss \cite{wang2018high} in two stages. During the first stage (100 epochs), we train the model with Adam (learning rate set to 1.0e-4) and batch size 10 by minimizing the $L1$ loss between VGG activations: \begin{multline} L_{VGG}(I_{gt}, I_{X}) =\\ \sum^5_{i=0}{\frac{1}{2^{(5-i)}} ||f_{VGG}^{(i)}(I_{gt}) - f_{VGG}^{(i)}(I_{X})||_1}, \label{eq:vgg_loss} \end{multline} where $f_{VGG}^{(i)}(I)$ are activations at layer $i$ and $f_{VGG}^{(0)}(I) = I$. During the second stage (100 epochs), we restart Adam with learning rate 1.0e-5 and include a combination of multi-scale GAN and feature-matching losses identical to the ones in \cite{wang2018high}: \begin{multline} L(I_{gt}, I_{X}) = L_{VGG}(I_{gt}, I_{X}) \\+ \min\limits_{G}\Big[\max\limits_{D_1, D_2, D_3}\sum_{k=1,2,3}{L_{GAN}(G, D_k)} \\+ 0.1 * \sum_{k=1,2,3}{L_{FM}(G, D_k)} \Big] . \end{multline} Implicitly, the network $G_{\Theta}$ is learning to accomplish several tasks. First, it needs to learn some form of geometric reasoning, i.e. to ignore certain projected vertices based on their depth values. In that sense, it substitutes fixed-logic differentiable mesh rendering procedures \cite{kato2018neural} with a flexible, task-specific neural equivalent. Second, it needs to learn how to synthesize realistic textures based on sparse supervision provided by the projected vertices, as well as to hallucinate whole areas not properly captured by the 3D geometry, e.g. hair and clothing, to match the real ground truth images. Therefore, we believe that this approach could serve as a potentially superior (in terms of acquired image realism), as well as easier to integrate and computationally flexible, alternative to the explicit fixed differentiable mesh rasterization step of \cite{kato2018neural}. \begin{figure*}[t!] \begin{center} \includegraphics[clip,width=\textwidth]{smplpix_fig2_wacv.jpeg} \end{center} \caption{\textit{Qualitative comparison between neural mesh renderer \cite{kato2018neural} and SMPLpix (27k vertices) on novel subjects and camera poses (zoom in for details).} Compared to a standard mesh renderer, our model can fix texture and geometry artefacts (toe and finger regions) and generate high frequency details (hair and cloth wrinkles), while remaining conceptually simple (point projections as the main 3D geometry operator) and efficient in terms of utilized data and inference time.} \label{fig:fig2} \vspace{-5mm} \end{figure*} \section{Experiments} \subsection{Data details} \label{subsec:data} Accurately captured, well-calibrated data is essential for the proposed approach in its current form. We use 3D scans of 1668 subjects in casual clothing. The subjects are diverse in gender, body shape, age, ethnicity, as well as clothing patterns and style. For each subject, we select 20 random photos from among the 137 camera positions available in the scanner camera rig. We use 1600 subjects for training and 68 subjects for test, which forms training and test sets of $32000$ and $1360$ images correspondingly. We use the image resolution of size $410 \times 308$ during all the experiments. Of 68 test subjects, 16 gave their explicit consent for their images to be used in the present submission. We use these test subjects for the qualitative comparison in the paper, while the full test set is used for the quantitative evaluation. \subsection{Quantitative experiments} \label{subsec:results} We compare our system with other renderers that can generate images of reshapeable and reposeable bodies. This limits the other methods to be classic rendering pipelines, since, to the best of our knowledge, no other deep learning model offers this generative behaviour. It is important that the renderers support automatic differentiation, since our ultimate goal includes integrating the renderer with a fully differentiable learning system. With these two constraints, we compare with the neural mesh renderer introduced in~\cite{kato2018neural}, in its popular PyTorch re-implementation~\cite{pytorchnr}. \textbf{Metrics.} We compare SMPLpix against different versions of classic renders implemented with~\cite{pytorchnr} according to two different quantitative metrics popular in image generation and super-resolution: peak signal-to-noise ratio (PSNR, \cite{hore2010image}) and learned perceptual image patch similarity (LPIPS,~\cite{zhang2018unreasonable}). PSNR is a classic method, while LPIPS has gained popularity in recent works for being more correlated with the perceptual differences. We should note that the field of quantitative perceptual evaluation is still an area of research, and no metric is perfect. Therefore, we also provide qualitative results in the next section. \textbf{Baseline variants.} For \cite{kato2018neural}, we use the following rendering variants. First, we render the mesh with exactly the same information available to our SMPLpix rendering pipeline, i.e.~only 1 RGB color per vertex\footnote{Technically, since~\cite{pytorchnr} does not support per-vertex color rendering, this has to be achieved by performing linear interpolation between the vertex colors in their per-triangle texture space}. Next, we use the much more information-dense option of texture images $I_{tex}$. To optimise the inference time of \cite{kato2018neural}, we do not utilise the full extensive 8k textures, but rather search for the optimal downscaled version of the texture image, at which no further improvement in terms of PSNR and LPIPS were observed (Table \ref{table:results}, row 2). Since our method can be topology agnostic, we perform these comparisons for two topologies: the native SMPL topology of 6890 vertices (noted as $7k$) and an upsampled version with a higher vert count of 27578 vertices (noted as $27k$). \begin{figure*}[t!] \begin{center} \includegraphics[clip,width=\linewidth]{view_image.jpg} \end{center} \caption{\textit{Novel view generation}. Images produced by our renderer are consistent across novel camera views.} \label{fig:view} \vspace{-5mm} \end{figure*} \textbf{Results.} The values for PSNR and LPIPS are compiled in Table~\ref{table:results}. The first conclusion to extract from this table is that, given a fixed amount of color information (i.e.~comparing per-verts NMR against SMPLpix for a fixed topology), SMPLpix clearly outperforms NMR in both PSNR and LPIPs. Limiting the color information can be useful in terms of computational and data transmission efficiency, and the use of textures makes the rendering system arguably more complex. However, we included also a comparison against NMR using full textures. Although the values are much closer, SMPLpix slightly outperforms NMR also in this case. This validates our main hypothesis, i.e.~that the adaptive rendering procedure described in Section \ref{subsec:rasterization} can learn a valid rendering prior of the human texture and surface, and reproduce it based on a sparse input given by the colored mesh vertices. Moreover, it outperforms the conventional methods in terms of acquired level of realism since it is trained end-to-end to reproduce the corresponding photo. In terms of efficiency, using low-dimensional geometry with no anti-aliasing and full textures achieves the fastest running times (14ms), followed closely by SMPLpix (17ms), which obtains better quality metrics. Also, note that for NMR, the inference time grows roughly linearly with the number of geometry elements, while for our method, most of the time is spent in the neural rendering module that is agnostic to the number of projected points. Being a UNet-like neural network, this module can be further optimised and tailored to specific hardware requirements. \begin{figure*}[t!] \begin{center} \includegraphics[clip,width=\linewidth]{pose_image_2.png} \end{center} \caption{\textit{Pose generation}. We can animate subjects with novel pose sequences, e.g.~the ones taken from \cite{mahmood2019amass}. Please see the supplementary video on the project website for more examples of avatar reposing.} \label{fig:motion} \vspace{-5mm} \end{figure*} \begin{table} \begin{center} \caption{\emph{Neural mesh renderer \cite{kato2018neural} vs SMPLpix neural rendering pipeline.} Our model outperforms all variants of standard mesh rendering in both pixel-wise and perceptual similarity metrics.} \label{table:results} \begin{tabular}{l|c|c} \hline\noalign{\smallskip} Method & PSNR $\uparrow$ & LPIPS $\downarrow$ \\ \hline NMR\cite{kato2018neural} (7k, per-verts) & 23.2 & 0.072 \\ NMR\cite{kato2018neural} (7k, full textures) & 23.4 & 0.049 \\ NMR\cite{kato2018neural} (27k, per-verts) & 23.5 & 0.064 \\ NMR\cite{kato2018neural} (27k, full textures)& 23.6 & 0.047 \\ SMPLpix (7k verts) & 24.2 & 0.051 \\ SMPLpix (27k verts) & \textbf{24.6} & \textbf{0.045} \\ \hline \end{tabular} \end{center} \end{table} \subsection{Qualitative experiments} \label{subsec:qualitative} Since it is well known that perceptual metrics are not perfect in capturing the quality of synthetic images, we also provide examples for the reader to judge the quality of our method and to suggest the potential applications that its generative character enables. \textbf{Qualitative comparison.} We provide a visual comparison of ground truth and the methods previously described in Figure~\ref{fig:fig2}. The first thing to note is that these images contain elements that are known to be difficult to model with the SMPL topology, e.g.~hair, baggy clothes, and shoes. We can observe that, since the relation between geometry and pixel colors in NMR is very constrained, the geometry artifacts are still visible in the rendered images. Note, for example, the unrealistic hair buns in NMR, smoothed out clothes in the first column, and the unrealistic ear shape in the sixth column due to the lack of independent hair geometry that covers the ears in the SMPL topology. In comparison, SMPLpix learns to correlate those artifacts with specific combinations of vertex locations and shapes, and recreates loose hair, pony tails, or loose clothing (to some extent). Another type of artifact that is corrected is incorrect texture due to misalignment: as seen in the fourth column, the hand area contain pixels of background color due to misalignment. SMPLpix learns to correct this type of artifact. Finally, pay attention to the toes rendered on the shoes by NMR, which are due to the SMPL topology. These toes are corrected (removed) by our renderer in the next to last column. It is important to note that some of these details are reconstructed in a plausible way, though not in the exact way they are present in the ground truth. \begin{figure}[b] \begin{center} \includegraphics[clip,width=\linewidth]{shape_variation.png} \end{center} \caption{\textit{Shape variations with SMPLpix. The first column shows renderings of the original subject from two views. Subsequent columns explore the first directions of the SMPL shape space, in the negative and positive directions. This varies the subject shape, making them thinner or heavier, respectively.}} \label{fig:shape} \vspace{-5mm} \end{figure} \textbf{Novel view generation.} A first question about SMPLpix generalization capabilities is how well does it generalize to novel views. Figure~\ref{fig:view} shows images generated from novel viewpoints with our algorithm. Given the ample coverage of views achieved by the scanning data, we can generate views from almost arbitrary orientations. However, we should note that the distance to the subject is not covered nearly as well in our setup, and the quality of our results degrade when the camera is too far or too close to the person. A possible way to handle this, left for future work, is to augment the data with arbitrary scalings of the input mesh and image. \textbf{Pose generation.} An advantage of our method with respect to the main other point-based renderer~\cite{aliev2019neural} is that we can alter the renders in a generative manner, thanks to the SMPL model that generates our inputs. To that end, we take the registrations previously mentioned and create a subject specific model in the same spirit as in~\cite{dyna}. A subject specific model has a template that is obtained by reverting the effects of the estimated registration pose. More specifically, it involves applying the inverse of the LBS transformation $W^{-1}$ and subtracting the pose-dependent deformations $B_P(\Vec{\theta})$ (Equations~\ref{eq:smpl_lbs} and ~\ref{eq:smpl_temp}) from the registration. We can repose a subject specific model to any set of poses compatible with the SMPL model. To that end, we tried some sequences from AMASS~\cite{mahmood2019amass}. As can be seen in Figure~\ref{fig:motion}, bodies can deviate largely from the A-pose in which most of the subjects stand in the training data. Experimentally, we have observed that this is very different for other neural renderers like~\cite{chan2019everybody}. \textbf{Shape generation.} Although~\cite{aliev2019neural} cannot generate people arbitrarily posed, other renderers like~\cite{chan2019everybody,shysheya2019textured} potentially can, if they have a way to generate new skeleton images. However, shape cannot change with those approaches, since skeletons only describe the length of the bones and not the body structure. We can see this potential application in Figure~\ref{fig:shape}. For this figure, we used the previously mentioned subject-specific SMPL model for two of the subjects, and modified their shape according to the first three components of the original SMPL shape space. We can see that shape variations are realistic, and details like hair or clothing remain realistic. To our knowledge, this is the first realistic shape morphing obtained through neural rendering. We provide more examples of avatar reposing, reshaping and novel view synthesis on the project web site\footnote{\url{https://sergeyprokudin.github.io/smplpix/}}. \section{Conclusion and future work} In this work, we presented SMPLpix, a deep learning model that combines deformable 3D models with neural rendering. This combination allows SMPLpix to generate novel bodies with clothing and with the advantages of neural rendering: visual quality and data-driven results. Unlike any other neural renderers of bodies, SMPLpix can vary the shape of the person and does not have to be retrained for each subject. Additionally, one of the key characteristics of SMPLpix is that, unlike the classic renderers, it is improvable and extensible in a number of ways. We are particularly interested in integrating the renderer with systems that infer SMPL bodies from images (e.g.~\cite{kanazawa2018end,kocabas2019vibe,kolotouros2019learning}) to enable an end-to-end system for body image generation trained from images in the wild. SMPLpix represents a step towards controllable body neural renderers, but it can obviously be improved. Rendering high-frequency textures remains a challenge, although including extra information in our input projection image is a promising approach; e.g.~per-vertex image descriptors, similar to the local image descriptors pooled across views in~\cite{pifu} or deep point descriptors in \cite{aliev2019neural}. \paragraph{Disclosure.} While MJB is also an employee of the Max Planck Institute for Intelligent Systems (MPI-IS), this work was performed solely at Amazon where he is a part time employee. At MPI-IS he has received research gift funds from Intel, Nvidia, Adobe, Facebook, and Amazon. He has financial interests in Amazon and Meshcapade GmbH. \clearpage {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-11-10T02:33:47', 'yymm': '2008', 'arxiv_id': '2008.06872', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06872'}
arxiv
\section{Introduction} \label{sec:intro} Deep neural networks (DNNs) have emerged as a predominant framework for learning multiple levels of representation, with higher levels representing more abstracts aspects of the data~\cite{bengio2013deep}. The better representation has led to the state-of-the-art performance in many challenging tasks in computer vision~\cite{krizhevsky2012imagenet, voulodimos2018deep}, natural language processing~\cite{collobert2008unified, young2018recent} and many other domains~\cite{pierson2017deep, heaton2017deep}. However, despite their pervasiveness, recent studies have exposed the lack of robustness of DNNs to various forms of perturbations~\cite{szegedy2013intriguing, hendrycks2019benchmarking, gu2019using}. In particular, adversarial examples which are imperceptible perturbations of the input data carefully crafted by adversaries to cause erroneous predictions pose a real security threat to DNNs deployed in critical applications~\cite{kurakin2016adversarial}. The intriguing phenomenon of adversarial examples has garnered a lot of attention in the research community~\cite{yuan2019adversarial} and progress has been made in both creating stronger attacks to test the model's robustness~\cite{goodfellow2014explaining, moosavi2015deepfool, carlini2017towards, xiao2018spatially} as well as defenses to these attacks~\cite{madry2017towards, Zhang2019theoretically, lamb2019interpolated}. However, \citet{athalye2018obfuscated} show that most of the proposed defense methods rely on obfuscated gradients which is a special case of gradient masking and lowers the quality of the gradient signal causing the gradient-based attack to fail and give a false sense of robustness. They observe adversarial training~\cite{madry2017towards} as the only effective defense method. The original formulation of adversarial training, however, does not incorporate the clean examples into its feature space and decision boundary. On the other hand, \citet{jacobsen2018excessive} provide an alternative viewpoint and argue that the adversarial vulnerability is a consequence of narrow learning, resulting in classifiers that rely only on a few highly predictive features in their decisions. We have not yet developed a full understanding of the major factors that contribute to adversarial vulnerability in DNNs and consequently, the optimal method for training robust models remains an open question. A recent variant of adversarial training, TRADES~\cite{Zhang2019theoretically}, adds a regularization term on top of the standard cross-entropy loss which forces the model to match its embeddings for the clean example and the corresponding adversarial example. However, there might be an inherent tension between the objective of adversarial robustness and that of standard generalization~\cite{tsipras2018robustness}. Therefore, combining these optimization tasks into a single model and forcing the model to completely match the feature distributions of the adversarial and clean examples may lead to sub-optimal solutions. We, therefore, hypothesize that considering the optimization for adversarial robustness and generalization as two distinct yet complementary tasks and encouraging more exhaustive exploration of the input and parameter space can lead to better solutions. In this paper, we propose adversarial concurrent training (ACT) for training a robust model in conjunction with a natural model in a collaborative manner (Fig.\ref{fig:act_schematic}a). The goal is to utilize the task-specific decision boundaries to align the feature space of the robust and natural model in order to learn a more extensive set of features that are less susceptible to adversarial perturbations. To this end, ACT closely intertwines the training of a robust and natural model by involving them in a minimax game inside a closed learning loop. The adversarial examples are generated by determining regions in the input space where the discrepancy between the two models is maximum. In the subsequent step, each model minimizes a supervised learning loss which optimizes the model on its specific task in addition to a mimicry loss that aligns the two models. Our formulation consists of bi-directional knowledge distillation between the clean and adversarial domain, enabling them to collectively explore the input and parameter space more extensively. Furthermore, the supervision from the natural model acts as a regularizer which effectively adds a prior on the learned representations and leads to semantically meaningful features that are less susceptible to off-manifold perturbations introduced by adversarial attacks. We empirically test the efficacy of our proposed approach and show that ACT provides a better trade-off between robustness and generalization across different datasets (CIFAR-10, CIFAR-100~\cite{krizhevsky2010cifar} and ImageNet \cite{krizhevsky2012imagenet}) and network architectures (ResNet~\cite{he2015deep} and WideResNet~\cite{zagoruyko2016wide}). Our further analyses show that ACT learns a lower complexity model with higher posterior entropy solutions, indicative of convergence to flatter minima. While standard adversarial training reduces the information compression in the learned representations compared to standard training~\cite{lamb2019interpolated}, our method shows higher information compression than even standard training. The empirical results coupled with desirable characteristics of models trained with ACT demonstrates the effectiveness of concurrent training for adversarial robustness. Our results also demonstrate the versatility of ACT to different datasets and network architectures which makes the method applicable across a variety of application \section{Related Work} The discovery of adversarial examples \cite{szegedy2013intriguing} has garnered a lot of interest from the research community. Researchers have proposed various forms of defense methods which include detecting the adversarial examples \cite{grosse2017statistical, feinman2017detecting}, applying non-linear pre-processing and transformations on the input image, using ensemble method \cite{strauss2017ensemble, tramer2017ensemble, buckman2018thermometer,bhagoji2017dimensionality}, regularization techniques \cite{zantedeschi2017efficient, jakubovitz2018improving, summers2019improved} and training on adversarial examples \cite{goodfellow2014explaining, madry2017towards, Zhang2019theoretically,lamb2019interpolated}. However, Athalye \emph{et al}\bmvaOneDot \cite{athalye2018obfuscated} showed that most of the proposed defense methods rely on gradient obfuscation, lowering the quality of the gradient signal, to give a false sense of robustness. They found adversarial training to be an effective method after addressing the issue of gradient obfuscation. Nevertheless, the increase in robustness comes at the cost of generalization. A number of studies even argue that there is an inherent trade-off between robustness and generalization and consider them as contradictory goals \cite{tsipras2018robustness, ilyas2019adversarial, su2018robustness, Zhang2019theoretically}. Ilyas \emph{et al}\bmvaOneDot \cite{ilyas2019adversarial} consider the adversarial vulnerability to be a direct consequence of the model's sensitivity to well generalizing features which are highly predictive yet brittle. Jacobsen \emph{et al}\bmvaOneDot \cite{jacobsen2018excessive} provide an alternative perspective on adversarial vulnerability and show that DNNs are also excessively invariant to task relevant changes in the input image. They attribute this to narrow learning resulting from the insufficiency of the standard cross-entropy loss to incentivize explaining all class dependent aspects of the input. On other end, collaborative learning which provides additional supervision signals, has been effective in increasing the robustness to different noise types. Knowledge distillation \cite{hinton2015distilling} has been shown to be a general-purpose training paradigm which is more robust to common challenges in the real-world datasets \cite{sarfraz2020knowledge}. Han \emph{et al}\bmvaOneDot~\cite{han2018co} use two networks to filter different types of errors introduced by noisy labels. Hendrycks \emph{et al}\bmvaOneDot~\cite{hendrycks2019using} show that self-supervision can improve the robustness of the model to adversarial examples, label corruption, and common input corruptions. Based on the aforementioned findings, we hypothesize that adversarial training within a collaborative framework that encourages the model to explore the input and parameter space more extensively can be instrumental in further improving the robustness gains of the standard adversarial training method. \begin{figure}[tb] \centering \includegraphics[clip, trim=0cm .3cm 0cm .3cm, width=13cm]{./figures/ACT_DNA.pdf \caption{a) Schematic of our proposed method. b) An overview of ACT on a binary classification problem. $x_{+}$ and $x_{-}$ indicate data samples for positive and negative classes respectively whereas circle indicates the allowed $\epsilon$-bound. First, adversarial examples are generated by identifying discrepancy regions between $G$ and $F$. The arrow in the circles shows the direction of the adversarial perturbation and the circles show the perturbation bound. In a subsequent step, the discrepancy between the models is minimized. This effectively aligns the decision boundaries and pushes them further from the examples. Best viewed in color.} \label{fig:act_schematic} \end{figure} \section{Adversarial Concurrent Training} In this section, we first present the overall idea and intuition behind the proposed method and how it aims to address some of the shortcomings of standard adversarial training and then formally define the method and introduce the loss functions used for training the model. \subsection{Proposed Method}\label{act_overview} Standard adversarial training~\cite{madry2017towards} involves generating an adversarial example $x'$ for each clean example $x$ and then subsequently training the model to assign the same label $y$ to $x'$ using cross-entropy loss. Adversarial training has been proven to confer robustness to the model. However, the standard formulation has a few shortcomings. The model does not receive any pair information indicating that $x'$ is the adversarial counterpart of $x$ and therefore fails to utilize the semantic similarity between the adversarial and clean examples for learning an optimal embedding. The objective function does not involve explicitly minimizing the generalization on clean examples which can lead to overfitting to the adversarial domain. Furthermore, the model is not incentivized to incorporate all class-dependent features of the input into its decision boundary which leads to narrow learning. One approach is to combine the generalization and adversarial robustness loss into one objective function \cite{Zhang2019theoretically,kannan2018adversarial}. However, the goal of adversarial robustness is different from standard generalization~\cite{tsipras2018robustness}. Therefore, combining these two optimization tasks together into a single model and completely matching the feature distributions of the adversarial and clean examples could cause tension between the two tasks and leads to sub-optimal solutions. We hypothesize that treating the optimization for adversarial robustness and generalization as distinct yet complementary tasks in a way that encourages more exhaustive exploration of the input and parameter space can lead to better solutions. To this end, we propose Adversarial Concurrent Training (ACT) which entails training an adversarially robust model in conjunction with a natural model in a collaborative manner (Fig.\ref{fig:act_schematic}a). The goal is to utilize the task specific decision boundaries to align the feature space of the robust and natural model in order to learn a more extensive set of features which are less susceptible to adversarial perturbations. ACT closely intertwines the training of a robust and natural model by involving them in a minimax game inside a closed learning loop. The adversarial examples are generated by identifying regions in the input space where the discrepancy between the robust and natural model is maximum. In the subsequent step, the discrepancy between the two models is minimized in addition to optimizing them on their respective tasks. \begin{algorithm}[tb] \caption{Adversarial Concurrent Training Algorithm} \label{algo:act} \textbf{Input:} Dataset $D$, Balancing factor $\alpha$, Learning rate $\eta$, Batch size $m$\\ \textbf{Initialize:} $G$ and $F$ parameterized by $\theta$ and $\phi$\\ \While{Not Converged}{ 1: Sample mini-batch: ${(x_1, y_1), ... , (x_m,y_m)} \sim D$\\ 2: Compute adversarial examples:\\ ~~~~$\delta^*=\argmax_{\delta\in S}\mathcal{L}_{G}(\theta,\phi,\delta)$\\ 3: Compute $\mathcal{L}_G(\theta,\phi,\delta^*)$ (Equation \ref{eq:loss_G})\\ ~~~~Compute $\mathcal{L}_F(\theta,\phi,\delta^*)$ (Equation \ref{eq:loss_F})\\ 4: Compute stochastic gradients and update the parameters:\\ ~~~~$\theta^*\gets\theta-\eta\frac{\partial\mathcal{L}_{G}}{\partial\theta}$\\ ~~~~$\phi^*\gets\phi-\eta\frac{\partial\mathcal{L}_{F}}{\partial\phi}$ } \Return{$\theta$* and $\phi$*} \end{algorithm} Our approach has a number of advantages. The adversarial perturbations, generated by identifying regions in the input space where the two models disagree, can be effectively used to align the two models. This alignment coupled with pushing the two decision boundaries away from the data samples leads to smoother decision boundaries (Fig.\ref{fig:act_schematic}b). Updating the models based on the disagreement regions combined with optimization on distinct tasks ensures that the two models do not converge to a consensus, and the method does not reduce to self-training. Furthermore, the supervision from the natural model acts as a noise-free reference for regularizing the robust model. This effectively adds a prior on the learned representations which encourages the model to learn semantically relevant features in the input space. This combined with the requirement on the robust model's prediction to be stable within the epsilon bound encourages the model to select semantically relevant features with stable behavior over a larger region. \subsection{Formulation}\label{formulation} We formulate our proposed method, ACT, as a concurrent training of an adversarially robust model $G$ parametrized by $\theta$ and a natural model $F$ parametrized by $\phi$ (see Fig.\ref{fig:act_schematic}a). Each model is trained with two losses: a task specific loss and a mimicry loss. The standard cross-entropy loss ($\mathcal{L}_{CE}$) is used as the task specific loss and the Kullback-Leibler Divergence (${D}_{KL}$) is used as the mimicry loss to align the output distributions of the models. The robust model minimizes the convex combination of the cross-entropy loss on adversarial examples and the ${D}_{KL}$ between the output distributions of the robust model on adversarial examples and the natural model on clean examples. \begin{equation}\label{eq:loss_G} \begin{split} \mathcal{L}_G(\theta,\phi,\delta)= &(1-\alpha)\mathcal{L}_{CE}(G(x + \delta;\theta),y)+\alpha D_{KL}(F(x;\phi)||G(x + \delta;\theta)) \end{split} \end{equation} where the perturbation $\delta$ is sampled from a set of allowed perturbations $S$ bounded by $\epsilon$. The tuning parameter $\alpha \in[0,1]$ plays key role on balancing the importance of task specific and alignment errors. The natural model uses a similar loss function which minimizes the cross-entropy loss on clean examples. \begin{equation}\label{eq:loss_F} \begin{split} \mathcal{L}_F(\theta,\phi,\delta)=&(1-\alpha)\mathcal{L}_{CE}(F(x;\phi),y)+\alpha D_{KL}(G(x+\delta;\theta)||F(x;\phi)) \end{split} \end{equation} The training procedures involves first finding the adversarial examples by maximizing the robust model loss $\mathcal{L}_{G}$ with respect to $\delta$ within the set of allowed perturbation $S$, and then subsequently minimizing the loss functions for each model $\mathcal{L}_{G}$ and $\mathcal{L}_{F}$ (see Algorithm \ref{algo:act}). This results in an approximate minimax optimization: \begin{equation}\label{eq:optim} \begin{cases} \min_{\theta}\mathop{E}_{(x,y)\in D}\max_{\delta\in S}\mathcal{L}_{G}(\theta,\phi,\delta)\\ \min_{\phi}\mathop{E}_{(x,y)\in D}\mathcal{L}_{F}(\theta,\phi,\delta) \end{cases} \end{equation} Note that the natural model $F$ is only used during training, and at inference, only the robust model $G$ is used. Therefore, ACT does not incur any additional inference cost compared to standard adversarial training. \section{Empirical Validation} In this section, we empirically evaluate the the effectiveness of our proposed method and study the characteristics of the models. \subsection{Experimental Setup}\label{exp_setup} We evaluate the performance ACT on different datasets (CIFAR-10, CIFAR-100 \cite{krizhevsky2010cifar} and ImageNet \cite{krizhevsky2012imagenet}) and network architectures (ResNet \cite{he2015deep} and WideResNet \cite{zagoruyko2016wide}). For all our experiments, we normalize the images between 0 and 1 and apply random cropping with reflective padding of 4 pixels and random horizontal flip data augmentations. For training, we use stochastic gradient descent (SGD) with 0.9 momentum, 200 epochs, batch size 128, and an initial learning rate of 0.1, decayed by a factor of 0.2 at epochs 60, 120 and 150. Unless explicitly mentioned, the results for ACT refers to the performance of the robust model G. For Madry and TRADES, we follow the training scheme used in \cite{Zhang2019theoretically}. For generating adversarial examples during training, we use the projected gradient decent (PGD) as a universal first order adversary \cite{madry2017towards} with $\epsilon=0.031$, step size $\eta=0.007$, and the perturbation steps $K=10$. For evaluation, we set $\eta = 0.003$ and test for different perturbation steps. For a fair comparison, we use $1/\lambda = 5$ for TRADES which achieves the highest robustness for ResNet-18 in \cite{Zhang2019theoretically}. In our experiments, TRADES achieves both better robustness and generalization than reported in the original work \cite{Zhang2019theoretically}. We train each method with 3 different random seeds and report the average and one standard deviation performance. $A_{nat}$ refers to standard accuracy on clean examples whereas $A_{rob}$ refers to accuracy on adversarial examples (reported in percentage). Unless otherwise stated, $A_{rob}$ shows the worst performance on a PGD-20 attack with 5 random initialization. \begin{table}[tb] \center \resizebox{\columnwidth}{!}{% \begin{tabular}{|l|l|cccccc|} \hline \multicolumn{2}{|l|}{} & 0.1 & 0.3 & 0.5 & 0.7 & 0.9 & 1.0 \\ \hline \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Standard \\ model (F)\end{tabular}} & $A_{nat}$ & 95.29$\pm$0.10 & 95.31$\pm$0.10 & 94.88$\pm$0.13 & 94.42$\pm$0.10 & 90.12$\pm$0.63 & 10.00\\ & $A_{rob}$ & 3.57$\pm$1.06 & 3.81$\pm$1.29 & 2.90$\pm$0.26 & 3.36$\pm$0.45 & 10.85$\pm$2.04 & 0.00\\ \hline \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}Robust\\ model (G)\end{tabular}} & $A_{nat}$ & 85.94$\pm$0.11 & 86.13$\pm$0.14 & 86.33$\pm$0.22 & 86.24$\pm$0.18 & 84.87$\pm$0.91 & 10.00\\ & $A_{rob}$ & 48.93$\pm$0.28 & 49.40$\pm$0.59 & 50.62$\pm$0.86 & 51.37$\pm$0.41 & 55.12$\pm$1.07 & 0.00\\ \hline \end{tabular}} \caption{Effect of $\alpha$ hyperparameter on ACT (ResNet-18 trained on CIFAR-10). \label{tab:alpha_eff}} \end{table} \subsection{Effect of $\alpha$ hyperparameter}\label{alpha_param} Table \ref{tab:alpha_eff} shows the effect of the balancing factor $\alpha$ on the robustness and generalization of the natural and robust models. The extra supervision signal from each of the model affects both the robustness and generalization performance of the models. The adversarial robustness of the robust model generally increases as we increase $\alpha$ value. Interestingly, considerable robustness is transferred to the natural model as well without explicitly being trained on adversarial examples and this transfer increases for higher $\alpha$ values. For our subsequent experiments, we use $\alpha=0.9$. \begin{table}[tb] \center \resizebox{\columnwidth}{!}{% \begin{tabular}{|l|l|l|c|c|c|c|c|} \hline \multirow{2}{*}{} & \multirow{2}{*}{Dataset} & \multirow{2}{*}{Defense} & \multirow{2}{*}{$A_{nat}$} & \multicolumn{3}{c|}{$A_{rob}$} & Minimum \\ \cline{5-7} & & & & PGD-20 & PGD-100 & PGD-1000 & Perturbation\\ \hline \hline \multirow{6}{*}{\rotatebox[origin=c]{90}{ResNet-18}} & \multirow{3}{*}{CIFAR-10} & Madry & \bf 85.11$\pm$0.19 & 50.53$\pm$0.01 & 47.67$\pm$0.18 & 47.51$\pm$0.16 & 0.03782$\pm$0.00024\\ & & TRADES & 83.49$\pm$0.38 & 53.79$\pm$0.29 & 52.15$\pm$0.26 & 52.12$\pm$0.26 & 0.04279$\pm$0.00066 \\ & & ACT & 84.33$\pm$0.27 & \bf 55.83$\pm$0.18 & \bf 53.73$\pm$0.19 & \bf 53.62$\pm$0.19 & \bf 0.04454$\pm$0.00069\\ \cline{2-8} & \multirow{3}{*}{CIFAR-100} & Madry & 58.36$\pm$0.10 & 24.48$\pm$0.16 & 23.10$\pm$0.20 & 23.02$\pm$0.23 & 0.01961$\pm$0.00010\\ & & TRADES & 56.91$\pm$0.46 & 28.88$\pm$0.16 & 27.98$\pm$0.17 & 27.96$\pm$0.19 & 0.02353$\pm$0.00014\\ & & ACT & \bf 61.56$\pm$0.46 & \bf 31.14$\pm$0.16 & \bf 29.74$\pm$0.15 & \bf 29.71$\pm$0.14 & \bf 0.02462$\pm$0.00017\\ \hline \multirow{6}{*}{\rotatebox[origin=c]{90}{WRN-28-10}} & \multirow{3}{*}{CIFAR-10} & Madry & 87.26$\pm$0.20 & 49.76$\pm$0.06 & 46.91$\pm$0.10 & 46.77$\pm$0.06 & 0.04412$\pm$0.00083\\ & & TRADES & 86.36$\pm$0.26 & 53.52$\pm$0.17 & \bf 50.73$\pm$0.18 & \bf 50.63$\pm$0.17 & 0.04714$\pm$0.00018\\ & & ACT & \bf 87.58$\pm$0.16 & \bf 54.94$\pm$0.14 & 50.66$\pm$0.11 & 50.44$\pm$0.13 & \bf 0.05601$\pm$0.00031\\ \cline{2-8} & \multirow{3}{*}{CIFAR-100} & Madry & \bf 60.77$\pm$0.16 & 24.92$\pm$0.23 & 23.56$\pm$0.26 & 23.46$\pm$0.24 & 0.02084$\pm$0.00011\\ & & TRADES & 58.10$\pm$0.17 & 28.49$\pm$0.08 & \bf 27.50$\pm$0.23 & \bf 27.44$\pm$0.23 & 0.02395$\pm$0.00011\\ & & ACT & 60.72$\pm$0.18 & \bf 28.74$\pm$0.14 & 27.32$\pm$0.00 & 27.26$\pm$0.01 & \bf 0.02595$\pm$0.00016 \\ \hline \end{tabular}} \caption{Comparison of ACT with prior defense models under various white-box attacks. \label{tab:comparison1}} \end{table} \subsection{Comparison with prior work}\label{comparison} As our method adapts standard adversarial training in a collaborative learning framework, original formulation by Madry \cite{madry2017towards} is included as baseline. Furthermore, TRADES \cite{Zhang2019theoretically} is included to show the effectiveness of optimization for robustness and generalization as two distinct yet complementary tasks instead of combining them into a single model. Table \ref{tab:comparison1} shows the effectiveness of ACT across different datasets and network architectures under various white-box attacks. Specifically, for ResNet-18, ACT significantly improves the robustness. In instances where Madry has better generalization, the difference in the robustness is considerably larger. \begin{figure}[tb] \centering \begin{tabular}{cc} \includegraphics[width=.47\columnwidth]{./figures/9_img_indx123_title.pdf}& \includegraphics[width=.47\columnwidth]{./figures/2_img_indx133_title.pdf}\\ \includegraphics[width=.47\columnwidth]{./figures/16_img_indx103.pdf}& \includegraphics[width=.47\columnwidth]{./figures/14_img_indx54.pdf}\\ \end{tabular} \caption{Minimum perturbations required to fool the robust models trained with different defense methods on ResNet-18 and CIFAR-10. The label of each image shows the predicted class along with the $\ell_\infty$ distance of the adversarial example from the clean example. Note that the perturbations are multiplied by 5 to highlight the visual differences.} \label{fig:adversarial_example} \end{figure} We also evaluate the average minimum perturbation required to successfully fool the defense methods. We apply the $FGSM^k$ attack in foolbox \cite{rauber2017foolbox} which returns the smallest adversarial perturbation under the $\ell_\infty$ distance. Table \ref{tab:comparison1} shows that ACT consistently requires higher perturbation in images on average across the different datasets and network architectures. Fig.\ref{fig:adversarial_example} provides examples of the required perturbations to fool each defense. ACT requires a higher degree of perturbation in the semantically relevant regions of the image. We further verify the effectiveness of our method under black-box attacks. Table \ref{tab:blackbox} shows the transferability of adversarial examples generated using a PGD-20 attack on the surrogate model to the target models trained with different defense methods. ACT shows higher robustness to black-box attacks transferred from Madry and TRADES. \savebox{\tempbox}{\begin{tabular}{@{}r@{}l@{\space}} &\rotatebox[origin=b]{0}{\bf Sur} \\ \rotatebox[origin=t]{0}{\bf Def} \end{tabular}} \begin{table}[tb] \center \resizebox{\linewidth}{!}{% \begin{tabular}{|l|cccc|cccc|} \hline \multirow{2}{*}{\tikz[overlay]{\draw (0pt,\ht\tempbox) -- (\wd\tempbox,-\dp\tempbox);}% \usebox{\tempbox}\hspace{\dimexpr 1pt-\tabcolsep}} & \multicolumn{4}{c|}{CIFAR-10} & \multicolumn{4}{c|}{CIFAR-100} \\\cline{2-9} & Natural & Madry & TRADES & ACT & Natural & Madry & TRADES & ACT \\\hline\hline Madry & \bf 15.93 & 49.50 & 35.88 & \bf 35.34 & 43.13 & 75.71 & 61.50 & 60.29 \\ TRADES & 18.23 & 35.84 & 46.49 & 37.11 & 44.25 & 60.80 & 71.20 & \bf 59.97 \\ ACT & 16.93 & \bf 33.65 & \bf 35.14 & 44.04 & \bf 40.80 & \bf 57.17 & \bf 57.32 & 68.61 \\\hline \end{tabular}} \caption{Comparison of ACT with prior defenses (Def) under black-box PGD-20 attack. Surrogate models (Sur) are source models that provide gradients for adversarial attacks. Values indicate the success rate of adversarial attack hence a lower number shows higher robustness.} \label{tab:blackbox} \end{table} \subsection{Results on ImageNet}\label{imagenet} We further demonstrate the effectiveness of our approach on the challenging ImageNet classification task \cite{krizhevsky2012imagenet}. As our approach is designed for untargeted adversarial training, following prior work on untargeted attacks on ImageNet dataset \cite{shafahi2019adversarial,wong2020fast} we train a Resnet-50 model to be robust to untargeted PGD attack with the following parameters: $\epsilon=2/255$, $\eta = 1.0$, and $K = 10$. For our experiments, we use four Tesla V100 GPUs with $\alpha=0.5$, batch size of 128 on each GPU, and train for 100 epochs with an initial learning rate of 0.1 decayed by a factor of 0.1 at 30, 60 and 90 epochs. For a fair comparison, we also train Madry \cite{madry2017towards} under the same experimental setup. Table \ref{tab:imagenet} shows that ACT improves both the generalization and robustness over the standard adversarial training method and its faster variants. As PGD attack is sensitive to the initial randomization, there can be small fluctuations in the final robustness. Therefore, the results for the different PGD attack essentially show that robustness is maintained even as we increase the number of steps. \begin{table}[tb] \center \begin{tabular}{|l|l|ccc|} \hline \multirow{2}{*}{Method} & \multirow{2}{*}{$A_{nat}$} & \multicolumn{3}{c|}{$A_{rob}$} \\ \cline{3-5} & & PGD-10 & PGD-50 & PGD-100 \\ \hline \hline Madry & 65.70 & 42.13 & 42.29 & 42.36 \\ Free (m=4) \cite{shafahi2019adversarial} & 64.45 & 43.52 & 43.39 & 43.40 \\ FGSM \cite{wong2020fast} & 60.90 & 43.46 & - & - \\ ACT & \bf 68.20 & \bf 44.06 & \bf 44.24 & \bf 44.29 \\ \hline \end{tabular \caption{Comparison of ACT with prior defenses under untargeted PGD attack with $\epsilon=2/255$ on the ImageNet dataset.} \label{tab:imagenet} \end{table} \subsection{Gradient obfuscation}\label{grad_obf} \citet{athalye2018obfuscated} showed that most of the proposed defense methods give a false sense of security by reducing the quality of the gradient signal and that these defenses can be circumvented by using gradient approximation techniques. Therefore, it is important to perform a number of sanity checks to ensure that a proposed adversarial defense does not rely on gradient obfuscation. These checks include ensuring that white-box attacks are at least as strong as black-box attacks and that an unconstrained iterative gradient-based attack with an unlimited number of iterations should be completely successful \cite{lamb2019interpolated}. Our evaluations show that black-box attacks are substantially weaker than the corresponding white-box attacks (Tables \ref{tab:comparison1} and \ref{tab:blackbox}). Table \ref{tab:epsilon_eff} shows that the robustness of the model monotonically decreases as we increase the allowed perturbation level for a PGD-100 attack. This shows that the gradients of our method do not impair the ability of the gradient-based attacks through gradient obfuscation. \begin{table}[tb] \centering \begin{tabular}{|l|cccccccc|} \hline Defense & 1 & 5 & 10 & 15 & 20 & 25 & 50 & 100 \\ \hline \hline Madry & \bf 81.90 & 63.53 & 36.69 & 16.61 & 7.01 & 3.31 & 0.22 & 0 \\ \hline TRADES & 80.23 & 65.27 & 42.51 & \bf 23.35 & 11.17 & 5.40 & 0.29 & 0 \\ \hline ACT & 81.47 & \bf 67.15 & \bf 42.98 & 22.45 & \bf 11.18 & \bf 5.74 & \bf 0.42 & 0 \\ \hline \end{tabular} \caption{Accuracy of ResNet-18 with different $\epsilon$ values and a fix number of steps (PGD-100) conducted on CIFAR-10. \label{tab:epsilon_eff}} \end{table} \subsection {Model complexity}\label{model_complexity} The magnitudes of the weights of neural networks can provide an estimate of the model's complexity. Following the analysis presented in \cite{lamb2019interpolated}, we analyze the Frobenius norms of all the weight layers in ResNet-18 for different defense methods trained on CIFAR-10. Fig.\ref{fig:defense_weights_norm} (left) shows that the Frobenius norm of ACT is considerably lower across all the layers. This provides preliminary evidence that ACT trains lower complexity models than standard adversarial training. \begin{figure}[tb] \centering \includegraphics[width=.42\columnwidth]{./figures/defense_weights_norm.pdf} \includegraphics[width=.45\columnwidth]{./figures/information_compression.pdf} \caption{(Left) Comparison of the Frobenius norms of the weights matrix in learnable layers of ResNet-18. (Right) Comparison of the degree to which the different models with frozen learned representation can fit random binary labels.} \label{fig:defense_weights_norm} \end{figure} \subsection{Information compression}\label{info_comp} A number of studies on understanding DNNs from an information theory perspective have shown a relationship between the information compression in the learned features and generalization \cite{tishby2015deep, shwartz2017opening}. They relate stronger compression in DNN's hidden states to a stronger bound on generalization. To study the effect of our proposed method on the compression of information in the learned representation, we follow the analysis performed by \citet{lamb2019interpolated} whereby we freeze the learned representation of the model and study how successful these frozen representations are in predicting fixed random labels. In particular, we add a 2-layer multi-layer perceptron (MLP) network with 400 and 200 neurons on top of the frozen representations of ResNet-18 models trained on CIFAR-10 with different defense methods and fit them on random binary labels. If the model compresses the information well in the learned representations, it will be more difficult to fit the random binary labels. Thereby, lower accuracy shows better information compression. \citet{lamb2019interpolated} showed that standard adversarial training causes the learned representation to be less compressed. To the contrary, Fig.\ref{fig:defense_weights_norm} (right) suggests that both the natural and robust model trained with ACT has more information compression. Interestingly, the models trained with ACT shows higher information compression compared to standard training (normal). This indicates the efficacy of our proposed approach in capturing more information in the hidden states of the models. \subsection{Entropy regularization}\label{entropr_reg} There can be multiple solutions that can fit the training data distribution, but some of these generalize better because of being in wide valleys rather than narrow crevices \cite{chaudhari2019entropy, keskar2016large} whereby the predictions do not change drastically with small perturbations. A number of studies have shown that the tendency towards finding these robust minima can be increased by biasing the DNNs towards solutions with higher posterior entropy \cite{chaudhari2019entropy, pereyra2017regularizing}. We argue that the extra mimicry loss which encourages the model to match the posterior probabilities in ACT has a regularization effect on the logits. The effect is that the model distributes its mass over the secondary classes more uniformly. This can be quantified with the average posterior entropy over the training samples. Fig.\ref{fig:mean_posterior_prob} shows that training with ACT leads to higher posterior entropy solutions. Therefore, the collaborative learning in ACT has a connection to entropy regularisation-based approaches \cite{chaudhari2019entropy, pereyra2017regularizing} to finding wider minima through mutual probability matching on secondary classes. \begin{figure}[tb] \centering \includegraphics[width=.6\columnwidth]{./figures/avg_entropy.pdf} \caption{Average entropy over all training samples obtained by a ResNet-18 on CIFAR-10 and CIFAR-100 datasets. ACT converges to higher posterior entropy solutions.} \label{fig:mean_posterior_prob} \end{figure} \section{Conclusion} We proposed {\it Adversarial Concurrent Training (ACT)} as an efficient approach to training a robust model in conjunction with a natural model. The additional supervision from the natural model allows the robust model to learn richer internal representation which is robust to adversarial perturbations. Our empirical results showed that ACT provides a better trade-off between robustness and generalization across different datasets and network architectures. Furthermore, our analysis suggests that ACT leads to a robust model with lower model complexity, higher information compression in the learned representation, and high posterior entropy solutions indicative of convergence to a flatter minima. The versatility of our proposed approach coupled with the desirable characteristics makes it applicable across a variety of tasks and applications.
{'timestamp': '2020-08-20T02:00:47', 'yymm': '2008', 'arxiv_id': '2008.07015', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07015'}
arxiv
\section{Introduction}\label{sec:introduction}} \IEEEPARstart {T}{emporal} graphs are amongst the best tools to model real-world evolving complex systems such as human interactions, transport networks, the Internet, biological interactions, and scientific networks, to name a few. Understanding the evolving patterns of such networks have important implications in our daily life and predicting future links among the nodes in networks reveals an important aspect of the evolution of temporal networks \cite{Abbasi_2016}. Learning useful representations from networks (or graphs) not only reduces the computational complexity but also provides greater predictive power that facilitates the use of machine learning methods \cite{wang2017knowledge}. To apply mathematical models, networks are represented by adjacency matrices in which only local information of each node is considered are both high-dimensional and generally sparse in nature, and therefore, insufficient for representing global information which are often important features of the network such as nodes' neighbours information. As a result, it cannot be directly used by machine learning models for predicting graph or node level changes. Similarly representing temporal networks using temporal adjacency matrices, as snapshot of the network at different time steps, inherits the same problems and necessitates using alternatives methods. This has led to development of deep neural network based approaches to learn node/edge level features \cite{bengio2013representation}. \par This research presents a new deep learning based model for generating low-dimensional features from large high-dimensional networks considering their temporal information. Our technical contributions are as follows: \begin{enumerate} \item We considered time varying adjacency matrix whose entries are ${e_{i,j,t}} = {e^{t - {t_{now}}}}$, where $t$ is the time step when graph was constructed, and $t_{now}$ is the current time. \item We developed a simple three-layer Graph convolutional feed forward model without implementing nonlinear activation and parameter learning, instead of a complex static generating method. \item We considered angles (using Given's angle method) between any two consecutive time steps, calculated from static generated features, and solved the least square optimization problem using QR factorization method. \end{enumerate} The remainder of the paper is organised as follows. We reviewed some related works in the direction of node embedding. Then we formally defined the problem in Section $3$. In Section $4$ we present our proposed approach for embedding temporal networks, which we refer to as $TempNodeEmb$. We outline our experimental design including data sets, evaluation metrics and benchmark methods in Section $5$, and present the results in Section $6$. We close the paper in Section $7$ with a discussion and our conclusions . \section{Related Works} Currently deep learning based framework is found to be very effective in learning low-dimensional representation for euclidean data such as image video or audio, meaning these data sets can be easily represented in the form of grid structure without loss of information. Network embedding, as such an approach, is developed for learning hidden representations of nodes in a network to encode links in a continuous vector space to facilitate the use of statistical models \cite{perozzi2014deepwalk}. In other words, very large high-dimensional and sparse networks embeds into low-dimensional vectors \cite{tang2015line}, while integrating global structure of the network (maintaining the neighbourhood information) into the learning process \cite{cao2015grarep}, that has applications in tasks such as node classification, visualization, link prediction, and recommendation \cite{tang2015line, mahdavi2018dynnode2vec}. Although network embedding models are best to capture network structural information, they lack considering temporal granularity and fail in temporal level predictions such as temporal link prediction, and evolving communities prediction. One solution for generating node embedding in temporal network is to generate static embedding for each time step and find node level orientation based on previously generated features \cite{haddad2019temporalnode2vec, singer2019node}. Network evolution studies have been at the center of network studies \cite{leskovec2005graphs, Abbas2018Popularity, yu2016network, albert2002statistical, trivedi2017know} and in particular on addressing link prediction \cite{lu2011link}. Apart from traditional machine learning and statistical modeling approaches currently deep neural networks are also being developed \cite{cui2018survey}. These models effectively generate a $d$ (lower than total number of nodes in graph) dimensional feature vector based on graph structure, which can be fed into any machine learning model. Some researchers came up with matrix factorization approach \cite{cao2015grarep,ou2016asymmetric}. Further researchers have used deep neural networks auto-encoders \cite{cao2016deep,wang2016structural}, convolutional neural networks\cite{kipf2016semi} often considering random walks \cite{chen2018harp,perozzi2014deepwalk,grover2016node2vec}. All these methods considered only static nature of the graph, and only recently some researchers considered temporal aspect of the network for low-dimensional node feature embedding \cite{mahdavi2018dynnode2vec, NguyenContinousTime2018, peng2019dynamic,li2018deep}. Methods for embedding network temporal behaviour are developed and among them is applying a static method at every time-step and minimizing error based on consecutive time step embedding \cite{singer2019node}. \section{Problem definition} Graphs are the best choice in representing implicit or explicit relationship among entities and are recently emerged as one of the best data structure to store such heterogeneity in data. Graphs are composed of a set of nodes $V = \{ {v_1},{v_2}...,{v_{\left| V \right|}}\}$ and a set of edges ${E_{}} = {e_{i,j}}$ that reflect a connection between each pair of nodes. However, when we model the real interactions in our daily life, the associated edges ${E_T} = {e_{i,j,t}}$ contains a time stamp $t$, where $i,j,t$ represents an interaction between node $v_i$ and $v_j$ at time $t$. So, a dynamic or temporal graph $G$ can be represented by a three tuple set $G(V,E_T)$: $G_t$, the graph at time $t$, contains all the edges which has been formed before time $t$. For training our model, we considered $T$ time slices such that $t \in [1,T]$. Consequently we use $T$ set of temporal graphs ${G_1},{G_2}....,{G_T}$. So, we aim to predict if an edge will be formed between two nodes $v_i$ and $v_j$ at time $T+t'$.\par \begin{figure*}[!t] \centerline{\includegraphics[width=0.9\textwidth]{modelFrameWork}} \caption{This is the proposed model framework to generate $d$ dimensional node embedding for temporal graphs.} \label{fig:modelFramework} \end{figure*} \section{Method} In this section we describe our proposed method and its main contributions. In Fig. \ref{fig:modelFramework}, we show our proposed framework that includes the following steps: \begin{comment} \subsection{Graph convolution operation} At every time step $t$ from training set, we generate a $d$ (${\rm{d < < < |V|}}$, $|V|$ is the number of nodes in the graph) dimensional feature vector for every node, by applying the following convolution operation. For a given graph $G(V,E)$, at time $t$ we apply the Graph Convolution as follows: \begin{enumerate} \item the timed adjacency matrix is represented as $A_t$ at time $t$ with size $|V|\times |V|$. We add self-loop by adding identity matrix $I; $ ${{\hat A}_t} = {A_t} + I$, where only diagonal elements are $1$ and rest elements are $0$ (represents only self-loops: node $i$ links to itself). \item Further we create a temporal edge influence matrix: $A_{i,j}(t)$. \item Suppose every node has its own feature vector of size $F^0$, there will be a feature matrix of size ($|V|\times F^0$). \item Using temporal edge influence matrix and node feature matrix, we apply simple convolution operations without non-linear activation operation. \\ \end{enumerate} \\ \end{comment} \subsection{Temporal edge influence matrix} To consider temporal influence of nodes, we considered that edge influence of a node decreases exponentially. Suppose time adjacency matrix at any time $t$ is represented by $A_{i,j}(t)$, the temporal influence matrix ($A{e_{i,j}}(t)$) at any time can be formulated as: \begin{equation} A{e_{i,j}}(t) = {e^{t - {t_{now}}}} \times ({A_{i,j}}(t) + I) \end{equation} where, $I$ is identity matrix, as above. \\ \subsection{Generating Static Embedding} At every time step, we generate a static $d$-dimensional embedding for every node $v$, using a three-layer of convolutional neural network. We generate a static embedding matrix $\Theta _t$ at every time step $t$, which we use the simplest convolutional forward prorogation model as follows: \begin{equation} f({R^l},A) = {{\hat A}_{et}}{R^l}{W^l} \end{equation} where $R^l$ is hidden representation and $W^l$ is a random weight matrix at layer $l$, and $R^0 = I$; as we do not have node level features at time 0. Two things to notice here is that, we do not apply either the degree matrix normalization technique \cite{kipf2016semi} nor nonlinear activation. As we are generating embedding without supervised learning. Considering the non-linear activation was not giving us good results.\\ \subsection{Loss function and learning representation} Our aim is to learn feature vector at time step $T$ using function ${{\rm{l}}_{\rm{T}}}{\rm{(v)}}$. For temporal link prediction tasks, we learn the parameter using cross entropy loss, as follows: \begin{equation} Cost(p,\widehat p) = - p\log (\widehat p) - (1 - p)\log (1 - \widehat {{p}}) \label{binaryCrossEntropy} \end{equation} where $p$ is the actual label and $\widehat p$ is the predicted label. As link prediction tasks happens between two nodes, we used concatenation function. Although it can be any function according to requirements. Further we learn the ${{\rm{l}}_{\rm{T}}}{\rm{(v)}}$ as follows: \begin{equation} {{\rm{l}}_{\rm{T}}}{\rm{(v) = }}{{\rm{L}}_T}(v,{G_1},{G_2},....,{G_T}) \end{equation} Further we learn the final orientation using recursive function, described by Singer et al. \cite{singer2019node} as follows: \begin{equation} {{\rm{l}}_{\rm{T}}}({\rm{v}}){\rm{ = }}\sigma ({A_{et}}{l_t}(v) + B{\Theta _t}{\Phi _t}v) \end{equation} where ${A_{te}},B,{\Theta _t},{\Phi _t}$ are matrices which are learned during training and $\sigma $ is activation function. In our case, we use $\tanh$ function, where $\Theta _t$ is the static feature matrix at time $t$. \break \subsection{Calculating node alignment} One of the important tasks in modeling temporal networks embedding is finding node alignments over time. In this work, we calculate the angle between node vectors (feature spaces). Instead of calculating the angles between two nodes, we calculate how node's individual features are changing. As two features, at times $t$ and $t+1$, lie in the same euclidean space, we consider the angle between features at two different time steps as described by angles between two scalars \cite{demmel1990matrix}. \break Using the two adjacency matrices of a graph at times $t$ and $t+1$, we create the angle between its individual features using Algo. \ref{algo:calculatingAngles}. In order to know how each feature aligns over time, we create matrices $\Theta _{\cos \alpha }$ and $\Theta _{\cos \beta }$. Furthermore, we apply dot operations so as to find the angle orientation with respect to the other nodes i.e. matrix $C_t = {\Theta ^T}_{\scriptstyle\cos \beta \hfill\atop \scriptstyle\hfill} \times {\Theta _{\cos \alpha }}$. To find a stable matrix between any two consecutive snapshots, we find orthogonal matrix $Q_t$ using the decomposition method $i.e. C_t = Q_t * R_t$ (i.e. we used QR decomposition method). By using recursive function, we find stable basis column matrix of $Q_t$ (at least first $k$ columns will be ortho-normal basis) which can be used to project snapshot of network at $t$ to future time $t+1$. \begin{algorithm} \caption{Calculating the angles($x_{v}(t,i)$),$x_{v}(t+1,i)$} \begin{algorithmic} \IF{$x_{v}(t+1)=0$} \STATE $cos\alpha=1;cos\beta=0$ \ELSE \IF{$|x_{v}(t+1,i)| > |x_{v}(t,i)|$} \STATE $tmp=-x_{v}(t,i)/x_{v}(t+1,i)$ \STATE$cos\beta=1/\sqrt {1 + tm{p^2}}$ \STATE$cos\alpha=tmp.cos\beta$ \ELSE \STATE $tmp=-x_{v}(t+1,i)/x_{v}(t,i)$ \STATE$cos\alpha=1/\sqrt {1 + tm{p^2}}$ \STATE$cos\beta=tmp.cos\alpha$ \ENDIF \ENDIF \\ \Return $cos\alpha, cos\beta$ \end{algorithmic} \label{algo:calculatingAngles} \end{algorithm} \subsection{Learning for link prediction} After getting $d$ dimensional stable aligned vector for each node and each time, we use recurrent neural network and in particular the Gated Recurrent Units \cite{cho2014learning}, which is a new kind of gating mechanism that has two gates, namely reset and update, and fewer parameters than 'long short-term memory' (LSTM) as an artificial recurrent neural network architecture. This way, we train the network by formulating our link prediction problem as a binary classification problem. Further we concatenate the features of any two nodes so that neural network can learn probability scores of having a link between any two nodes. We use binary cross entropy loss as in equation \ref{binaryCrossEntropy}. \subsection{Optimization algorithm} For parameter learning, we use Adam optimizer \cite{kingma2014adam}, which calculates an exponentially weighted average of past gradients and removes biases ($v^{corrected}$). Further, it calculates the exponentially weighted average of the squares of the past gradients and removes biases($s^{corrected}$). The details are as follows: \begin{equation} {v_{d{W^{[l]}}}} = {\beta _1}{v_{d{W^{[l]}}}} + (1 - {\beta _1})d{W^{[l]}}v_{d{W^{[l]}}}^{corrected} = \frac{{{v_{d{W^{[l]}}}}}}{{1 - {{({\beta _1})}^t}}} \end{equation} \begin{equation} {s_{d{W^{[l]}}}} = {\beta _2}{s_{d{W^{[l]}}}} + (1 - {\beta _2}){(d{W^{[l]}})^2}s_{d{W^{[l]}}}^{corrected} = \frac{{{s_{d{W^{[l]}}}}}}{{1 - {{({\beta _1})}^t}}} \end{equation} \begin{equation} W^{[l]} = W^{[l]} - \alpha \frac{v^{corrected}_{dW^{[l]}}}{\sqrt{s^{corrected}_{dW^{[l]}}} + \varepsilon} \end{equation} \begin{equation} b^{[l]} = b^{[l]} - \alpha \frac{v^{corrected}_{db^{[l]}}}{\sqrt{s^{corrected}_{db^{[l]}}} + \varepsilon} \end{equation} where, $t$ counts the number of steps taken of Adam, $l$ is the number of layers ($1,2,3$), $\beta_1$ and $\beta_2$ are hyper-parameters that control the two exponentially weighted averages. $\alpha$ is the learning rate. $\varepsilon$ is a very small number to avoid dividing by zero. Following the same aforementioned steps, parameter $b^{[l]}$ is also updated for each layer $l$. \\ \section{Experimental Design} In this section, we discuss our approach to evaluate our proposed method compared to relevant approaches on temporal link prediction using node embedding. Temporal link prediction problem is to predict if any two nodes will be connected by t+1 or not. To achieve this, we divide the temporal network data sets into two parts based on a pivot time, considering $70\%$ edges remains for training and the remaining $30\%$ for testing purpose. So all the edges formed at or before the pivot time are considered positive examples for training set. All the edges formed after pivot time and before future test time point is considered as positive test example for testing. Almost similar number of edges are randomly sampled to create negative examples. For negative test examples, we sample similar number to the positive test examples which have not been formed at any time. \par \subsection{Baseline Methods} To evaluate the performance of our proposed model, we compared it with state-of-the-art temporal embedding as well static node embedding methods, as follows: \begin{enumerate} \item \textbf{tNodeEmbed \cite{singer2019node} }: This method is state-of-the art for node embedding for dynamic graphs. It learns embedding by first generating static embedding and then finding node alignment. Further it can fed to recurrent neural network for task oriented predictions. \item\textbf{Prone \cite{ijcai2019ProNE}}: This method first initializes the embedding using sparse matrix factorization and spectral analysis for local and global structural information. \\ \item\textbf{DeepWalk\cite{perozzi2014deepwalk}}: This model learns node low dimensional embedding based on random walks. It has two hyper-parameter: walk length $l$, and window size $w$. \\ \item\textbf{Node2vec \cite{grover2016node2vec}}: It is a similar model for graphs which works on similar principal of Word2vec model \cite{mikolov2013efficient}, as a state-of-the-art framework for word embedding in natural language processing. Based on similar skip-gram concept node2vec works on neighbourhood node and generates low-dimensional embedding. Node2vec can be generalized according to need such as if one wants to embedd similarity based on distance or based on role of the node in network. \\ \item\textbf{LINE \cite{tang2015line}}: This model generate node low level embedding considering first order and second order node similarity. Furthermore, this model uses sampling based on edge weights which also improves the performance for large scale networks. It is special case of DeepWalk when the size of vertices context is kept $1$. \\ \item\textbf{Hope \cite{ou2016asymmetric}}: The High-Order Proximity preserved Embedding method is based on PageRank and Katz index. This method uses singular value decomposition for making low rank approximations. \par \end{enumerate} \subsection{Evaluation metrics} \textbf{ROAUC}: The $ROAUC$ (aka $ROC$) is area under plot between True Positive Rate ($TPR$) and False Positive Rate ($FPR$). It depicts the trade-off between true positive and false positive prediction rate. The $TPR$ is also known as sensitivity, recall or probability of detection. ROAUC gives measure of separability of the classifier, therefore it is a vital metrics in our case also. \\ \textbf{PRAUC}: The PRAUC is the area under Precision and Recall curve, which is used to estimate the accuracy between precision and recall both at one time. In other words, precision recall pair points are obtained by considering different threshold values. Therefore, it is used to estimate efficiency for imbalance class and proves model's ability to work for skewed distributed datasets. \par \subsection{Datasets} The following real-world datasets are used in our experiments: \begin{enumerate} \item \textbf{MIT human contact (MITC) network} (from \cite{realityMiningMIT2015Download}). This undirected network contains human contact data among students of the Massachusetts Institute of Technology (MIT), collected by the Reality Mining experiment performed in $2004$ as part of the Reality Commons project \cite{realityMiningMIT2015}. A node represents a person and an edge indicates the corresponding nodes have physical contacts. The data was collected over $9$ months using mobile phones. A daily granularity is used for time steps in this dataset. \\ \item \textbf{College text message (COLLMsg) network}. Data was gathered though a Facebook like social networking app used at University of California Irvine. Nodes are people and a directed edge represent a message has send from one user to another. A daily granularity between $15th$ April $2004$ to $26th$ October $2004$ is used for time steps. \\ \item \textbf{Protein-Protein interaction (PPI) network} (from \cite{singer2019node}). It includes protein as nodes and edges between any pair of proteins exist if they are biologically interacted. We consider the interaction discovery dates as the edge’s timestamp. \\ \item \textbf{Wikipedia news edits (WikiEdit) network} (from \cite{nr-aaai15}). This is a dataset for user edits on wiki news. A monthly granularity is used for time steps in this dataset. \\ \end{enumerate} Table \ref{tab:datasetProperties} provides basic properties of datasets including the number of nodes, links and the average degree of networks. \begin{table} \centering \def\~{\hphantom{0}} \begin{minipage}{130mm} \caption{Properties of the dataset used in our experiments} \label{tab:datasetProperties} \begin{tabular*}{20pc}{c|c|c|c} \hline & \textbf{No of Nodes} & \textbf{No of edges} & \textbf{Average degree} \\ \hline \textbf{MITC} & 96 & 2539 & 52.8958 \\ \hline \textbf{COLLMsg} & 1,899 & 59835 & 14.5729 \\ \hline \textbf{PPI} & 16,458 & 144,033 & 17.5031 \\ \hline \textbf{WikiEdit} & 25042 & 68678 & 5.485 \end{tabular*} \end{minipage} \vspace*{-6pt} \end{table} \section{Results} The performance of our proposed link prediction models ($TempNodeEmb_{Static}$ and $TempNodeEmb$) compared to baselines models on four real datasets are reported in Table \ref{aucPerformanceTable}. As shown, our temporal proposed model ($TempNodeEmb$) outperforms all the models and on all the data sets except in two cases. Deepwalk method performs slightly better than $TempNodeEmb$ on MIT Human contact network (MITC) considering both evaluations metrics, while its performance is not on top list among other models for the other three datasets. The small size of MITC dataset might be a key factor on the high performance of Deepwalk model, in another case, tNodeEmbed performs better on WikiEdit network considering ROC metric, while again tNodeEmbed performance in rest of the cases is not as good as Prone and Hope. Here $TempNodeEmb_{Static}$ is a model we used to generate the static embedding at each temporal point during training process. We also want to emphasis that as Graph Convolutional model uses node level explicit features, and therefore, our model can consider node level features along with network structural features. Due to absence of node level features, we used only one hot vector for each node. We believe our model's accuracy will improve when we use node level explicit features along with temporal and graph level features. \begin{table*}[!t] \centering \def\~{\hphantom{0}} \begin{minipage}{130mm} \caption{Comparing performance of link prediction models (rows) on four real datasets (columns) considering ROC-AUC(ROC) and Precision-AUC(PRAUC) evaluation metrics} \label{aucPerformanceTable} \begin{tabular*}{30.5pc} {|c | c c | c c | c c | c c | } \bf Datasets & \multicolumn{2}{l}{\qquad \bf PPI} &\multicolumn{2}{l}{\qquad \bf COLLMsg} & \multicolumn{2}{l}{\qquad \bf MITC} & \multicolumn{2}{l}{\qquad \bf WikiEdit} \\ \hline \bf Models &\bf ROC &\bf PRAUC&\bf ROC &\bf PRAUC&\bf ROC &\bf PRAUC&\bf ROC & \bf PRAUC \\ \hline \bf Prone & 0.756 & 0.766 & 0.620 & 0.606 & 0.692 & 0.668 & 0.782 & 0.785 \\ \hline \bf Node2vec & 0.693 & 0.688 & 0.533 & 0.530 & 0.588 & 0.582 & 0.717 & 0.714 \\ \hline \bf Line & 0.700 & 0.697 & 0.559 & 0.533 & 0.618 & 0.606 & 0.690 & 0.682 \\ \hline \bf Hope & 0.787 & 0.791 & 0.640 & 0.621 & 0.677 & 0.646 & 0.741 & 0.761 \\ \hline \bf Deepwalk & 0.690 & 0.684 & 0.525 & 0.514 & \bf 0.706 & \bf 0.675 & 0.720 & 0.732 \\ \hline \bf $TempNodeEmb_{Static}$ & 0.687 & 0.685 & 0.613 & 0.662 & 0.553 & 0.555 & 0.691 & 0.694 \\ \hline \bf tNodeEmbed & 0.759 & 0.766 & 0.602 & 0.600 & 0.640 & 0.607 & \bf 0.798 & 0.774\\ \hline \bf $TempNodeEmb$ & \bf 0.818 &\bf 0.821 & \bf 0.776 & \bf 0.762 & 0.690 & 0.652 & 0.782 & \bf 0.798 \\ \hline \end{tabular*} \end{minipage} \vspace*{-6pt} \end{table*} \section{Conclusion} Temporal node embedding has just gaining attention recently. As it provide not only node level task such as link prediction, node classification or anomaly detection but can also be applied for graph level prediction tasks such as community detection. In this work we presented an model to generate node embedding in temporal graphs. The embedding we present is very simple and effective. To achieve this, we created a temporal influence matrix and generated static embedding of nodes at each time step, applying basic 3-step forward graph convolutional operations. The only difference here is that we did not use degree matrix normalization trick as our matrices are already normalized, i.e. its entries lie between $[0,1]$ due to exponential decay operator. The second most important difference is that we did not apply any non-linear activation function. Just only 3-step convolutional operations makes performance efficient as compared to tNodeEmbed model which is based on Node2Vec. Furthermore, tNodeEmbed method does not allow node level explicit feature consideration, while our model allows node level explicit feature consideration. \\ In this work, as the node level features are not available, we therefore initialized features as one-hot vectors. To evaluate the performance of our temporal link prediction model, we used five static and one dynamic link prediction models as benchmarks. Although our current work proves to be better than state-of-the art but in future we will try to improve its performance further, as learning static feature vector and alignment at each time-step is computational in-efficient as compared to models for static graphs. \ifCLASSOPTIONcompsoc \section*{Acknowledgments} \else \section*{Acknowledgment} \fi This work is supported in part by the Key Scientific and Technological Research Projects in Henan Province under Grants ($202102210379$,$182102210152$, $182102310034$), Zhoukou Normal University super scientific project $ZKNUC2018019$, Key scientific research projects of Henan Provincial Department of Education $20A520046$, Chinese National Natural Science Foundation under grant No. $61602202$, the Natural Science Foundation of Jiangsu Province under contracts $BK20160428$, the Six talent peaks project in Jiangsu Province under contract $XYDXX-034$ and the project in Jiangsu Association for science and technology. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2020-08-18T02:18:24', 'yymm': '2008', 'arxiv_id': '2008.06940', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06940'}
arxiv
\section{Introduction} Person re-identification (ReID) \cite{gong2014person,zheng2016person} aims to match images of a person across disjoint cameras, which is widely used in video surveillance, security and smart city. Many methods \cite{ma2014covariance,yang2014salient,liao2015person,zheng2013reidentification,koestinger2012large,liao2015efficient,zheng2016person,hermans2017defense,sun2018beyond} have been proposed for person ReID. However, for higher accuracy, most of them utilize a large deep network to learn high-dimensional real-value features for computing similarities by Euclidean distance and returning a rank list by quick-sort \cite{hoare1962quicksort}. Quick-sort of high-dimensional deep features can be slow, especially when the gallery set is large. Table \ref{table:sort_time} shows that the query time per ReID probe image increases massively with the increase of the ReID gallery size; and counting-sort \cite{bajpai2014implementing} is much more efficient than quick-sort, in which the former has a linear complexity w.r.t the gallery size ($O(n)$) whilst the latter has a logarithm complexity ($O(nlogn)$). Several fast ReID methods \cite{chen2016person,zheng2016learning,wu2017structured,zhu2017part,chen2017fast,fang2018perceptual,zhu2018fast,liu2019adversarial} have been proposed to increase ReID speed whist retaining ReID accuracy. The common main idea is hashing, which learns a binary code instead of real-value features. To sort binary codes, the inefficient Euclidean distance and quick-sort are replaced by the Hamming-distance and counting-sort \cite{bajpai2014implementing}. Table \ref{table:distance_time} shows that computing a Hamming distance between 2048-dimensional binary-codes is $229\times$ faster than that of a Euclidean distance between real-value features. \begin{table*}[t] \begin{floatrow} \capbtabbox{ \begin{tabular}{c|cc} \hline \hline \multirow{1}{*}{Gallery} & \multicolumn{2}{c}{Query Time (s)} \\ \multirow{1}{*}{Size} & \multicolumn{1}{c}{ \ \ Quick-Sort \ \ } & \multicolumn{1}{c}{Counting-Sort}\\ \hline $1 \times 10^3$ & $3.4 \times 10^{-3}$ & $4.7 \times 10^{-4}$ \\ $1 \times 10^4$ & $1.0 \times 10^{-1}$ & $2.7 \times 10^{-3}$ \\ $1 \times 10^5$ & $4.3 \times 10^{-1}$ & $2.7 \times 10^{-2}$ \\ $1 \times 10^6$ & $6.4 \times 10^{0}$ \ \ & $2.6 \times 10^{-1}$ \\ $1 \times 10^7$ & $1.1 \times 10^{2}$ \ \ & $2.7 \times 10^{0}$ \ \ \\ \hline Per Sample & - & $2.6 \times 10^{-7}$ \\ Complexity & $O(nlogn)$ & $O(n)$ \\ \hline \hline \end{tabular} }{ \caption{ReID search time per probe image by quick-sort (real-value) and counting-sort (binary). The latter is much faster.} \label{table:sort_time} } \capbtabbox{ \begin{tabular}{c|cc} \hline \hline \multirow{1}{*}{Code} & \multicolumn{2}{c}{Computation Time (s)} \\ \multirow{1}{*}{Length} & \ \ Euclidean \ \ & \ \ Hamming \ \ \\ \hline $32$ & $6.8 \times 10^{-5}$ & $2.4 \times 10^{-6}$ \\ $64$ & $1.3 \times 10^{-4}$ & $2.7 \times 10^{-6}$ \\ $128$ & $2.6 \times 10^{-4}$ & $2.8 \times 10^{-6}$ \\ $256$ & $5.0 \times 10^{-4}$ & $3.3 \times 10^{-6}$ \\ $512$ & $1.0 \times 10^{-3}$ & $4.4 \times 10^{-6}$ \\ $1,024$ & $2.0 \times 10^{-3}$ & $7.1 \times 10^{-6}$ \\ $2,048$ & $3.9 \times 10^{-3}$ & $1.7 \times 10^{-5}$ \\ \hline \hline \end{tabular} }{ \caption{Comparing Euclidean and Hamming distances, Euclidean and longer lengths are slow to compute.} \label{table:distance_time} } \end{floatrow} \end{table*} Different from common image retrieval tasks, which are category-level matching in a close-set, ReID is instance-level matching in an open-set (zero-shot setting). For image retrieval in the ImageNet \cite{russakovsky2015imagenet}, the classes of training and test sets are the same and imagery appearances of different classes diverse a lot, such as dog, car, and airplane. In contrast, the training and test ReID images have completely different ID classes without any overlap (ZSL) whilst the appearances of different persons can be very similar to subtle changes (fine-grained) on clothing, body characteristics, gender, and carried-objects. The ZSL and fine-grained characteristics of ReID require state-of-the-art hashing-based fast ReID models \cite{liu2019adversarial} to employ very long binary codes, \textit{e.g.} 2048, in order to retain competitive ReID accuracy. However, the binary code length affects significantly the cost of computing Hamming distance. Table \ref{table:distance_time} shows that computing a Hamming distance between two 2048-dimensional binary codes takes $1.7\times10^{-5}$ seconds, which is $7\times$ slower than computing that of 32-dimensional binary codes at $2.4\times10^{-6}$ seconds. This motivates us to solve the following problem: How to yield higher accuracy from hashing-based ReID using shorter binary codes. \begin{figure}[t] \center \includegraphics[scale=0.4]{materials/coarse-to-fine.pdf} \caption{A Coarse-to-Fine (CtF) hashing code search strategy to speed up ReID, where $Q$ is a query image, $\{G_i\}_{i=1}^{3}$ are the positive images in the gallery set, $B=\{b_k\}_{k=1}^{N}$ are binary codes of lengths $L=\{l_k\}_{k=1}^{N}$, $T=\{k_i\}_{k=2}^{N}$ are Hamming distance thresholds where gallery images are selected by each $t_k$ for further comparison by increasingly longer codes $b_{k}$. } \label{figure:coarse-to-fine strategy} \end{figure} To that end, we propose a novel Coarse-to-Fine (CtF) search strategy for faster ReID whilst also retaining competitive accuracy. At test time, our model (CtF) first uses shorter codes to coarsely rank a gallery, then iteratively utilises longer codes to further rank selected top candidates where the top-ranked candidates are defined iteratively by a set of Hamming distance thresholds. Thus, the long codes are only used for a decreasingly fewer matches in ranking in order to reduce the overall search time whilst retaining ReID accuracy. This is an intuitively straightforward idea but not easily computable for ReID due to three difficulties: (1) Coarse-to-fine search requires multiple codes of different lengths. Asymmetrically, computing them with multiple models is both time-consuming and sub-optimal. (2) The coarse ranking must be accurate enough to minimise missing true-match candidates in fine-grained ranking whilst keeping their numbers small, thus reduce the total search time. Paradoxically, shorter codes perform much worse than longer codes in ReID task therefore hard to be sufficiently accurate. (3) The set of distance thresholds for guiding the coarse search affect both final accuracy and overall speed. How to determine {\em automatically} these thresholds to balance optimally accuracy and speed is both important and nontrivial. In this work, we propose a novel All-in-One (AiO) framework together with a Distance Threshold Optimization (DTO) algorithm to simultaneously solve these three problems. The AiO framework can simultaneously learn and enhance multiple codes of different lengths in a single model. It progressively learns multiple codes in a pyramid structure, where the knowledge from the bottom long code is shared by the top short code. We promote shorter codes to mimic longer codes by both probability- and similarity- distillation. This makes shorter codes more powerful without importing extra teacher networks. The DTO algorithm solves a complex threshold search problem by a simple optimization process and the balance between search accuracy and speed is easily controlled by a single parameter. It explores a $F_{\beta}$ score as the optimization target formulated as Gaussian cumulative distribution functions. So that we can estimate its parameters by the statistics of Gaussian probability distributions modeling the distances of positive and negative pairs. Finally, by maximizing the $F_{\beta}$ score, we compute iteratively optimal distance thresholds. Our contributions are: (1) We propose a novel Coarse-to-Fine (CtF) search strategy for Faster ReID, not only speeding up hashing ReID, but also improving their accuracy. To the best of our knowledge, this is the first work to introduce such search strategy into ReID. (2) A novel All-in-One (AiO) framework is proposed to learn and enhance multiple codes of different lengths in a single framework by viewing it as a multi-channel self-distillation problem. In the framework, the multiple codes are learned in a pyramid structure and shorter codes mimic longer codes via probability- and similarity- distillation loss. (3) A novel Distance Threshold Optimization (DTO) algorithm is proposed to find the optimal thresholds for coarse-to-fine search by concluding the threshold search task to a $F_{\beta}$ distance optimization problem. The $F_{\beta}$ score is represented with Gaussian cumulative distribution functions, whose mean and variance can be estimated by fitting a small validation set. (4) Extensive experimental results on two datasets show that, our proposed method is $50\times$ faster than non-hashing ReID methods, $5\times$ faster and $8\%$ more accurate than hashing ReID methods. \section{Related Works} In this work, we wish to solve the fast ReID problem under the framework of hashing by proposing an All-in-One (AiO) hashing learning module and a Distance Threshold Optimization (DTO) algorithm. Thus, we mainly discuss the related works including non-fast person re-identification (ReID) task, fast ReID task and hashing algorithm. \textbf{Person Re-Identification.} Person re-identification addresses the problem of matching pedestrian images across disjoint cameras \cite{gong2014person}. The key challenges lie in the large intra-class and small inter-class variation caused by different views, poses, illuminations, and occlusions. Existing methods can be grouped into hand-crafted descriptors \cite{ma2014covariance,yang2014salient,liao2015person}, metric learning methods \cite{zheng2013reidentification,koestinger2012large,liao2015efficient} and deep learning algorithms \cite{zheng2016person,hermans2017defense,sun2018beyond,wang2019rgb,wang2019color,wang2020cross,wang2020high}. The goal of hand-crafted descriptors is to design robust features. Metric learning aims to make a pair of true matches have a relatively smaller distance than that of a wrong match pair in a discriminant manner. Deep learning algorithms adopt deep neural networks to straightly learn robust and discriminative features in an end-to-end manner and achieve the best performance. However, all the ReID methods above learn real-value features for high accuracy, which is slow. \textbf{Hashing Algorithm.} Hashing algorithm mainly divided into unsupervised and (semi-)supervised ones. Unsupervised hashing methods (LSH \cite{Datar2004Locality}, SH \cite{Weiss2008Spectral}, ITQ \cite{Lazebnik2011Iterative}) employ unlabeled data even no data. (Semi-)Supervised (SSH \cite{Wang2012Semi}, BRE \cite{Kulis2009Learning}, KSH \cite{Liu2012Supervised}, SDH \cite{Shen2015Supervised}, SSGAH\cite{wang2018semi}) utilize labeled information to improve binary codes. Recently, inspired by powerful deep networks, some deep hashing methods (CNNH \cite{Xia2014Supervised}, NINH \cite{Lai2015Simultaneous}, DPSH \cite{Li2016Feature}) have been proposed and achieve much better performance. They usually utilize a CNN to extract meaningful features, formulate the hashing function as a fully-connected layer with $tanh/sigmoid$ activation function, and quantize features by $signature$ function. The framework can be optimized with a related layer or some iteration strategies. However, all the hashing methods are designed for close-set category-level retrieval tasks, which cannot be directly used for person ReID, an open-set fine-grained search problem. \textbf{Fast Person Re-Identification.} Fast ReID methods aims to search in a fast speed meanwhile obtaining accuracy as high as possible. The main idea of those methods is hashing algorithm, which learns binary code instead of real-value features. Based on the binary codes, the inefficient Euclidean distance and quick-sorting can be replaced by efficient Hamming distance and counting sort. Zheng \textit{et al.} \cite{zheng2016learning} learn cross-view binary codes using two hash functions for two different views. Wu \textit{et al.} \cite{wu2017structured} simultaneously learn both CNN feature and hash functions to get robust yet discriminative features and similarity-preserving binary codes. CSBT \cite{chen2017fast} solves the cross-camera variations problem by employing a subspace projection to maximize intra-person similarity and inter-person discrepancies. In \cite{zhu2017part} integrate spatial information for discriminative features by representing horizontal parts to binary codes. ABC \cite{liu2019adversarial} improves binary codes by implicitly fits the feature distribution to a pre-defined binary one with Wasserstein distance. However, all the fast ReID methods take very long binary codes (\textit{e.g.} 2048) for high accuracy. Different from them, we propose a coarse-to-fine search strategy which complementarily uses codes of different lengths, obtaining not only faster speed but also higher accuracy. \section{Proposed Method} In this work, we propose a coarse-to-fine (CtF) search strategy for fast and accurate ReID. For effectively implementing the strategy, we design an All-in-One (AiO) framework together with a Distance Threshold Optimization (DTO) algorithm. The former learns and enhances multiple codes of different lengths in a single framework. The latter finds the optimal distance thresholds to balance time and accuracy. \subsection{Coarse-to-Fine Search} As we illustrated in the introduction section, although the long binary codes can get high accuracy, it takes much longer time than short codes. This motivates us to think about that can we reduce the usage of long codes to further speed hashing ReID methods up. Thus, a simple but efficient solution is complementarily using both short and long codes. Here, shorter codes fast return a rough rank list of gallery, and longer codes carefully refine a small number of top candidates. Figure \ref{figure:coarse-to-fine strategy} shows its procedures. Although the idea is straightforward, there are still three difficulties preventing it being applied to ReID. (1) Coarse-to-fine search requires multiple codes of different lengths. Asymmetrically, computing them with multiple models is both time-consuming and sub-optimal. (2) The coarse ranking must be accurate enough to minimise missing true-match candidates in fine-grained ranking whilst keeping their numbers small, thus reduce the total search time. Paradoxically, shorter codes perform much worse than longer codes in ReID task. (3) The set of distance thresholds for guiding the coarse search affect both final accuracy and overall speed. How to determine {\em automatically} these thresholds to balance optimally accuracy and speed is both important and nontrivial. To solve the problems, we propose an All-in-One (AiO) framework and a Distance Threshold Optimization (DTO) algorithm. Please see the next two parts for more details. \subsection{All-in-One Framework} \begin{figure}[t] \center \includegraphics[width=\linewidth]{materials/all-in-one-framework.pdf} \caption{All-in-One framework. It learns and enhances multiple codes of different lengths in a single framework with a code pyramid structure and self-distillation learning. } \label{figure:aio-framework} \end{figure} The All-in-One (AiO) framework aims to simultaneously learn and enhance multiple codes of different lengths in a single model, whose architecture can be seen in Figure \ref{figure:aio-framework}. Specifically, it first utilizes a convolutional network to extract the real-value feature vectors, then learns multiple codes of different lengths in a pyramid structure, finally enhances the codes by encouraging shorter codes mimic longer codes via self-distillation. \noindent \textbf{Learn Multiple Codes in a Pyramid Structure.} The code pyramid learns multiple codes of different lengths, where the shorter codes are based on the longer codes. With such a structure, we can not only learn many codes in one shot, but also share the knowledge of longer codes with shorter codes. The equations are as below: \begin{equation} v_{0} = F(x), \ \ v_{k} = FC_{k}(v_{k-1}), \ \ k \in {1, 2, ..., N}, \label{eq:hash-func} \end{equation} where $x$ is input image, $F$ is the CNN backbone, $N$ is the code number, $V = \{v_k\}_{k=1}^{N}$ are the real-value feature vectors with different lengths $L = \{l_k\}_{k=1}^{N}$, $FC_k$ is the fully-connected layers with $l_{k-1}$ input- and $l_{k}$ output-sizes. After getting real-value features of different lengths, we can obtain their binary codes $B = \{b_{k}\}_{k=1}^{N}$ in the following equation. \begin{equation} b_{k} = sgn(bn(v_{k})), \label{eq:quantization-func} \end{equation} where $bn$ is the batch normalization layer, $sgn$ is the symbolic function. We use the batch normalization layer because it normalizes the real-value features to be symmetric to $0$ and reduces the quantization loss. \noindent \textbf{Enhance Codes with Self-Distillation Learning.} As we discussed in the introduction section, the coarse ranking must be accurate enough to minimise missing true-match candidates in fine-grained ranking. Inspired by \cite{hinton2015distilling,tung2019similarity}, we introduce self-distillation learning to enhance the multiple codes in a single framework without importing extra teacher network. Different from conventional distillation models, which imports an extra large teacher network to supervise a small student network, we perform distillation learning in a single network and achieve better performance, which is important for fast ReID. Specifically, our self-distillation learning is composed of a probability- and a similarity- distillation. The probability-distillation transfers the instance-level knowledge in a from of softened class scores. Its formulation is given by \begin{equation} \mathcal{L}_{pro} = \frac{1}{N-1} \sum_{k=1} ^{N-1} \mathcal{L}_{ce}(\sigma(\frac{z_{k+1}}{T}), \sigma(\frac{\hat{z}_{k}}{T})), \label{eq:prob-loss} \end{equation} where $\mathcal{L}_{ce}(\cdot, \cdot)$ denotes the cross-entropy loss, $\sigma$ is the softmax function, $\hat{z}_{k}/z_{k+1}$ means the output logits of the binary code $b_{k}/b_{k+1}$, $\hat{z}_{k}$ means it act as a teacher and fixed during training, $T$ is a temperature hyperparameter, which is set $1.0$ empirically. The similarity-distillation transfers the knowledge of relationship from longer codes to shorter one, whose formulation is in Eq.(\ref{eq:sim-loss}). This is motivated by that as an image search task, ReID features should also focus on the relationship among samples, \textit{i.e.} to what extent the sample A is similar/dissimilar to sample B. \begin{equation} \mathcal{L}_{sim} = \frac{1}{N-1} \sum_{k=1}^{N-1} \sum _{i,j} ||\frac{1}{l_{k+1}}{G}^{i,j}_{k+1} - \frac{1}{l_{k}} \hat{G}^{i,j}_{k}||^2, \label{eq:sim-loss} \end{equation} where $G^{i,j}_{k}/G^{i,j}_{k+1}$ is the Hamming distance between $b^{i}_{k}/b^{i}_{k+1}$ and $b^j_{k}/b^j_{k+1}$, $b^{i/j}_{k/k+1}$ is the binary code of image $x_i/x_j$ with length $l_{k}/l_{k+1}$, the $\hat{G}$ means that $G$ acts as a label and is fixed during the optimization process, thus contributes nothing to the gradients. \noindent\textbf{Overall Objective Function and Training.} Recent progresses on ReID have shown the effectiveness of the classification \cite{zheng2016person} and triplet \cite{hermans2017defense} losses. Thus, our final objective function includes our proposed probability- and similarity- distillation losses together with the classification and triplet losses as the final objective function. The formulation can be found in Eq.(\ref{eq:over-all-loss}), \begin{equation} \mathcal{L} = \mathcal{L}_{ce} + \mathcal{L}_{tri} + \lambda_1 \mathcal{L}_{prob} + \lambda_2 \mathcal{L}_{sim} \label{eq:over-all-loss} \end{equation} Considering that the mapping function $sgn$ in Eq.(\ref{eq:quantization-func}) is discrete and Hamming distance in Eq.(\ref{eq:quantization-func}) is not differentiable, a natural relaxation \cite{Li2016Feature} is utilised in Eq.(\ref{eq:over-all-loss}) by replacing $sgn$ with $tanh$ and changing the Hamming distance to the inner-product distance. Finally, our All-in-One framework can be optimized in an end-to-end way by minimizing the loss in Eq.(\ref{eq:over-all-loss}). \subsection{Distance Threshold Optimization} \begin{algorithm}[t] \caption{Distance Threshold Optimization} \hspace*{0.02in} {\bf Input:} Trained Model in Eq.(\ref{eq:quantization-func}), Validation Data $(X_v, Y_v)$ \\ \hspace*{0.02in} {\bf Output:} Thresholds $\{T_{i}\}_{i=2}^{N}$ \begin{algorithmic}[1] \For{$k = \{1, 2, ..., n-1\}$} \State $B_{k}$: Extract binary codes of validation set with length $l_k$ via Eq.(\ref{eq:quantization-func}) \State $D^{r}$: Hamming distances of relevant pairs $(b^i_{k}, b^j_{k})$, where $y^i=y^j$ \State $D^{n}$: Hamming distances of non-relevant pairs $(b^i_{k-1}, b^j_{k-1})$, where $y^i \not= y^j$ \State $PDF^r, PDF^n$: Probability distribution function of $D^{r}$ and $D^{n}$ of in Eq.(\ref{eq:gaussian}) \State $CDF^r, CDF^n$: Cumulative Distribution Function of $D^{r}$ and $D^{n}$ in Eq.(\ref{eq:gaussian}) \State $t_{n+1}$: Maximize $F_\beta$ score in Eq.(\ref{eq:f-beta}) and return $t_{n+1}$ \EndFor \State return $T=\{t_i\}_{i=2}^N$ \end{algorithmic} \end{algorithm} After getting the multiple codes of different lengths $B=\{b_i\}_{i=1}^{N}$, we can perform the Coarse-to-Fine (CtF) search. There are two tips in CtF search, \textit{i.e.} high accuracy and fast speed. For fast speed, the candidate number returned by coarse search should be small. For high accuracy, the candidates returned by coarse search should include relevant images as more as possible. But the two requirements are naturally conflicting. Thus, it is important to find the proper thresholds to optimally balance the two targets, \textit{i.e.} both high accuracy and fast speed. One simple solution is brute search via cross-validation. However, the search space is too large. For example, if we have multiple binary codes of lengths $L = \{32, 128, 512, 2048\}$, the complexity of the brute search will be $\prod_{L} > 4 \times 10^{9}$ times. In this part, we propose a novel Distance Threshold Optimization (DTO) algorithm which solves the time-consuming brute parameter search task with a simple optimization process. Specifically, inspired by \cite{goutte2005probabilistic}, we first explicitly formulate the two sub-targets as two scores in Eq.(\ref{eq:p-r-f}), \textit{i.e.} precision ($P$) and recall ($R$) scores. Then we balance the two sub-targets by mixing the two scores with a single parameter $\beta$ and get $F_{\beta}$ score in Eq.(\ref{eq:p-r-f}). \begin{equation} \begin{split} P = \frac{TP}{TP+FP}, \ \ R = \frac{TP}{TP+FN} , \ \ F_{\beta} = (\beta^2+1)\frac{PR}{\beta^2P+R} \end{split} \label{eq:p-r-f} \end{equation} Here, $TP$ is the number of relevant images in the candidates, $FP$ is the number of non-relevant images in the candidates and $FN$ is not retrieved relevant samples. As we can see, the precision score $P$ means the rate of relevant images in the candidates. Usually a high $P$ means a small candidate number, which is good for fast speed. The recall score $R$ represents the rate of returned relevant samples in the total relevant samples. A high $R$ score means more returned relevant samples, which is important for high accuracy. The $F_{\beta}$ mixed the precision and recall scores with a parameter $\beta$, which considers both speed and accuracy. \begin{equation} \begin{split} PDF(t) = \frac{1}{\sigma\sqrt{2\pi}} exp({-\frac{(t-u)^2}{\sigma\sqrt{2}}}), \ \ CDF(t) = \frac{1}{2}(1 + erf\frac{t-u}{\sigma\sqrt{2}}) \end{split} \label{eq:gaussian} \end{equation} \begin{equation} F_{\beta} = \frac{CDF^{r}(\beta^2 + 1)}{CDF^{n} + CDF^{r} + \beta^2(1-CDF^{n} + CDF^{r})} \label{eq:f-beta} \end{equation} Considering that TP/FP/FN are statistics which cannot be optimized, we replace them with two Gaussian cumulative distribution functions in form of Eq.(\ref{eq:gaussian}) (right), whose parameters $u$ and $\sigma$ are estimated by fitting a validation set using the Gaussian probability distribution function in Eq.(\ref{eq:gaussian}) (left). Finally, by maximizing the $F_{\beta}$ in Eq.(\ref{eq:f-beta}), we can get the optimal distance thresholds $T=\{t_k\}_{k=2}^{N}$ balanced by $\beta$. \iffalse \subsection{Discussion} \noindent\textbf{Different with Distillation Model.} Model distillation \cite{hinton2015distilling} requires an extra large teacher network to guide a small student one. Different from it, our self-distillation encourages shorter codes to mimic longer codes in a single network, which is more efficient. \noindent\textbf{Different with $F_{\beta}$ score.} Precision, recall and F scores are evaluation protocols, which need to \fi \section{Experiments} \subsection{Dataset and Evaluation Protocols} \noindent\textbf{Datasets.} We extensively evaluate our proposed method on two common datasets (Market-1501 \cite{zheng2015scalable} and DukeMTMC-reID \cite{zheng2017unlabeled}) and one large-scale dataset (Market-1501+500k\cite{zheng2015scalable}). The Market-1501 dataset contains 1,501 identities observed under 6 cameras, which are splited into 12,936 training, 3,368 query and 15,913 gallery images. The Market-1501+500k enlarges the gallery of Market-1501 with extra 500,000 distractors, making it more challenging for both accuracy and speed. DukeMTMC-reID contains 1,404 identities with 16,5522 training, 2,228 query and 17,661 gallery images. \noindent\textbf{Evaluation Protocols.} For accuracy, we use standard metrics including Cumulative Matching Characteristic (CMC) curves and mean average precision (mAP). All the results are from a single query setting. To evaluate speed, we use average query time per image, including distance computation and sorting time. For fair evaluation, we do not use any parallel algorithm for distance computation and sorting. \subsection{Implementation Details} We implemented our method with Pytorch on a PC with 2.6Ghz Intel Core i5 CPUs, 10GB memory, and a NVIDIA RTX 2080Ti GPU. For a fair comparison and following \cite{luo2019bag,liu2019adversarial}, we use ResNet50 \cite{he2016deep} as the CNN backbone. In training stage, each image is resized to $256\times128$ and augmented by horizontal flip and random erasing \cite{zhong2017random}. A batch data includes 64 images from 16 different persons, where every person includes 4 images. The lengths $L=\{l_k\}_{k=1}^{N}$ of multiple codes are empirically set $\{32, 128, 512, 2048\}$. The margin in the triplet loss in Eq.(\ref{eq:over-all-loss}) is 0.3. The framework is optimized by Adam \cite{kingma2014adam} with total epochs 120. Its initial learning rate is 0.00035, which is warmed up for 10 epochs and decayed to its $0.1\times$ and $0.01\times$ at 40 and 70 epochs. We randomly split the training data into a training and a validation set according to $6:4$, then decide the parameters via cross-validation, After that, we train our method with all training data. $\lambda_1$ and $\lambda_2$ in Eq.(\ref{eq:over-all-loss}) are set as 1.0 and 1,000, and $\beta$ in Eq.(\ref{eq:f-beta}) is set 2.0. The three paramters are decided via cross validation. Code is available at github\footnote{\url{https://github.com/wangguanan/light-reid}}. \subsection{Comparisons with Non-Hashing ReID Methods} \begin{table}[t] \begin{center} \small \begin{tabular}{l|cc|ccc|ccc} \hline \hline \multicolumn{1}{l|}{\multirow{2}{*}{Methods}} & \multicolumn{2}{c|}{Code} & \multicolumn{3}{c|}{Market-1501} & \multicolumn{3}{c}{DukeMTMC-reID} \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c}{Type} & \multicolumn{1}{c|}{Length} & \multicolumn{1}{c}{R1(\%)} & \multicolumn{1}{c}{mAP(\%)} & \multicolumn{1}{c|}{\textbf{\textit{Q.Time}}(s)} & \multicolumn{1}{c}{R1(\%)} & \multicolumn{1}{c}{mAP(\%)} & \multicolumn{1}{c}{\textbf{\textit{Q.Time}}(s)} \\ \hline PSE \cite{sarfraz2018a} & $\mathbf{R}$ & 1,536 & 78.7 & 56.0 & - & - & - & - \\ PN-GAN \cite{qian2018pose} & $\mathbf{R}$ & 1,024 & 89.4 & 72.6 & - & 73.6 & 53.2 & - \\ IDE \cite{zheng2016person} & $\mathbf{R}$ & 2,048 & 88.1 & 72.8 & - & 69.4 & 55.4 & - \\ Camstyle \cite{zhong2018camera} & $\mathbf{R}$ & 2,048 & 88.1 & 68.7 & - & 75.3 & 53.5 & - \\ PIE \cite{zheng2019pose} & $\mathbf{R}$ & 2,062 & 87.7 & 69.0 & - & 79.8 & 62.0 & - \\ BoT~\cite{luo2019bag} & $\mathbf{R}$ & 2,048 & \underline{94.1} & \underline{85.7} & \underline{$2.2\times10^0$} & \underline{86.4} & \underline{76.4} & \underline{$2.0\times10^{0}$} \\ \hline SPReID \cite{kalayeh2018human} & $\mathbf{R}$ & 10,240 & 92.5 & 81.3 & - & 84.4 & 71.0 & - \\ PCB \cite{sun2018beyond} & $\mathbf{R}$ & 12,288 & 93.8 & 81.6 & $6.9\times10^0$ & 83.3 & 69.2 & $6.3\times10^{0}$ \\ VPM \cite{sun2019perceive} & $\mathbf{R}$ & 14,336 & 93.0 & 80.8 & - & 83.6 & 72.6 & - \\ \hline \textbf{CtF (ours)} & $\mathbf{B}$ & 2,048 & \textbf{93.7} & \textbf{84.9} & $\mathbf{4.6\times10^{-2}}$ & \textbf{87.6} & \textbf{74.8} & \textbf{$\mathbf{3.7\times10^{-2}}$} \\ \hline \hline \end{tabular} \end{center} \caption{Comparisons with non-hashing ReID methods using real-value features of different lengths on Market-1501 and DukeTMTC-reID. $\mathbf{B}$: binary code, $\mathbf{R}$: real-value feature. Longer real-value features have higher accuracy but slower query speed. Our model CtF (including AiO) has very fast query speed (two orders of magnitude faster) and comparable accuracy with non-hashing ReID methods. } \label{tab:sota-non-hashing} \end{table} Non-hashing ReID use longer real-value features, such as 2048-dimensional $float64$ features, for a better accuracy. This significantly affects their speed, \textit{i.e.} query time. Table~\ref{tab:sota-non-hashing} shows that our proposed CtF (including AiO) method is significantly faster than non-hashing ReID methods (two orders of magnitude). CtF also achieves very competitive accuracy with close Rank-1 (93.7\% vs. 94.1\%) and mAP (87.6\% vs. 86.4\%) scores of the best non-hashing ReID mehtod BoT \cite{luo2019bag} on Market-1501 and DukeMTMC-reID, and better than all the other non-hashing methods using different feature length, of which 5 methods have features shorter than 2,062 (PSE \cite{sarfraz2018a}, IDE \cite{zheng2016person}, PN-GAN \cite{qian2018pose}, CamStyle \cite{zhong2018camera}, PIE \cite{zheng2019pose}) and 3 methods have features longer than 10,240 (SPReID \cite{kalayeh2018human}, PCB \cite{sun2018beyond}, VPM \cite{sun2019perceive}). Overall, longer feature usually contributes to higher accuracy but with slower speed. For example, SPReID, PCB and VPM take features longer than 10,240 and achieves $92\%$-$93\%$ and $83\%$-$84\%$ Rank-1 scores on Market-1501 and DukeMTMC-reID datasets, respectively. The others utilize features no longer than 2,048 achieving Rank-1 score less than $92\%$ and $80\%$. On the other hand, the query speed of those methods with long features is much slower. For example, PCB takes $6.9s$ and $6.3s$ for query each image on the two datasets respectively. This is $3$-$4\times$ slower than IDE with $2s$ on either dataset. Specifically, CtF performs much faster than non-hashing methods and significantly, it achieves much better accuracy than comparable length real-value feature model. For example, CtF achieves $93.7\%/87.6\%$ Rank-1 scores on Market-1501/DukeMTMC-reID, as compared to BoT having $94.1\%/86.4\%$ respectively. This is because CtF (including AiO) utilizes all-in-one framework together with coarse-to-fine search strategy, which not only learns powerful binary code, but also complementarily uses short and long codes for both high accuracy and fast speed. \subsection{Comparisons with Hashing ReID Methods} \begin{table}[t] \begin{center} \begin{tabular}{c|c|ccc|ccc} \hline \hline \multicolumn{1}{c|}{\multirow{2}{*}{Methods}} & \multicolumn{1}{c|}{Code} & \multicolumn{3}{c|}{Market-1501} & \multicolumn{3}{c}{DukeMTMC-reID} \\ \multicolumn{1}{c|}{} & \multicolumn{1}{c|}{Length} & \multicolumn{1}{c}{R1(\%)} & \multicolumn{1}{c}{mAP(\%)} & \multicolumn{1}{c|}{\textbf{Q.Time}(s)} & \multicolumn{1}{c}{R1(\%)} & \multicolumn{1}{c}{mAP(\%)} & \multicolumn{1}{c}{\textbf{Q.Time}(s)} \\ \hline DRSCH \cite{Zhang2015Bit} & 512 & 17.1 & 11.5 & - & 19.3 & 13.6 & - \\ DSRH \cite{zhao2015deep} & 512 & 27.1 & 17.7 & - & 25.6 & 18.6 & - \\ HashNet \cite{cao2017hashnet} & 512 & 29.2 & 19.1 & - & 40.8 & 28.6 & - \\ DCH \cite{cao2018deep} & 512 & 40.7 & 20.2 & - & 57.4 & 37.3 & - \\ CSBT \cite{chen2017fast} & 512 & 42.9 & 20.3 & - & 47.2 & 33.1 & - \\ PDH \cite{zhu2017part} & 512 & 44.6 & 24.3 & - & - & - & - \\ DeepSSH \cite{zhao2018deepssh} & 512 & 46.5 & 24.1 & - & - & - & - \\ ABC \cite{liu2019adversarial} & 512 & 69.4 & 48.5 & $9.8\times10^{-2}$ & 69.9 & 52.6 & $7.5\times10^{-2}$ \\ ABC \cite{liu2019adversarial} & 2,048 & 81.4 & 64.7 & $2.8\times10^{-1}$ & 82.5 & 61.2 & $2.0\times10^{-1}$ \\ \hline \multirow{5}{*}{\textbf{CtF (ours)}} & AiO+32 & 60.0 & 37.7 & \underline{$3.4\times10^{-2}$} & 49.5 & 28.7 & \underline{$2.3\times10^{-2}$} \\ & AiO+128 & 88.9 & 71.0 & $4.2\times10^{-2}$ & 78.6 & 59.4 & $3.2\times10^{-2}$\\ & AiO+512 & 92.8 & 82.2 & $9.8\times10^{-2}$ & 85.4 & 71.6 & $7.5\times10^{-2}$\\ & AiO+2,048 & \underline{93.7} & \underline{85.4} & $2.8\times10^{-1}$ & \underline{87.7} & \underline{75.7} & $2.0\times10^{-1}$ \\ & AiO+CtF & \textbf{93.7} & \textbf{84.0} & $\mathbf{4.6\times10^{-2}}$ & \textbf{87.6} & \textbf{74.8} & $\mathbf{3.7\times10^{-2}}$ \\ \hline \hline \end{tabular} \end{center} \caption{Comparisons with state-of-the-art hashing ReID methods on Market-1501 and DukeTMTC-reID. AiO+$k$ means learning multiple codes with all-in-one framework, but querying with only the code of length $l_{k}$. Aio+CtF not only learns multiple codes with all-in-one framework, but also query with coarse-to-fine search strategy. Our AiO+CtF achieve a good balance between accuracy and speed.} \label{tab:sota-hashing} \end{table} Hashing ReID methods learn binary codes using a hashing algorithm. Binary codes are good for speed but sacrifice model accuracy. To mitigate this problem, the state-of-the-art hashing ReID methods usually employ long codes such as $2048$. In binary coding, $2048$ is relatively very long as compared to the more commonly used $512$ length, unlike in real-value feature length compared above. Table \ref{tab:sota-hashing} shows that CtF (with AiO) not only achieves the best accuracy (even compared to much shorter code length used by other hashing methods), but also is significantly faster than existing hashing ReID methods (even compared to the same code length used by other hashing methods). Overall, hashing ReID methods usually perform much worse than non-hashing methods. For example, best non-hashing ReID methods achieves $94.1\%$ and $86.4\%$ Rank-1 scores on Market-1501 and DukeMTMC-reID respectively. But the best hashing ReID method only obtains $81.4\%$ and $82.5\%$ Rank-1 scores. Moreover, existing hashing ReID models can increase accuracy by using longer code length and compromising speed. For example, ABC with 512-dimensional binary codes achieves $69.4\%/69.9\%$ Rank-1 scores and $9.8/7.5\times10^{-2}s$ query time per probe image. When using 2048 binary codes, its Rank-1 scores increase to $81.4\%/82.5\%$ with query time slow down to $2.8/2.0\times10^{-1}s$. This observation is also verified with our method CtF (with AiO) using different code lengths. Importantly, our method CtF (with AiO) significantly outperforms all existing hashing ReID methods in terms of both accuracy (R1 12.3\% or 5.1\% better) and speed ($5\times$ faster). Specifically, CtF with AiO achieves high accuracy very close to AiO without CtF using 2048 code length, but yields significant speed advantage that is comparable to much shorter 128 binary code length. CtF obtains $93.7\%$ and $87.6\%$ Rank-1 scores, similar to AiO without CtF of a fixed 2048 length at $93.7\%$ and $87.7\%$. \subsection{Evaluation on Large-Scale ReID} \begin{figure}[t!] \center \includegraphics[width=\linewidth]{materials/large-scale.png} \caption{Experimental results on large-scale ReID dataset Market-1501+500k. Our Coarse-to-Fine (CtF) get a high accuracy comparable with non-hashing ReID method of long code and fast speed comparable with hashing ReID method of short code.} \label{fig:large-scale} \end{figure} Gallery size affects significantly ReID search accuracy and speed. To show the effectiveness of our proposed Coarse-to-Fine (CtF) search strategy, we evaluated it on a large-scale ReID dataset Market1501+500k. The dataset is based on the Market-1501 and enlarged with $500,000$ distractors. The experimental results are shown in Figure \ref{fig:large-scale}. We can observe the following phenomenons. Firstly, with the increase of gallery size, for all methods, the Rank-1 and mAP scores decrease, and the ReID speed per probe image slows down gradually. The reason is that more gallery images is more likely to contain more difficult samples. They make ReID search more challenging. Also, the extra gallery images significantly increase the time for computing all the distance comparisons and sorting required for ReID each probe image. Secondly, the non-hashing method with 2048-D real-value feature achieves the best accuracy but the worst time. This is because the real-value feature is more discriminative but slow to compute and sort. Thirdly, for hashing ReID methods, the 2048-D binary code obtains comparable ReID accuracy to that of the non-hashing model, but $10\times$ faster. This is because Hamming distances and counting sort are faster to compute. ReID speed of 32-D binary code is $5\times$ faster than that of 2048-D binary codes, but its accuracy drops dramatically. Finally, the proposed CtF model achieves a comparable accuracy to that of the non-hashing method but the advantage of similar speed to that of a hashing ReID method of 32-D binary code. Critically, the advantage is independent of the gallery size. Overall, these experiments demonstrate the effectiveness of CtF for a large-scale ReID task. \subsection{Model Analysis} \iffalse \begin{table}[t] \begin{center} \scalebox{1}{ \begin{tabular}{ccc|c|ccccc|ccccc} \hline \hline \multirow{2}{*}{CP} & \multirow{2}{*}{PD} & \multirow{2}{*}{SD} & \multirow{1}{*}{Code} & \multicolumn{4}{c|}{Rank-1(\%)} & \multicolumn{4}{c}{mAP(\%)} \\ & & & Type & \multicolumn{1}{c}{32} & \multicolumn{1}{c}{128} & \multicolumn{1}{c}{512} & \multicolumn{1}{c}{2048} & \multicolumn{1}{c}{32} & \multicolumn{1}{c}{128} & \multicolumn{1}{c}{512} & \multicolumn{1}{c}{2048} &\\ \hline \times & \times & \times & $\mathbf{B}$ & 25.5 & 84.8 & 92.3 & 93.8 & 33.9 & 67.5 & 81.4 & 84.0\\ \Checkmark & \times & \times & $\mathbf{B}$ & 54.4 & 87.8 & 92.7 & 93.8 & 35.0 & 72.2 & 81.7 & 84.8\\ \Checkmark & \Checkmark & \times & $\mathbf{B}$ & 54.4 & 88.4 & 92.4 & 94.0 & 34.3 & 71.1 & 81.4 & 85.1\\ \Checkmark & \times & \Checkmark & $\mathbf{B}$ & 60.5 & 88.4 & 92.9 & 94.0 & 37.0 & 71.6 & 82.3 & 85.4\\ \Checkmark & \Checkmark & \Checkmark & $\mathbf{B}$ & 60.0 & 88.9 & 92.9 & 93.8 & 37.7 & 71.0 & 82.0 & 85.3 \\ \hline \multicolumn{3}{c|}{upper bound} & $\mathbf{R}$ & 82.7 & 90.9 & 93.4 & 94.2 & 66.7 & 78.9 & 84.3 & 85.4\\ \hline \hline \end{tabular} } \end{center} \caption{Analysis of All-in-One (AiO) framework. $\mathbf{B}$ and $\mathbf{R}$ mean binary codes and real-valure features, respectively.} \label{tab:ablation-study} \end{table} \fi \begin{table}[t] \begin{center} \begin{tabular}{ccc|c|ccccc|ccccc} \hline \hline \multirow{2}{*}{\textbf{AiO}} & \multirow{2}{*}{\textbf{CP}} & \multirow{2}{*}{\textbf{SD}} & \multirow{1}{*}{Feature} & \multicolumn{5}{c|}{Rank-1(\%)} & \multicolumn{5}{c}{mAP(\%)} \\ & & & Type & \multicolumn{1}{c}{\ 32 \ } & \multicolumn{1}{c}{\ 128 \ } & \multicolumn{1}{c}{\ 512 \ } & \multicolumn{1}{c}{2048} & \multicolumn{1}{c|}{\ CtF \ } & \multicolumn{1}{c}{\ 32 \ } & \multicolumn{1}{c}{\ 128 \ } & \multicolumn{1}{c}{\ 512 \ } & \multicolumn{1}{c}{2048} & \multicolumn{1}{c}{\ CtF \ } \\ \hline $\times$ & $\times$ & $\times$ & $\mathbf{B}$ & - & - & - & - & - & - & - & - & - & \\ \Checkmark & $\times$ & $\times$ & $\mathbf{B}$ & 25.5 & 84.8 & 92.3 & 93.8 & 92.5 & 33.9 & 67.5 & 81.4 & 85.3 & 75.1 \\ \Checkmark & \Checkmark & $\times$ & $\mathbf{B}$ & 54.4 & 87.8 & 92.7 & 93.8 & 93.0 & 35.0 & 72.2 & 81.7 & 85.3 & 80.2 \\ \Checkmark & \Checkmark & \Checkmark & $\mathbf{B}$ & 60.0 & 88.9 & 92.9 & 93.8 & 93.7 & 37.7 & 71.0 & 82.0 & 85.3 & 84.0 \\ \hline \multicolumn{3}{c|}{upper bound} & $\mathbf{R}$ & 82.7 & 90.9 & 93.4 & 94.2 & - & 66.7 & 78.9 & 84.3 & 85.4& - \\ \hline \hline \end{tabular} \end{center} \caption{Analysis of the All-in-One (AiO) framework. \textbf{CP}: learn multiple codes in a pyramid structure, otherwise separate models. \textbf{SD}: enhance binary codes via self-distillation. $\mathbf{B}$ and $\mathbf{R}$ mean binary codes and real-value features, respectively.} \label{tab:analysis-aio} \end{table} \noindent \textbf{Analysis of AiO.} The All-in-One (AiO) framework aims to learn and enhance multiple codes of different lengths in a single model. It uses code pyramid (CP) structure and self-distillation (SD) learning. Results are in Table \ref{tab:analysis-aio}. Firstly, longer codes contribute to better accuracy. This can be seen in all settings no matter whether CP or SD is used and what code type is. Secondly, when using short codes, real-value features is much better than binary ones. But for long codes, they obtain similar accuracy. For example, the 32-dimensional real-value feature obtains $82.7\%$ Rank-1 score, outperforming the 32-dimensional binary code by $60\%$, where the latter achieved only $25.5\%$. But when using 2048 code length, binary codes and real-valure features both achieve approx. Rank-1 $94\%$ and mAP $84\%$. This suggests that the quantization loss of short codes is significantly worse than that of longer codes. Thirdly, learning with code pyramid (CP) structure or self-distillation (SD) improves short codes significantly. For example, CP+SD boosts the 32-dimensional binary codes from $25.5\%$ to $60.0\%$ in Rank-1 score, upto $35\%$ gain. It is evident that both code pyramid (CP) structure and self-distillation (SD) learning contribute to the effectiveness of the coarse-to-fine (CtF) search strategy, and significantly improve model performance. \begin{figure}[t] \center \includegraphics[scale=0.40]{materials/beta.png} \caption{Accuracy and Speed controlled by $\beta$. With the increase of $\beta$, the accuracy increases and speed becomes slow gradually.} \label{fig:beta} \end{figure} \noindent\textbf{Analysis of DTO.} We further analyzed parameter $\beta$ of the Distance Threshold Optimization (DTO) algorithm, which controls the balance between ReID accuracy and speed. Figure \ref{fig:beta} show the model accuracy and speed using different $\beta$ value on Market-1501 and DukeMTMC-reID. Firstly, it is evident that the value of $\beta$ has a good control of accuracy and speed, increasing $\beta$ slows down the speed but improves accuracy. For example, when $\beta=10^{-2}$, ReID is fastest at approx. 0.03 and 0.02 seconds to ReID each probe image on Market-1501 and DukeMTMC-reID, but with mAP scores only at $40\%$ and $30\%$. In contrast, $\beta=10^{1}$ gives high mAP $85\%$ and $75\%$, but the query speed is $5\times$ slower at approx. $0.1$ and $0.2$ seconds. Secondly, when $\beta$ is close to $10^{0}$, Rank-1 and mAP are almost peaked with a good balance on speed. \section{Conclusion} In this work, we proposed a novel Coarse-to-Fine (CtF) search strategy for faster person re-identification whilst also improve accuracy on conventional hashing ReID. Extensive experiments show that our method is $5\times$ faster than existing hashing ReID methods but achieves comparable accuracy with non-hashing ReID models that are 50$\times$ slower. \section*{Acknowledgement} This work was supported in part by the National Key R\&D Program of China (Grant 2018YFC2001700), by the National Natural Science Foundation of China (Grants 61720106012, and U1913601), by the Beijing Natural Science Foundation (Grants L172050), by the Strategic Priority Research Program of Chinese Academy of Sciences (Grant XDB32040000), by the Youth Innovation Promotion Association of CAS (2020140), the Alan Turing Institute Turing Fellowship, and Vision Semantics Ltd. \bibliographystyle{splncs04} \subsection{To Reviewer \#1} \end{document}
{'timestamp': '2020-08-18T02:14:07', 'yymm': '2008', 'arxiv_id': '2008.06826', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06826'}
arxiv
\section{Introduction}\label{intro} Semantic segmentation, aiming at classifying each pixel in one image, heavily relies on the dense pixel-wise annotations~\cite{long2015fully,zhao2017pyramid,chen2018deeplab,ronneberger2015u,Lin2016RefineNet,GaoLearning}. To reduce the annotation pressure, leveraging weak annotations like image-level~\cite{oh2017exploiting,papandreou2015weakly,Yao2015Semantic}, box-level~\cite{khoreva2017simple,GraphNet}, or scribble-level~\cite{lin2016scribblesup} annotations for semantic segmentation recently gained the interest of researchers. In this work, we focus on a more challenging task named zero-shot semantic segmentation~\cite{bucher2019zero}, which further relieves the burden of human annotation. Similar to zero-shot learning~\cite{lampert2013attribute}, we divide all categories into seen and unseen categories. The training images only have pixel-wise annotation for seen categories, while both seen and unseen objects may appear in test images. Thus, we need to bridge the gap between seen and unseen categories via category-level semantic information, enabling the model to segment unseen objects in the testing stage. Transferring knowledge from seen categories to unseen categories is not a new idea and has been actively studied by zero-shot learning (ZSL)~\cite{lampert2013attribute,akata2015evaluation,xian2019f,DBLP:conf/ijcai/GuoDHSLD19}. Most ZSL methods tend to learn the mapping between visual features and semantic word embeddings or synthesize visual features for unseen categories. To the best of our knowledge, there are quite few works on zero-shot semantic segmentation~\cite{zhao2017open,kato2019zero,xian2019semantic,bucher2019zero}, in which only SPNet~\cite{xian2019semantic} and ZS3Net~\cite{bucher2019zero} can segment an image with multiple categories. SPNet extends a segmentation network by projecting visual features to semantic word embeddings. Since the training images only contain labeled pixels of seen categories, the prediction will be biased towards seen categories in the testing stage. Hence, they deduct the prediction scores of seen categories by a calibration factor during testing. However, the bias issue is still severe after using calibration. Inspired by feature generation methods for zero-shot classification~\cite{xian2018feature,FelixMulti}, ZS3Net learns to generate pixel-wise features from semantic word embeddings. The generator is trained with seen categories and able to produce features for unseen categories, which are then used to finetune the last $1\times 1$ convolutional (conv) layer in the segmentation network. Moreover, they extend ZS3Net to ZS3Net (GC) by using Graph Convolutional Network (GCN)~\cite{kipf2016semi-supervised} to capture spatial relationships among different objects. However, it still has two drawbacks: 1) ZS3Net simply appends a random noise to one semantic word embedding to generate diverse features. However, the generator often ignores the random noise and can only produce limited diversity for each category-level semantic word embedding, known as mode collapse problem~\cite{xian2018texturegan,zhu2017unpaired}; 2) Although ZS3Net (GC) utilizes relational graphs to encode spatial object arrangement, the contextual cues it considers are object-level and only limited to spatial object arrangement. Moreover, the relational graphs containing unseen categories are usually inaccessible when generating unseen features. \begin{figure}[tbp] \centering \includegraphics[width=0.9\linewidth]{example.png} \caption{The pixel-wise visual features of category ``cat" are grouped into $K$ clusters with each color representing one cluster in Pascal-Context. The left (\emph{resp.}, right) subfigure shows the visualization results when $K=2$ (\emph{resp.}, $K=5$).} \label{example} \end{figure} In this paper, we follow the research line of feature generation for zero-shot segmentation and propose a \emph{\textbf{C}}ontextual-\emph{\textbf{a}}ware feature \emph{\textbf{G}}eneration model, CaGNet, by considering pixel-wise contextual information when generating features. The contextual information of a pixel means the information inferred from its surrounding pixels (\emph{e.g.}, its location in the object, the posture of the object it belongs to, background objects), which is not limited to spatial object arrangement considered in \cite{bucher2019zero}. Intuitively, the pixel-wise feature vectors in deep layers highly depend on their contextual information. To corroborate this point, we obtain the output features of the ASPP module in Deeplabv2~\cite{chen2018deeplab} for category ``cat" on Pascal-Context~\cite{mottaghi2014role}, and group those pixel-wise features into $K$ clusters by K-means. Based on Figure~\ref{example}, we observe that pixel-wise features are affected by their contextual information in an interlaced and complicated way. When $K=2$, the features from the interior (\emph{resp.}, exterior) of the cat are grouped together. When $K=5$, we provide examples in which pixel-wise features are affected by adjacent or distant background objects. For example, the red (\emph{resp.}, blue) cluster is likely to be influenced by the cushion (\emph{resp.}, green plant) as shown in the top (\emph{resp.}, bottom) row. These observations motivate us to generate context-aware features with the guidance of pixel-wise contextual information. Unlike the feature generator in ZS3Net, which takes semantic word embedding and random noise as input to generate pixel-wise fake feature, we feed semantic word embedding and pixel-wise contextual latent code into our generator. The contextual latent code is obtained from our proposed Contextual Module ($CM$). Our $ CM $ takes the output of the segmentation backbone as input and outputs pixel-wise real feature and corresponding pixel-wise contextual latent code for all pixels. In our $CM$, we also design a context selector to adaptively weight different scales of contextual information for different pixels. Since adequate contextual information is passed to the generator to resolve the ambiguity of feature generation, we expect that the pixel-wise contextual latent code together with semantic word embedding is able to reconstruct the pixel-wise real feature. In other words, we build the one-to-one correspondence (bijection) between input pixel-wise contextual latent code and output pixel-wise feature. It has been proved in \cite{NeurIPS2017_6650} that the bijection between input latent code and output could mitigate the mode collapse problem, so our model can generate more diverse features from one semantic word embedding by varying the contextual latent code. We enforce the contextual latent code to follow unit Gaussian distribution to get various contextual latent codes via randomly sampling. Therefore, the segmentation network and our feature generation network are linked by contextual module and classifier. In summary, compared with ZS3Net, CaGNet can produce more diverse and context-aware features. Compared with its extension ZS3Net (GC), our method has two advantages: 1) we leverage more informative pixel-wise contextual information instead of object-level contextual information; 2) we encode contextual information into latent code, which supports stochastic sampling, so we do not require explicit contextual information of unseen categories (\emph{e.g.}, relational graph) when generating unseen features. Our main contributions are: \begin{itemize} \item We design a feature generator guided by pixel-wise contextual information, to obtain diverse and context-aware features for zero-shot semantic segmentation. \item Two minor contributions are: 1) unification of segmentation network and feature generation network; 2) contextual module with a novel context selector. \item Extensive experiments on Pascal-Context, COCO-stuff, and Pascal-VOC demonstrate the effectiveness of our method. \end{itemize} \begin{figure*}[htbp] \centering \includegraphics[width=0.9\linewidth]{ours2.pdf} \caption{\textbf{Overview of our CaGNet.} Our model contains segmentation backbone $E$, Contextual Module $CM$, feature generator $G$, discriminator $D$, and classifier $C$. $\textbf{W}$, $\textbf{Z}$, and $\textbf{X}$ represent semantic word embedding map, contextual latent code map, and feature map respectively (see Section~\ref{sec:CM} and \ref{sec:context_feature_generator} for detailed definition). Optimization steps are separated into training step and finetuning step indicated by two different colors (see Section~\ref{sec:optimization}).} \label{ours} \end{figure*} \section{Related Works} \noindent\textbf{Semantic Segmentation: }State-of-the-art semantic segmentation models~\cite{long2015fully,zhao2017pyramid,chen2018deeplab,ronneberger2015u,Lin2016RefineNet,GaoLearning} are typically extending Fully Convolutional Network (FCN) \cite{long2015fully} framework with larger receptive field and more efficient encoder-decoder structure. Based on the idea to expand receptive field, PSPNet\cite{zhao2017pyramid} and Deeplab\cite{chen2018deeplab} design specialized pooling layers for fusing the contextual information from feature maps of different scales. Other methods like U-Net~\cite{ronneberger2015u} and RefineNet~\cite{Lin2016RefineNet} focus on designing more efficient network architectures to better combine low-level and high-level features. One important characteristic of semantic segmentation is the usage of contextual information since the category predictions of target objects are often influenced by nearby objects or background scenes. Thus, many works~\cite{chen2018deeplab,Yu2015Multi} tend to explore contexts of different receptive fields with dilated convolutional layers, which also motivates us to incorporate contexts into feature generation. However, those models still require annotations of all categories during training, and thus cannot be applied to the zero-shot segmentation task. In contrast, we successfully combine segmentation network with feature generator for zero-shot semantic segmentation. \noindent\textbf{Zero-shot Learning: }Zero-shot learning (ZSL) was first introduced by~\cite{Lampert2009Learning}, in which training data are from seen categories, but test data may come from unseen categories. Knowledge is transferred from seen categories to unseen via category-level semantic embeddings. Many ZSL methods~\cite{akata2015label,frome2013devise,romera2015embarrassingly,fu2015transductive,10.1145/2964284.2964319,10.1145/2578726.2578746,10.1145/3240508.3240715,niu2018webly,niu2019zero-shot} attempted to learn a mapping between feature space and semantic embedding space. Recently, a popular approach of zero-shot classification is generating synthesized features for unseen categories. For example, the method in~\cite{xian2018feature} first generated features using word embeddings and random vectors, which was further improved by later works \cite{FelixMulti,xian2019f,Mert2019Gradient,Li2019Leveraging,Mandal2019Out}. These zero-shot classification methods generated image features without involving contextual information. In contrast, due to the uniqueness of semantic segmentation, we utilize pixel-wise contextual information to generate pixel-wise features. \noindent\textbf{Zero-shot Semantic Segmentation: }The term zero-shot semantic segmentation appeared in prior works~\cite{zhao2017open,kato2019zero,xian2019semantic,bucher2019zero}, in which only SPNet~\cite{xian2019semantic} and ZS3Net~\cite{bucher2019zero} focused on multi-category semantic segmentation. SPNet achieves knowledge transfer between seen and unseen categories via semantic projection layer and calibration method, while ZS3Net aims to generate pixel-wise features to finetune the classifier, which is biased to the seen categories. Our method is inspired by ZS3Net, but different from their method in mainly two ways: 1) we unify the segmentation network and feature generator; 2) we leverage pixel-wise contextual information to guide feature generation. \section{Methodology}\label{method} For ease of representation, we denote the set of seen (\emph{resp.}, unseen) categories as $\mathcal{C}^s$ (\emph{resp.}, $\mathcal{C}^u$) and $\mathcal{C}^s\cap \mathcal{C}^u=\emptyset$. In the zero-shot segmentation task, the training set only contains pixel-wise annotations of $\mathcal{C}^s$, while the trained model is supposed to segment objects of $\mathcal{C}^s\cup \mathcal{C}^u$ at test time. As mentioned in Section~\ref{intro}, the bridge between seen and unseen categories is the category-level semantic word embeddings $\{{\bar{\textbf{w}}}_c|c\in \mathcal{C}^s\cup \mathcal{C}^u\}$, in which ${\bar{\textbf{w}}}_c \in \mathcal{R}^{d}$ is the semantic word embedding of category $c$. \subsection{Overview} Our method, CaGNet, can be applied to an arbitrary segmentation network. We start from Deeplabv2~\cite{chen2018deeplab}, which has shown remarkable performance in semantic segmentation. Any segmentation network like Deeplabv2 can be separated into two parts: backbone $E$ and classifier $C$ (\emph{e.g.}, one or two $1\times1$ conv layers). Given an input image, the backbone outputs its real feature map, which is passed to the classifier to get the segmentation results. To enable the segmentation network to segment unseen objects, we aim to learn a generator $G$ to generate features for unseen categories. As shown in Figure~\ref{ours}, $G$ takes the semantic word embedding map and the latent code map as input to output fake features. Then, discriminator $ D $ and classifier $ C $, with a shared $1\times 1$ conv layer, take real/fake features to output discrimination and segmentation results respectively. Note that our classifier $C$ is shared by the feature generation network and the segmentation network. To help the generator $G$ produce more diverse and context-aware features, we insert a Contextual Module ($CM$) after the backbone $E$ of segmentation network to obtain contextual information, which is encoded into the latent code as the guidance of $G$. Therefore, we unify the segmentation network $\{E, CM, C\}$ and the feature generation network $\{CM, G, D, C\}$, which are linked by Contextual Module $CM$ and classifier $C$. Next, we will detail our $CM$ in Section~\ref{sec:CM} and feature generator in Section~\ref{sec:context_feature_generator}. For ease of description, we use capital letter in bold (\emph{e.g.}, $\textbf{X}$) to denote a map and small letter in bold (\emph{e.g.}, $\textbf{x}_i$) to denote its pixel-wise vector. We use upperscript $s$ (\emph{resp.}, $u$) to indicate seen (\emph{resp.}, unseen) categories. \subsection{Contextual Module}\label{sec:CM} \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{contextual.pdf} \caption{\textbf{Contextual Module.} We aggregate the contextual information of different scales using our context selector. Then, the aggregated contextual information produces latent distribution for sampling contextual latent code. } \label{contextual} \end{figure} \noindent\textbf{Multi-scale Context Maps:} We insert our Contextual Module ($CM$) after the backbone $E$ of Deeplabv2, as shown in Figure~\ref{ours}. For the $n$-th image, we use $\textbf{F}_n\in \mathcal{R}^{h\times w\times l}$ to denote the output feature map of the $E$ Our $CM$ aims to gather the pixel-wise contextual information for each pixel on $\textbf{F}_n$. Recall that the pixel-wise contextual information of a pixel means the aggregated information of its surrounding pixels. To achieve this goal, $CM$ takes $\textbf{F}_n$ as input to produce one or more context maps of the same size as $\textbf{F}_n$. Each pixel-wise vector on context maps contains the pixel-wise contextual information of its corresponding pixel on $\textbf{F}_n$. In terms of the detailed design of $CM$, we consider two principles: 1) multi-scale contexts should be preserved for better feature generation; 2) the one-to-one correspondence between contexts and pixels should be maintained as discussed in Section~\ref{intro}, which means that no pooling layers should be used. Based on these principles, we employ several dilated conv layers~\cite{Yu2015Multi} because they support the exponential expansion of receptive fields without loss of spatial resolution. As shown in Figure~\ref{contextual}, we use three serial dilated convs and refer to the output context maps of these layers as ${\hat{\textbf{F}}}^0_n,{\hat{\textbf{F}}}^1_n,{\hat{\textbf{F}}}^2_n\in \mathcal{R}^{h\times w\times l}$ respectively. Applying three successive context maps can capture contextual information of different scales because pixels on a deeper context map have larger receptive fields, which means information within larger neighborhoods can be collected for these pixels. \noindent\textbf{Context Selector:} Next, we attempt to aggregate three context maps. Intuitively, the features of different pixels may be dominated by the contextual information of small receptive field (\emph{e.g.}, the posture or inner parts of its belonging object) or large receptive field (\emph{e.g.}, distant background objects). To better select the contextual information of suitable scale for each pixel, we propose a light-weight context selector to adaptively learn different scale weights for different pixels. Specifically, we employ a $3\times 3$ conv layer to transform the concatenated $ [{\hat{\textbf{F}}}^0_n,{\hat{\textbf{F}}}^1_n,{\hat{\textbf{F}}}^2_n]$ to a $3$-channel scale weight map $\textbf{{A}}_n=[\textbf{A}_n^0,\textbf{A}_n^1,\textbf{A}_n^2]\in \mathcal{R}^{h\times w\times 3}$, in which the $k$-th channel $\textbf{A}_n^k$ contains the weights of all pixels for the $k$-th scale. Then, we duplicate each channel $\textbf{A}_n^k$ to $l$ channels to get ${\hat{\textbf{A}}}_n^k \in \mathcal{R}^{h\times w\times l}$ and obtain the weighted concatenation of three context maps $[{\hat{\textbf{F}}}^0_n\odot{\hat{\textbf{A}}}_n^0,{\hat{\textbf{F}}}^1_n\odot{\hat{\textbf{A}}}_n^1,{\hat{\textbf{F}}}^2_n\odot{\hat{\textbf{A}}}_n^2]\in \mathcal{R}^{h\times w\times 3l}$ with $\odot$ being Hadamard product. In this way, we select contexts of different scales pixel-wisely. Although our contextual module looks similar to channel attention ~\cite{SEnet,li2018harmonious} or full attention~\cite{wang2018mancs}, our motivation and technical details are intrinsically different from them. \noindent\textbf{Contextual Latent Code:} To obtain contextual latent code, we apply a $1\times 1$ conv layer to the weighted concatenation of context maps $[{\hat{\textbf{F}}}^0_n\odot{\hat{\textbf{A}}}_n^0,{\hat{\textbf{F}}}^1_n\odot{\hat{\textbf{A}}}_n^1,{\hat{\textbf{F}}}^2_n\odot{\hat{\textbf{A}}}_n^2]$ to output $\bm{\mu}_{\textbf{Z}_n}\in \mathcal{R}^{h\times w\times l}$ and $\bm{\sigma}_{\textbf{Z}_n}\in \mathcal{R}^{h\times w\times l}$, in which $\bm{\mu}_{\textbf{z}_{n,i}}$ and $\bm{\sigma}_{\textbf{z}_{n,i}}$ represent for each pixel-wise vector respectively. Then, the contextual latent code $\textbf{z}_{n,i}$ for the $i$-th pixel can be sampled from Gaussian distribution $\mathcal{N}(\bm{\mu}_{\textbf{z}_{n,i}},\bm{\sigma}_{\textbf{z}_{n,i}})$ by using $\textbf{z}_{n,i}=\bm{\mu}_{\textbf{z}_{n,i}}+\epsilon \bm{\sigma}_{\textbf{z}_{n,i}}$, with epsilon being a random scalar sampled from $\mathcal{N}(0,1)$. To enable stochastic sampling during inference, we employ a KL-divergence loss to enforce $\mathcal{N}(\bm{\mu}_{\textbf{z}_{n,i}},\bm{\sigma}_{\textbf{z}_{n,i}})$ to be close to unit Gaussian distribution $\mathcal{N}(\textbf{0,1})$: $$\mathcal{L}_{KL} = \mathcal{D}_{KL}[\mathcal{N}(\bm{\mu}_{\textbf{z}_{n,i}},\bm{\sigma}_{\textbf{z}_{n,i}})||\mathcal{N}(\textbf{0,1})].$$ We assume that the pixel-wise contextual latent code encodes the contextual information of this pixel. For instance, given a pixel in a cat near a tree, its contextual latent code may encode its near local region in the cat, its relative location in the cat, the posture of the cat, background objects like the tree, \emph{etc}. Furthermore, we aggregate all $\textbf{z}_{n,i}$ for the $n$-th image into latent code map $\textbf{Z}_n \in \mathcal{R}^{h\times w\times l}$. Inspired by~\cite{hu2018gather}, we element-multiply $\textbf{Z}_n$ to $\textbf{F}_n$ after applying sigmoid activation (denoted as $\phi$) as residual attention, that is, our $CM$ outputs the new feature map $\textbf{X}_n = \textbf{F}_n+\textbf{F}_n\odot \phi(\textbf{Z}_n) \in \mathcal{R}^{h\times w\times l}$ as both the target of feature generation and the input of classifier $C$. In this way, $CM$ can be jointly trained with segmentation network as a residual attention module. Note that $CM$ could slightly enhance the output feature map ($\textbf{X}_n$ \emph{v.s.} $\textbf{F}_n$ of segmentation network, see Section~\ref{sec:ablation}), but the main goal of $CM$ is to facilitate feature generation. \subsection{Context-aware Feature Generator}\label{sec:context_feature_generator} In this section, we first introduce the feature generation pipeline for seen categories, because training images only have pixel-wise annotations of seen objects. Given an input image $\textbf{I}_n$, the backbone $E$, together with the Contextual Module $CM$, delivers real visual feature map $\textbf{X}_n^s$ with pixel-wise feature $\textbf{x}_{n,i}^s$ and contextual latent code map $\textbf{Z}_n \in \mathcal{R}^{h\times w\times l}$ with pixel-wise latent code $\textbf{z}_{n,i}$ as mentioned in Section~\ref{sec:CM}. For the $i$-th pixel on $\textbf{X}_n^s$, , we have the category label $c_{n,i}^s$, which can also be represented by a one-hot vector $\textbf{y}_{n,i}^s$ from the segmentation label map $\textbf{Y}_n^s$. Note that $\textbf{Y}_n^s$ is a down-sampled label map with the same spatial resolution as $\textbf{X}_n^s$, \emph{i.e.}, $\textbf{Y}_n^s \in \mathcal{R}^{h\times w\times (|\mathcal{C}^s|+|\mathcal{C}^u|)}$. We can obtain the corresponding semantic word embedding map $\textbf{W}^s_n\in \mathcal{R}^{h\times w\times d}$ with pixel-wise category embedding $\textbf{w}^s_{n,i} = {\bar{\textbf{w}}}_{c_{n,i}^s}$. To generate fake pixel-wise feature, $\textbf{Z}_n$ is then concatenated with $\textbf{W}^s_n$ as the input of generator $G$, which can be written as ${\tilde{\textbf{x}}}_{n,i}^s=G(\textbf{z}_{n,i},\textbf{w}_{n,i}^s)$ for each pixel-wise generation process. As discussed in Section~\ref{intro}, since category-specific $\textbf{w}^s_{n,i}$ and adequate contextual information $\textbf{z}_{n,i}$ is passed to $G$ to resolve the ambiguity of output, we expect $G$ to reconstruct the pixel-wise feature $\textbf{x}^s_{n,i}$. This goal is accomplished by a L2 reconstruction loss $\mathcal{L}_{REC}$: \begin{eqnarray} \mathcal{L}_{REC}=\sum_{n,i}||\textbf{x}^s_{n,i}-{\tilde{\textbf{x}}}^s_{n,i}||^2_2. \end{eqnarray} We also use a classification loss and an adversarial loss to regulate the generated features. Since the down-sampled label map $\textbf{Y}_n^s$ has the same spatial resolution as the real feature map $\textbf{X}_n^s$, $\textbf{y}_{n,i}^s$ one-to-one corresponds to $\textbf{x}_{n,i}^s$ pixel-wisely. Following many segmentation papers~\cite{long2015fully,zhao2017pyramid,chen2018deeplab,Lin2016RefineNet}, we use the cross-entropy loss function as classification loss $\mathcal{L}_{CLS}$. It can be written as \begin{eqnarray}\label{eqn:L_cls} \mathcal{L}_{CLS} =-\sum_{n,i}\textbf{y}_{n,i}^s\log(C(\textbf{x}_{n,i}^s)), \end{eqnarray} where the segmentation score from $C$ is normalized by a softmax function. Following~\cite{MaoLeast}, adversarial loss $\mathcal{L}_{ADV}$ can be written as \begin{eqnarray}\label{eqn:L_adv} \mathcal{L}_{ADV} =\sum_{n,i} (D(\textbf{x}_{n,i}^s))^2 + (1-D(G(\textbf{z}_{n,i}, \textbf{w}_{n,i}^s)))^2, \end{eqnarray} in which the discrimination score from $D$ is normalized within $[0,1]$ by a sigmoid function, with target $1$ (\emph{resp.}, $0$) indicating real (\emph{resp.}, fake) pixel-wise features. Then, we introduce the pixel-wise feature generation pipeline for both seen and unseen categories. We can feed a latent code $\textbf{z}$ randomly sampled from $\mathcal{N}(0,1)$ and a semantic word embedding ${\bar{\textbf{w}}}_c$ into $G$ to generate a pixel-wise feature $G(\textbf{z}, {\bar{\textbf{w}}}_c)$ for arbitrary category $c\in \mathcal{C}^s\cup \mathcal{C}^u$. Intuitively, $G(\textbf{z}, {\bar{\textbf{w}}}_c)$ stands for the pixel-wise feature of category $c$ in the context encoded by $\textbf{z}$. \subsection{Optimization}\label{sec:optimization} As shown in Figure~\ref{ours}, our optimization procedure has two steps in different colors: training and finetuning. 1) \textbf{Training:} In this step, the segmentation network and the feature generation network are trained jointly based on image data and segmentation masks of only seen categories. All network modules $(E, CM, G, D, C)$ are updated. The objective function contains the loss terms introduced in Section~\ref{sec:context_feature_generator}: $$ \min\limits_{G,E,C,CM}\max\limits_D \quad \mathcal{L}_{CLS}+\mathcal{L}_{ADV}+\lambda_1 \mathcal{L}_{REC}+\lambda_{2}\mathcal{L}_{KL}.$$ Note that during optimization, we first update the parameters in $ D $ by maximizing the objective function, aiming to improve the discrimination ability of $ D $. Then we try to minimize the objective function to update the other parameters of the network to both enhance the performances of segmentation and feature generation. 2) \textbf{Finetuning:} In this step, we consider both seen and unseen categories, so that the segmentation network can generalize well to unseen categories. For ease of computation, we construct the $m$-th word embedding map ${\tilde{\textbf{W}}}^{s\cup u}_m\in \mathcal{R}^{h\times w\times d}$ by randomly stacking pixel-wise word embeddings ${\tilde{\textbf{w}}}^{s\cup u}_{m,i}$ of both seen and unseen categories. The corresponding label map is ${\tilde{\textbf{Y}}}^{s\cup u}_m$ with pixel-wise label vector ${\tilde{\textbf{y}}}^{s\cup u}_{m,i}$. We use approximately the same number of seen and unseen pixels in each ${\tilde{\textbf{W}}}^{s\cup u}_m$, which can generally achieves good performances as discussed in Table~\ref{training} of Section~\ref{Hyper-parameter_Analyses}. Then, we generate fake feature map ${\tilde{\textbf{X}}}^{s\cup u}_m$ with pixel-wise feature ${\tilde{\textbf{x}}}^{s\cup u}_{m,i}$, based on ${\tilde{\textbf{W}}}^{s\cup u}_m$ and contextual latent code map ${\tilde{\textbf{Z}}}_m$ with pixel-wise latent code ${\tilde{\textbf{z}}}_{m,i}$ sampled from $\mathcal{N}(\textbf{0,1})$. The above pixel-wise feature generation process can be formulated as ${\tilde{\textbf{x}}}^{s\cup u}_{m,i}=G({\tilde{\textbf{z}}}_{m,i},{\tilde{\textbf{w}}}^{s\cup u}_{m,i})$. We freeze $E$ and $CM$ because there are no real visual features for gradient backpropagation. Only $G$, $D$, and $C$ are updated. Thus, the objective function can be written as $$ \min\limits_{G,C}\max\limits_D \quad \mathcal{\tilde{L}}_{CLS}+\mathcal{\tilde{L}}_{ADV},$$ in which $\mathcal{\tilde{L}}_{CLS}$ is obtained by replacing $\textbf{y}_{n,i}^s$ (\emph{resp.}, $\textbf{x}_{n,i}^s$) in (\ref{eqn:L_cls}) with ${\tilde{\textbf{y}}}_{m,i}^{s\cup u}$ (\emph{resp.}, ${\tilde{\textbf{x}}}_{m,i}^{s\cup u}$). For $\mathcal{\tilde{L}}_{ADV}$, we replace $\textbf{w}_{n,i}^s$ (\emph{resp.}, $\textbf{z}_{n,i}$) in (\ref{eqn:L_adv}) with ${\tilde{\textbf{w}}}_{m,i}^{s\cup u}$ (\emph{resp.}, ${\tilde{\textbf{z}}}_{m,i}$), and delete the first term $(D(\textbf{x}_{n,i}^s))^2$ within the summation formula since we have no real features in this step. The optimizing process is the same as the training step by iteratively maximizing and minimizing the objective function. \begin{table*} \centering \setlength{\tabcolsep}{1mm}{ \begin{tabular}{c|cccc|ccc|ccc} \toprule[1.5pt] \multicolumn{11}{c}{Pascal-Context}\\ \hline \multirow{2}*{Method} & \multicolumn{4}{c}{Overall} & \multicolumn{3}{c}{Seen} & \multicolumn{3}{c}{Unseen} \\ ~ & \textbf{hIoU} & mIoU & pixel acc.& mean acc. & mIoU & pixel acc. & mean acc. & mIoU & pixel acc. & mean acc. \\ \hline SPNet& 0& 0.2938& 0.5793& 0.4486& 0.3357& \textbf{0.6389}& 0.5105& 0&0& 0\\ SPNet-c& 0.0718&0.3079& 0.5790& 0.4488& 0.3514& 0.6213& 0.4915& 0.0400& 0.1673& 0.1361\\ ZS3Net&0.1246 & 0.3010 &0.5710 & 0.4442 & 0.3304 & 0.6099 & 0.4843 & 0.0768 & 0.1922 & 0.1532 \\ \textbf{CaGNet}&\textbf{0.2061} &\textbf{0.3347} & \textbf{0.5924} &\textbf{0.4900} & \textbf{0.3610} & 0.6189 & \textbf{0.5140} & \textbf{0.1442} & \textbf{0.3341} &\textbf{0.3161} \\ \hline ZS3Net+ST& 0.1488 & 0.3102 & 0.5725 & 0.4532 & 0.3398 & 0.6107 & 0.4935&0.0953 & 0.2030 & 0.1721 \\ \textbf{CaGNet+ST} &\textbf{0.2252} &\textbf{0.3352} & \textbf{0.5961} &\textbf{0.4962} &\textbf{0.3644} & \textbf{ 0.6120} &\textbf{0.5065} & \textbf{0.1630} & \textbf{0.4038} & \textbf{0.4214 } \\ \toprule[1.2pt] \multicolumn{11}{c}{COCO-stuff}\\ \hline SPNet& 0.0140 & 0.3164 & 0.5132 & 0.4593&0.3461 & \textbf{0.6564} & 0.5030 &0.0070 & 0.0171 & 0.0007 \\ SPNet-c&0.1398 & 0.3278 &0.5341 &0.4363 & 0.3518 & 0.6176 &0.4628 & 0.0873 &0.2450 & 0.1614 \\ ZS3Net& 0.1495 & 0.3328 & 0.5467 &0.4837 &0.3466 & 0.6434 & 0.5037 & 0.0953 & 0.2275 & 0.2701 \\ \textbf{CaGNet}& \textbf{0.1819} &\textbf{0.3345} & \textbf{0.5658} &\textbf{0.4845} & \textbf{0.3549} & 0.6562 & \textbf{0.5066} & \textbf{0.1223} & \textbf{0.2545} & \textbf{0.2701} \\ \hline ZS3Net+ST& 0.1620 &0.3367 & 0.5631 & \textbf{0.4862} &0.3489 & 0.6584 & 0.5042 & 0.1055 & 0.2488 &0.2718 \\ \textbf{CaGNet+ST} &\textbf{0.1946} &\textbf{0.3372} & \textbf{0.5676} &0.4854 &\textbf{0.3555} & \textbf{0.6587 } &\textbf{0.5058} & \textbf{0.1340} & \textbf{0.2670} & \textbf{0.2728} \\ \toprule[1.2pt] \multicolumn{11}{c}{Pascal-VOC}\\ \hline SPNet& 0.0002 &0.5687 & 0.7685 & 0.7093 &0.7583 & \textbf{0.9482} & \textbf{0.9458} & 0.0001 & 0.0007 & 0.0001 \\ SPNet-c&0.2610 &0.6315 & 0.7755 &0.7188 &0.7800 &0.8877 &0.8791 & 0.1563 &0.2955 &0.2387 \\ ZS3Net&0.2874 &0.6164 &0.7941 &0.7349 &0.7730 & 0.9296 &0.8772 &0.1765 &0.2147 &0.1580 \\ \textbf{CaGNet}&\textbf{0.3972} &\textbf{0.6545} & \textbf{0.8068} &\textbf{0.7636} & \textbf{0.7840} & 0.8950 & 0.8868 &\textbf{0.2659} & \textbf{0.4297} & \textbf{0.3940} \\ \hline ZS3Net+ST& 0.3328 & 0.6302 & 0.8095 & 0.7382&0.7802 &\textbf{0.9189} &\textbf{0.8569} & 0.2115 & 0.3407 & 0.2637 \\ \textbf{CaGNet+ST} &\textbf{0.4366} &\textbf{0.6577} & \textbf{0.8164} &\textbf{0.7560} &\textbf{0.7859} & 0.8704 &0.8390 & \textbf{0.3031} & \textbf{0.5855} & \textbf{0.5071} \\ \bottomrule[1.5pt] \end{tabular} \caption{Zero-shot segmentation performances on Pascal-Context, COCO-stuff and Pascal-VOC. ``ST'' stands for self-training. The best results with or w/o self-training are denoted in boldface, respectively.} \label{coco} } \end{table*} By using ResNet-101~\cite{resnet-101} pre-trained on ImageNet~\cite{ILSVRC15} as the initialization of backbone $E$, we first apply the training step on our network for enough iterations. Next, we iteratively perform training and finetuning steps every 100 iterations to balance the network optimization based on real features and fake features. In the testing stage, a test image goes through segmentation backbone $ E $ and Contextual Module $ CM $ to obtain its real visual feature map, which is passed to classifier $ C $ to achieve segmentation results. \section{Experiments} \subsection{Datasets and Semantic Embeddings} We evaluate our model on three benchmark datasets: Pascal-Context \cite{mottaghi2014role}, COCO-stuff~\cite{caesar2018coco}, and Pascal-VOC 2012~\cite{EveringhamThePascalVisual}. The Pascal-Context dataset contains 4998 training and 5105 validation images of 33 object/stuff categories. COCO-stuff has 164K images with dense pixel-wise annotations from 182 categories. Pascal-VOC 2012 contains 1464 training images with segmentation annotations of 20 object categories. For Pascal-VOC, following ZS3Net and SPNet, we adopt additional supervision from semantic boundary annotations~\cite{Hariharan2011Semantic} during training. The experiment settings of two previous works, \emph{i.e.}, SPNet and ZS3Net, are different in many aspects (\emph{e.g.}, dataset, seen/unseen category split, backbone, semantic word embedding, evaluation metrics). SPNet reports results on large-scale COCO-stuff dataset\cite{caesar2018coco}, which makes their results more convincing. Besides, ZS3Net uses the word embedding of ``background'' as the semantic representation of all categories (\emph{e.g.}, sky and ground) belonging to ``background", which seems a little unreasonable, while SPNet ignores ``background" in both training and validation. Thus, we choose to strictly follow the settings of SPNet. But we also report the results by strictly following the settings of ZS3Net in the supplementary. Following SPNet~\cite{xian2019semantic}, we concatenate two different types of word embeddings ($d=600$, $300$ for each), \emph{i.e.}, word2vec~\cite{mikolov2013distributed} trained on Google News and fast-Text~\cite{joulin2017bag} trained on Common Crawl. The word embeddings of categories that contain multiple words are obtained by averaging the embeddings of each individual word. Our training/test sets are based on the standard train/test splits of three datasets, but we only use the pixel-wise annotations of seen categories and ignore the unseen pixels during training. For seen/unseen category split, following SPNet, we treat ``frisbee, skateboard, cardboard, carrot, scissors, suitcase, giraffe, cow, road, wallconcrete, tree, grass, river, clouds, playingfield'' as $15$ unseen categories on COCO-stuff, and treat ``potted plant, sheep, sofa, train, tv monitor'' as $5$ unseen categories on Pascal-VOC. We additionally report results on Pascal-Context with $33$ categories, which is a popular segmentation dataset but not used in~\cite{xian2019semantic}. On Pascal-Context, we treat ``cow, motorbike, sofa, cat'' as $4$ unseen categories. \subsection{Implementation Details}\label{hypers} Our generator $G$ is a multi-layer perceptron ($512$ hidden neurons, Leaky ReLU and dropout for each layer). Our classifier $C$ and discriminator $D$ consist of two $1\times 1$ conv layers and share the same weights in the first conv layer. During training, the learning rate is initialized as $2.5e^{-4}$ and divided by $10$ when the loss stops decreasing. The size of the training batch is $8$ on one Tesla V100. All input images are $368$ in size. We set $\lambda_{1}=10,\lambda_{2}=100$ via cross-validation by splitting a set of validation categories from seen categories. The analyses of $\lambda_{1},\lambda_{2}$ can be found in the supplementary. We report results based on three evaluation metrics, \emph{i.e.}, pixel accuracy, mean accuracy and mean Intersection over Union (mIoU) for both seen and unseen categories. Moreover, we also calculate the harmonic IoU (hIoU)~\cite{xian2019semantic} of all categories. \subsection{Comparison with State-of-the-art}\label{Implement} We compare our method with two baselines: SPNet~\cite{xian2019semantic} and ZS3Net \cite{bucher2019zero}. For a fair comparison, we use the same backbone Deeplabv2 as in \cite{xian2019semantic} for all methods. We also report the results of SPNet-c which deducts the prediction scores of seen categories by a calibration factor. Besides, we additionally employ the Self-Training (ST) strategy in~\cite{bucher2019zero} for both ZS3Net and our method. Specifically, we tag unlabeled pixels in training images using the trained segmentation model and add them to the training set to finetune the segmentation model iteratively. We do not compare with ZS3Net (GC) in~\cite{bucher2019zero}, because their used graph contexts are unavailable in our setting and also difficult to acquire in real-world applications. Among evaluation metrics, ``IoU'' quantizes the overlap between predicted and ground-truth objects, which is more reliable than ``accuracy'' considering the integrity of objects. For ``overall'' evaluation, ``hIoU'' is more valuable than ``mIoU'', because seen categories often have much higher mIoUs and dominate overall results. Experimental results are summarized in Table~\ref{coco}. For unseen and overall evaluation, our CaGNet achieves significant improvement over SPNet\footnote{Our reproduced results of SPNet on Pascal-VOC dataset are obtained using their released model and code with careful tuning, but still lower than their reported results.} and ZS3Net on all three datasets, especially \emph{w.r.t.} ``mIoU'' and ``hIoU''. For seen evaluation, our method underperforms SPNet in some cases, because SPNet almost segments all pixels as seen categories while our method sacrifices some seen pixels for much better unseen performance. \subsection{Ablation Study}\label{sec:ablation} We evaluate our CaGNet on Pascal-VOC for ablation studies. We only report four reliable evaluation metrics: hIoU, mIoU, seen IoU (S-mIoU), and unseen IoU (U-mIoU), as claimed in Section~\ref{Implement}. \begin{table}[tbp] \centering \resizebox{\columnwidth}!{ \begin{tabular}{cccc|cccc} \toprule[1.5pt] $E$ \& $C$ &$G$ &$D$ & $CM$ &\textbf{hIoU} &mIoU&S-mIoU&U-mIoU \\ \hline \hline \checkmark&&& &0 &0.5687 & 0.7583 & 0\\ \checkmark&&&\checkmark&0 & 0.5689 &0.7599 & 0\\ \checkmark&\checkmark& &&0.2911 &0.6332 & 0.7633 &0.1798\\ \checkmark&\checkmark&\checkmark &&0.3105 &0.6387 & 0.7751 &0.1941 \\ \checkmark&\checkmark& \checkmark &\checkmark& \textbf{0.3972} & \textbf{0.6545} & \textbf{0.7840}&\textbf{0.2659} \\ \bottomrule[1.5pt] \end{tabular}} \caption{Ablation studies of different network modules on Pascal-VOC. S-mIoU (\emph{resp.}, U-mIoU) is the mIoU of seen (\emph{resp.}, unseen) categories.} \label{novel} \end{table} \begin{table}[tbp] \centering \resizebox{\columnwidth}!{ \begin{tabular}{cccc|cccc} \toprule[1.5pt] Layer & Dilated & MS & CS &\textbf{hIoU} &mIoU&S-mIoU&U-mIoU \\ \hline \hline conv ($1\times 1$)&&&& 0.3211 & 0.6394 &0.7762 &0.2023 \\ conv&&&&0.3298 & 0.6408 & 0.7768&0.2093 \\ conv&\checkmark&&&0.3654 & 0.6502 & 0.7789 &0.2386\\ conv&\checkmark&\checkmark&&0.3825 &0.6526 &0.7810 &0.2532\\ conv (mask) & \checkmark&\checkmark &\checkmark &0.3961 & 0.6538 & 0.7821& 0.2652\\ conv & \checkmark&\checkmark &$\circ$ &0.3902 & 0.6529 & 0.7816 &0.2600 \\ conv&\checkmark& \checkmark &\checkmark & \textbf{0.3972} & \textbf{0.6545} & \textbf{0.7840}&\textbf{0.2659} \\ \bottomrule[1.5pt] \end{tabular}} \caption{Ablation studies of different variants of the contextual module on Pascal-VOC. ``MS'' and ``CS'' stand for Multi-Scale and Context Selector respectively.} \label{architecture} \end{table} \noindent \textbf{Validation of network modules:} We validate the effectiveness of each module ($E$, $C$, $G$, $D$, $CM$) in our method. The results are reported in Table~\ref{novel}, from which we can see that simply applying $CM$ to the segmentation network only brings marginal improvement. Feature generation with $G, D$ significantly raises the performance of unseen categories due to the reduced gap between seen and unseen categories. Finally, our proposed Contextual Module ($CM$) achieves evident improvements \emph{w.r.t.} all metrics. \noindent \textbf{Variants of contextual module:} We explore different architectures before predicting $\bm{\mu}_{\textbf{Z}_n}$ and $\bm{\sigma}_{\textbf{Z}_n}$ in our Contextual Module ($CM$) from simple to complex in Table~\ref{architecture}, in which the last row is our proposed $CM$. The first row simply utilizes two $1\times 1$ conv layers without capturing contextual information, and the bad performance shows the benefit of using contextual information. The second row utilizes five standard conv layers (number of model parameters equal to our $CM$) to capture contextual information. The third row replaces the first three conv layers in the second row with three dilated conv layers as in our $CM$ and achieves better results, which shows the benefit of using dilated conv. Built upon the third row, the fourth row further concatenates multi-scale contextual information $[{\hat{\textbf{F}}}^0_n,{\hat{\textbf{F}}}^1_n,{\hat{\textbf{F}}}^2_n]$ as in our $CM$ and applies a $1\times1$ conv layer, but does not use the context selector. The fourth row is better than the third row but worse than the last row, which proves the advantage of aggregating multi-scale contextual information and adaptively weighting different scales for different pixels. \begin{table}[tbp] \centering \begin{tabular}{c|cccc} \toprule[1.5pt] loss &\textbf{hIoU} & mIoU& S-mIoU& U-mIoU \\ \hline \hline w/o $\mathcal{L}_{KL}$ & 0.3772 & 0.6513&0.7801& 0.2487 \\ w/o $\mathcal{L}_{GAN}$ & 0.3154 &0.6392& 0.7753& 0.1979 \\ w/o $\mathcal{L}_{REC}$ & 0.2176 &0.6473 & 0.7835& 0.1263 \\ \hline CaGNet & \textbf{0.3972} & \textbf{0.6545} & \textbf{0.7840}&\textbf{0.2659} \\\bottomrule[1.5pt] \end{tabular} \caption{Ablation studies of loss terms on Pascal-VOC.} \label{losses} \end{table} \begin{table}[tbp] \centering \begin{tabular}{c|cccc} \toprule[1.5pt] $r$ (seen:unseen) &\textbf{hIoU} & mIoU& S-mIoU& U-mIoU \\ \hline \hline $|\mathcal{C}^s|:|\mathcal{C}^u|$ &0.2887 &0.6425&\textbf{0.7898}& 0.1763 \\ $1:1$ &\textbf{0.3972} & \textbf{0.6545} & 0.7840&\textbf{0.2659} \\ $1:10$ &0.3896 &0.6375&0.7687& 0.2617 \\ $0:1$ & 0.3766 &0.6024 &0.6620 & 0.2632\\ \bottomrule[1.5pt] \end{tabular} \caption{Performances of different \textbf{feature generating ratio} $r$ during the finetuning step on Pascal-VOC.} \label{training} \end{table} We also study a special case of our $CM$ in the fifth row named ``conv (mask)". The only difference is that we set the central $1\times 1\times l$ weights of all $3\times 3\times l$ conv filters as constant zeros without any update in the first dilated conv layer. In this way, when gathering the contextual information for each pixel, we roughly eliminate the impact of its own pixel-wise feature. The results in the fifth row are comparable with those in the last row, so it does not matter whether to eliminate the pixel-wise information for each pixel themselves. \begin{figure}[tbp] \centering \includegraphics[width=\linewidth]{visseg.pdf} \caption{Visualization of zero-shot segmentation results on Pascal-VOC. GT mask is ground-truth segmentation mask.} \label{visseg} \end{figure} Another variant of our $CM$ is in the sixth row, in which $\circ$ means we modify the context selector by learning only one weight for each scale without considering inter-pixel difference. Specifically, we perform global average pooling on $[{\hat{\textbf{F}}}^0_n,{\hat{\textbf{F}}}^1_n,{\hat{\textbf{F}}}^2_n]$ followed by a FC to obtain a $1\times 1\times3$ scale weight vector, which is replicated to an $h\times w\times3l$ scale weight map. The results in the sixth row are also worse than the last row, showing the effectiveness of contextual information. Besides these results, we also evaluate two more special cases of $CM$, ``w/o residual'' and ``Parallel'' in the supplementary. \noindent \textbf{Validation of loss terms:} We remove each loss term (\emph{i.e.}, $\mathcal{L}_{KL}$, $\mathcal{L}_{ADV}$, $\mathcal{L}_{REC}$) and report the results in Table~\ref{losses}. We observe that the performance becomes worse after removing any loss, which demonstrates that all loss terms contribute to better performance. \subsection{Hyper-parameter Analysis}\label{Hyper-parameter_Analyses} There exists a hyper-parameter during the finetuning step. We name it as the feature generating ratio (notated as $r$), which is the expected count ratio of seen pixels to unseen pixels while constructing each semantic word embedding map for feature generation. For example, if we randomly construct a word embedding map without any constraint, then $r=|\mathcal{C}^s|:|\mathcal{C}^u|$. However, in this case, seen features are much more than unseen features in pixel level (29:4 on Pascal-Context, 167:15 on COCO-stuff), leading to bad performances on unseen categories. After a few trials, we find that the reasonable feature generating ratio $r$ is $1:1$, as shown in Table~\ref{training}. The analyses of the other two hyper-parameters $\lambda_{1},\lambda_{2}$ can be found in the supplementary. \begin{figure}[tbp] \centering \includegraphics[width=\linewidth]{visgen.pdf} \caption{Visualization of context-aware feature generation on Pascal-VOC test set. GT mask is ground-truth segmentation mask. In the third and fourth columns, we show the reconstruction loss maps calculated based on the generated feature maps and real feature maps (the darker, the better).} \label{visgen} \end{figure} \subsection{Qualitative Analyses} We also provide some visualizations on Pascal-VOC. More visualization results can be found in the Supplementary. \noindent\textbf{Semantic segmentation:} We show the segmentation results of baselines and our method in Figure~\ref{visseg}, in which ``GT'' means ground-truth. Our method performs more favorably when segmenting unseen objects, \emph{e.g.}, the train (green), tv monitor (orange), potted plant (green), sheep (dark blue) in the sorted four rows. \noindent \textbf{Feature generation:} To confirm the effectiveness of feature generation with Contextual Module ($CM$), we evaluate the generated features on test images. On the one hand, we feed ground-truth semantic word embeddings and latent code into the generator to obtain the generated feature map. On the other hand, we input the test image to the segmentation backbone to obtain the real feature map. Then, we show the reconstruction loss map calculated based on the generated and real feature maps in Figure~\ref{visgen}, in which smaller loss implies better generation quality. We compare our method ``with $CM$'' (latent code is contextual latent code produced by $CM$) with the special case ``w/o $CM$'' (latent code is random vector). We can observe that our $CM$ not only helps generate better features for seen categories (\emph{e.g.}, ``person''), but also for unseen categories (\emph{e.g.}, ``potted plant, sheep, sofa, tv monitor''). \begin{figure}[tbp] \centering \includegraphics[width=0.9\linewidth]{viscon.pdf} \caption{Visualization of the effectiveness of context selector on Pascal-VOC. GT mask is ground-truth segmentation mask. The scale selection map is obtained from the scale weight map, in which dark blue, green, light blue represents small scale, middle scale, and large scale respectively.} \label{viscon} \end{figure} \noindent\textbf{Context selector:} The target of our context selector is to select context of the suitable scale for each pixel based on the scale weight map $[\textbf{A}_n^0,\textbf{A}_n^1,\textbf{A}_n^2]\in\mathcal{R}^{h\times w\times 3}$, in which each pixel-wise vector contains three scale weights for the pixel it corresponds to. In our implementation, $\textbf{A}_n^0$ (\emph{resp.}, $\textbf{A}_n^1$, $\textbf{A}_n^2$) corresponds to small scale (\emph{resp.}, middle scale, large scale) with the size of receptive field being $3\times3$ (\emph{resp.}, $7\times7$, $17\times17$) \emph{w.r.t.} the input feature map $\textbf{F}_n$. In Figure~\ref{viscon}, we list some examples with their corresponding scale selection maps and ground-truth segmentation masks. Note that the scale selection map is obtained from the scale weight map by choosing the scale with the largest weight for each pixel. We use three colors to indicate the most suitable scale (largest weight) of each pixel. In detail, dark blue, green, and light blue represent small scale, medium scale, and large scale respectively. From Figure~\ref{viscon}, we can observe that the pixels within discriminative local regions prefer the small scale while the other pixels prefer medium or large scale, which can be explained as follows. For the pixels within discriminative local regions (\emph{e.g.}, animal faces, small objects on the table), small-scale contextual information is sufficient for reconstructing pixel-wise features, while other pixels may require contextual information of larger scale. Another observation is small (\emph{resp.}, large) objects prefer small (\emph{resp.}, large) scale (\emph{e.g.}, the small boat and the large boat in the second row). These observations verify our motivation and the effectiveness of our proposed context selector. \section{Conclusion} In this work, we have unified the segmentation network and feature generation for zero-shot semantic segmentation, which utilizes contextual information to generate diverse and context-aware features. Qualitative and quantitative results on three benchmark datasets have shown the effectiveness of our method. \begin{acks} The work is supported by the National Key R\&D Program of China (2018AAA0100704) and is partially sponsored by the National Natural Science Foundation of China (Grant No.61902247) and Shanghai Sailing Program (19YF1424400). \end{acks} \bibliographystyle{ACM-Reference-Format} \section{Comparison in the setting of ZS3Net} To further verify the effectiveness of our proposed method, we also evaluate our method in the setting of ZS3Net~\cite{bucher2019zero} (\emph{i.e.}, backbone, semantic word embedding method, seen/unseen splits, evaluation metrics). Note that we only follow the setting of ZS3Net~\cite{bucher2019zero} in this section, while in other sections we still follow SPNet~\cite{xian2019semantic}. Following ZS3Net~\cite{bucher2019zero}, we use word2vec~\cite{mikolov2013distributed} embeddings in length 300 as semantic word embeddings and use deeplabv3+~\cite{deeplabv3} as the backbone. For both evaluation and training, we treat ``background'' as a seen category following ZS3Net. We conduct experiments on Pascal-VOC dataset with 20 categories and Pascal-Context dataset with 59 categories. For seen/unseen split, we choose one of the splits provided by ZS3Net for each dataset: ``cow, motorbike, airplane, sofa'' as 4 unseen categories on Pascal-VOC dataset, and ``cow, motorbike, sofa, cat, boat, fence, bird, tvmonitor, keyboard, aeroplane'' as 10 unseen categories on Pascal-Context dataset. The experimental results are shown in Table~\ref{exp1} and the results of ZS3Net are directly copied from their paper. Our method achieves comparable or better results on seen categories. More importantly, our method significantly improves the results on unseen categories. For overall hIoU, our method achieves the improvement of $13.0$ and $4.9$ on Pascal-VOC and Pascal-Context respectively. This indicates that our method still beats ZS3Net in their setting with dramatic improvements. Another observation is that our method has much larger performance gain on Pascal-VOC than Pascal-Context, which may be due to the difficulty in segmenting more unseen categories. \begin{table} \centering \resizebox{\columnwidth}!{ \begin{tabular}{c|cccc} \toprule[1.5pt] &\textbf{hIoU} &mIoU&S-mIoU&U-mIoU \\ \hline \hline w/o residual& 0.3862 & 0.6480 & 0.7815 & 0.2564\\ Paralle& 0.3821 &0.6509 & 0.7832 &0.2527 \\ \hline CaGNet& \textbf{0.3972} & \textbf{0.6545} & \textbf{0.7840}&\textbf{0.2659} \\ \bottomrule[1.5pt] \end{tabular}} \caption{Ablation studies of special cases of the contextual module on Pascal-VOC.} \label{specialcase} \end{table} \section{More Ablation Studies on Our Contextual Module} In this section, we add two more special cases ``w/o residual" and ``Parallel" to supplement Table 3 of Section 4.4 in the main paper, as part of the ablation studies on different variants of our Contextual Module. In the special case ``w/o residual", our Contextual Module ($CM$) outputs the contextual latent code without being linked back to the segmentation network, so that residual attention is not applied to feature map $\textbf{F}_n$ to obtain enhanced feature map $\textbf{X}_n$. In this case, the contextual latent code is obtained in the same way, while the target of feature reconstruction becomes $\textbf{F}_n$ instead of $\textbf{X}_n$. We also replace $\textbf{X}_n$ with $\textbf{F}_n$ in all loss functions. The results are shown in the first row of Table~\ref{specialcase}. We can observe that linking our $CM$ to the segmentation network improves the performances on all metrics. In the special case ``Parallel", we change the way of arranging three dilated conv layers in $CM$ from serial to parallel. That is, we parallelly put three dilated conv layers (same parameters as those in original $CM$ respectively) after the input feature map $\textbf{F}_n$ and obtain context maps of different receptive fields. The receptive fields of three dilated convs are $3\times3$, $5\times 5$, and $13\times 13$ on $\textbf{F}_n$ respectively, which are equal to or smaller than those ($3\times3$, $7\times 7$, and $17\times 17$) in the serial mode. The experiment results of the second row in Table~\ref{specialcase} indicates that the serial mode in the main paper is more superior than the parallel mode, probably due to the larger receptive fields of the obtained context maps. \section{Hyper-parameter Analyses} By taking Pascal-VOC dataset as an example, we investigate the impact of hyper-parameters $\lambda_{1}, \lambda_{2}$ in our method (depicted in Section 3.4 in the main paper). We vary $\lambda_{1}$ (\emph{resp.}, $\lambda_{2}$) within the range [0.1,1000] and report hIoU (\%) results of our method in Figure~\ref{alpha}. We observe that $\lambda_1$ has larger impact and the performance drops sharply when $\lambda_1$ is very small, which proves the necessity of feature reconstruction. Our method is robust when setting $\lambda_1$ (\emph{resp.}, $\lambda_2$) in a reasonable range [10, 100] (\emph{resp.}, [1, 1000]). \begin{figure}[] \centering \includegraphics[width=\linewidth]{alpha.pdf} \caption{The \textbf{effects} of varying the values of $\lambda_{1},\lambda_{2}$ on Pascal-VOC. The dashed lines denote the default values used in our paper.}\label{alpha} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{suppvis.pdf} \caption{Visualization of segmentation results for different methods on Pascal-VOC dataset. GT mask is the ground-truth segmentation mask.} \label{vis1} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{suppgen.pdf} \caption{Visualization of the effectiveness of Contextual Module (CM) in feature generation on test images on Pascal-VOC dataset. In the second column, GT mask is the ground-truth segmentation mask. In the third and fourth columns, we show the reconstruction loss maps calculated based on the generated feature maps and real feature maps (the darker, the better).} \label{vis2} \end{figure} \section{More visualizations of segmentation results} In this section, we show more visualizations of segmentation results for different methods in Figure~\ref{vis1}, supplementing the visualizations in Figure 5 of Section 4.6 in the main paper. As shown in Figure~\ref{vis1}, our method beats others when segmenting unseen objects like ``tv", ``train'', ``sofa'', and ``sheep'', which further proves the advantage of our method. For example, in the first and third row, SPNet and ZS3Net misclassify ``tv'' and ``sofa'' as ``table'', but our method segments them successfully. We can also observe that ``train'' in the second row is hard to segment by SPNet and ZS3Net. This is probably because the word ``train'' contains several distinct meanings and only one of them represents the typical unseen category in the dataset. Therefore, the semantic word embedding of ``train'' is not accurate enough for the model to segment objects of this category precisely. However, our method can still recognize and segment it. In the fourth row, ``sheep'' is also recognized by our method, while ZS3Net and SPNet classify it as ``cow''. \section{More visualizations of feature generation} We show more visualizations of feature generation in Figure~\ref{vis2}, supplementing the visualizations in Figure 6 of Section 4.6 in the main paper. By taking test images of Pascal-VOC dataset as examples, we show the reconstruction loss maps calculated based on the generated feature maps and their according real feature maps, in which smaller loss (darker region) implies better generation quality. We compare the reconstruction loss maps obtained by using Contextual Module ($CM$) or without $CM$. It can be observed from Figure~\ref{vis2} that our $CM$ not only facilitates generating better features for seen categories (\emph{e.g.}, ``person''), but also for unseen categories (\emph{e.g.}, ``tv'' in brown in the first two rows, ``potted plant'' in dark green in the fourth row). \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-08-18T02:17:07', 'yymm': '2008', 'arxiv_id': '2008.06893', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06893'}
arxiv
\section{Introduction} \label{introduction} Automated face analysis has many applications~\cite{application}, such as in medical treatment and human-computer interaction. However, the different factors of variation, such as age, gender, and identity overlap heavily \cite{li2018deep,sawant2019age}. In-the-wild data is almost always occluded due to head-pose or facial attributes like glasses or beard. Especially in facial expression recognition the performance of state-of-the-art methods is still unsatisfying. While the application of deep learning has led to superhuman performance in face identity recognition \cite{cao2018vggface2,Taigman14}, expression recognition on in-the-wild datasets is still an unsolved problem \cite{sfewresult1,kim2015hierarchica}. The efficiency of many data-driven tasks depends on the quality of the data representation \cite{Goodfellow2016a}, and the developments in deep learning in the last decade allow to learn rich task-specific features given a sufficient amount of labelled data \cite{Bengioy2012}. Due to the essential role these data representations play in determining the model’s overall performance, recent research has paid attention to these representations’ characteristics. One way to influence the learned features is disentangled representation learning \cite{Bengioy2012,BengioYann}. It aims to improve learned representations by separating the desired information from other factors, or sources of variation, thus obtaining higher levels of abstraction in captured representations and enabling better generalization \cite{Schmidhuber1992,Bengioy2012,BengioYann}. An example model that learns disentangled representations is an autoencoder~\cite{LeCun1987,Hinton1994}, which performs this by reconstructing the data as a linear combination of low-level features \cite{Bengioy2012}. Recently, \cite{Liu2018} introduced a framework called identity Distilling and Dispelling Autoencoder (D2AE), which disentangles face identity features from other features. Despite the similarity between our approach and theirs, we show that there is no need for a decoder network for disentangling facial expression representations. \cite{li2018occlusion} had achieved state-of-the-art on the AffectNet benchmark with 58.78\% accuracy using a CNN that utilizes attention mechanisms and is co-trained on multiple datasets. On the other hand, without additional attention mechanisms, nor additional datasets, our method outperforms theirs on the same benchmark. In this paper, we investigate the disentangling of expression representations from other factors of variation from face images. We use an encoder-based adversarial method. The main motivation is to tackle the problem of expression recognition in ``in-the-wild'' scenarios. \section{Learning Disentangled Expression Representations}\label{method} The proposed method generates two distinct representations by using two different encoders: the first encodes the facial expression representation from an input image, and the other encodes the representation of other factors of variation. However, these two encoders share some layers (for shared face features) using a shared encoder $En_{base}$. This shared encoder is followed by the two branches $B_{exp}$, and $B_{non-exp}$, which specialize in encoding expression and non-expression specific features, respectively. Then, the two encoders are trained in a way that enables a decoder to reconstruct the input image by combining the representations together. In order to achieve our goal of disentanglement, we use an adversarial loss that is imposed on non-expression representations, \emph{i.e.} to prevent them from being able to discriminate expressions. This way, we ensure that these representations do not contain any expression features. We also introduce another constraint that induces the expression representations to recognize expressions. Thus, the branch $B_{exp}$ is trained in a supervised manner with expression labels to capture expression features using an expression classifier $C_{exp}$. And $B_{non-exp}$ is trained adversarially to disentangle non-expression features using an expression discriminator $C^{adv}_{exp}$. Fig. \ref{fig29} shows our proposed model architecture. \\ \\ \textbf{Training Process: \label{sec:training1}} The loss function that guides the training process in the proposed method consists of many terms. First, a reconstruction loss $\mathcal{L}_{r}$ is imposed on the encoder-decoder, and the two branches $B_{exp}$ and $B_{non-exp}$ to ensure that $code_{exp}$ and $code_{non-exp}$ encode all important features from the input image $x$, respectively. This loss is an $L_2$-norm between the input image $x$ and its reconstruction ${x}'$, and is formally expressed as $\mathcal{L}_{r} = \left \| x - De(code_{exp} \oplus code_{non-exp}) \right \|^2$. The second loss is the expression classification loss $\mathcal{L}_{c-exp}$. We use the cross-entropy loss to train this classifier, as shown in eq.\ref{classify-exp}. The optimization over $\mathcal{L}_{exp}$ updates the shared encoder layers $En_{base}$, the expression branch layers $B_{exp}$, and the expression classifier layers $C_{exp}$. \begin{equation} \label{classify-exp} -\: \mathcal{L}_{exp} = \sum_{i=1}^{N_{exp}}\; y_{i} \;\log(C_{exp}(code_{exp})) \end{equation} where $N_{exp}$ is the number of emotions. Finally, we introduce the adversarial loss $\mathcal{L}_{adv}$ that is imposed on the output of the expression classifier $C^{adv}_{exp}$, which ensures that $code_{non-exp}$ does not contain any expression features. $\mathcal{L}_{adv}$, as any adversarial loss, consists of two parts: The first is $\mathcal{L}^{adv}_{exp}$ that is imposed on the output of the classifier $C^{adv}_{exp}$, which classifies $code_{non-exp}$ into one of the expressions. The optimization over $\mathcal{L}^{adv}_{exp}$ updates only the expression classifier layers $C^{adv}_{exp}$. The second part $\mathcal{L}^{adv}_{En}$, tries to fool the expression classifier $C^{adv}_{exp}$ by maximizing the uncertainty of the classifier's output for input images. Therefore, the optimization over $\mathcal{L}^{adv}_{En}$ updates the shared encoder layers $En_{base}$, and non-expression branch layers $B_{non-exp}$. The formulation of these losses is as follows: \begin{equation} \label{adv_gan} \begin{split} - \mathcal{L}^{adv}_{exp} &= \sum_{i=1}^{N_{exp}} y_{i} \log(C^{adv}_{exp}(code_{non-exp})) \\ - \mathcal{L}^{adv}_{En} &= \frac{1}{N_{exp}} \sum_{i=1}^{N_{exp}} \log(C^{adv}_{exp}(code_{non-exp})) \\ \mathcal{L}_{adv} &= \mathcal{L}^{adv}_{exp} + \mathcal{L}^{adv}_{En} \end{split} \end{equation} In order to train the proposed framework, we minimize the final objective function which is the weighted sum of all the above losses, and is given by $\mathcal{L}_{final}$ as follows: \begin{equation} \label{final1} \mathcal{L}_{final} = \beta_{1}\;\mathcal{L}_{r} + \beta_{2}\;\mathcal{L}_{exp} + \beta_{3}\;\mathcal{L}_{adv} \end{equation} Where $\beta_{1}$, $\beta_{2}$, $\beta_{3}$, are hyper-parameters to control the contribution of each loss. We should mention that we can optimize $\mathcal{L}_{r}$, $\mathcal{L}_{exp}$, and $\mathcal{L}^{adv}_{En}$ jointly. However, $\mathcal{L}^{adv}_{exp}$, is optimized independently from the above losses, and it updates $C^{adv}_{exp}$ while the other components of the model remain constant. \begin{figure*}[t] \centering \includegraphics[width=0.5\textwidth, height=0.2\textheight]{./fig/F.pdf} \caption{Disentangling expression representation from all other non expression features.} \label{fig29} \vspace{-8mm} \end{figure*} \section{Experiments} \label{experiments} \textbf{Experimental setup} \label{experiment-exp-nexp-setup} For the following experiments, we use the model in Fig. \ref{fig29}, where each expression branch $B_{exp}$ and non-expression branch $B_{non-exp}$ consists of four Conv. layers, with leaky-ReLU activation functions. The decoder $De$ consists of six De-conv. layers with leaky-ReLU activation functions, except for the last layer with a Sigmoid activation. The shared encoder $En_{base}$ is an Inception-ResNet-V1 \cite{szegedy2017inception} encoder, pre-trained on VGGFace2 dataset \cite{cao2018vggface2}. Both $C_{exp}$ and $C^{adv}_{exp}$ are linear classifiers. The values of the hyper-parameters in eq.\ref{final1} are $\beta_{1} = 0$, $\beta_{2} = \beta_{3} = 1$. Thus, there is no effect for the reconstruction loss, except for the experiment with an ablation study for the influence of the reconstruction loss. For all our experiments, we report the validation accuracy of $C_{exp}$ and $C^{adv}_{exp}$. However, when comparing with methods from the literature, we only provide results for $C_{exp}$, since other methods do not rely on an adversarial loss. The baseline model architecture is identical to the above model, only without the adversarial components. This means that the baseline consists of an encoder similar to $En_{base}$ in Fig. \ref{fig29}. This encoder is followed by four Conv. layers similar to $B_{exp}$. Then, the learned representation is fed as an input to the linear classifier $C_{exp}$ similar to $C_{exp}$ in Fig. \ref{fig29} as well. \\ \\ \textbf{Results} \label{experiment-exp-nexp-results1} The first row in Table \ref{tab:results5} shows that we outperform the baseline on the AffectNet dataset, confirming that our method provides a performance boost on the task of FER. In Table \ref{tab:results5} we also compare to methods from literature, and report the classification accuracy. We obtain the results for these methods from \cite{li2018occlusion}. The first method (VGG16) is a simple classifier that uses the VGG16 architecture \cite{simonyan2014very} trained on a mix of RAF \cite{li2018reliable} and AffectNet \cite{mollahosseini2017affectnet} datasets. In the IPA2LT \cite{Zeng_2018_ECCV} framework, the samples are assigned to multiple labels. This method is also trained on a combination of RAF and AffectNet, and on 1.2 million unlabelled face images from AffectNet and Microsoft Bing. We also compare to gACNN \cite{li2018occlusion}, which relies on attention mechanisms in this task, and to DLP-CNN \cite{li2018reliable}, which simulates how attention mechanisms work using a CNN. It is noteworthy that our method outperforms all the above methods. It is worth mentioning that there are few works that achieve better accuracy on AffectNet by using additional datasets or multi-modal data \cite{cake} \cite{NIPS2019} \cite{steven2}. The ablation study for the effect of the reconstruction task is shown in Table \ref{tab:results-en-de-loss}, which shows the classification accuracy of $C_{exp}$ and $C^{adv}_{exp}$ on AffectNet dataset when we set the hyper-parameter $\beta_{1}$ in eq.\ref{final1}. The results in the table confirm that the reconstruction task has a negative effect on disentangling, e.g. when $\beta_{1}=1$ or $\beta_{1}=0.001$ both representations $code_{exp}$ and $code_{non-exp}$ have a similar ability in encoding expression features, which means less disentangling performance. However, we achieve the best performance when there is no effect for the reconstruction loss $\beta_{1} = 0$. Higher $C_{exp}$ accuracy indicates better classification results, however, lower $C^{adv}_{exp}$ accuracy indicate better disentangling behavior. In order to evaluate the quality of the learned representations on other datasets, we chose randomly a few images from the CASIA dataset \cite{casia}. Table \ref{tab:results-cos-similar} shows the cosine-similarity between the representations of these images, and shows that images with the same expressions have more similar representations regardless of their identities. \begin{table} \parbox[t]{.45\linewidth}{ \centering \small \label{fig35} \begin{minipage}[t]{0.45\textwidth} \centering \includegraphics[width=0.8\textwidth, height=0.2\textheight]{fig/F35.jpg} \captionof{figure}{\label{fig89}Synthesize images from happy and neutral images of the same identity} \end{minipage} } \hfill \parbox[t]{.45\linewidth}{ \centering \small \caption{Comparison to results from literature on AffectNet dataset}\label{tab:results5}\vspace{-5mm} \begin{tabular}[t]{ c c } \toprule Approach & Test Accuracy \\ \hline Baseline & 56\%\\ \hline VGG16 \cite{simonyan2014very} & 51.11\% \\ DLP-CNN \cite{li2018reliable} & 54.47\% \\ IPA2LT \cite{Zeng_2018_ECCV} & 57.31\% \\ gACNN \cite{li2018occlusion} & 58.78\%\\ \hline Proposed method & \textbf{60.53\%} \\ \hline \end{tabular} } \vspace{0.5cm} \\ \parbox[t]{.45\linewidth}{ \centering \small \caption{Studying the effect of the reconstruction loss on the disentangling performance}\label{tab:results-en-de-loss}\vspace{-5mm} \begin{tabular}[t]{ c c c } \toprule Hyper-parameter & $C_{exp}$ Acc. & $C^{adv}_{exp}$ Acc. \\ \hline $beta_1=1.0$& 51\% & 46\% \\ $beta_1=0.001$& 56\% & 53\% \\ $beta_1=0.0$& \textbf{60.53\%} & \textbf{16\%}\\ \hline \end{tabular} } \hfill \parbox[t]{.45\linewidth}{ \centering \small \caption{Cos-Similarity between two expression representations learned by the proposed disentangling method}\label{tab:results-cos-similar} \vspace{-5mm} \begin{tabular}[t]{ c c c } \toprule Im-1 & Im-2 & Cos-sim.(Im-1,Im-2) \\ \hline \rowincludegraphics[scale=0.1]{fig/h_jon.jpg} & \rowincludegraphics[scale=0.1]{fig/n_jon.jpg} & 0.7877541 \\ \hline \rowincludegraphics[scale=0.1]{fig/n_boy.jpg} & \rowincludegraphics[scale=0.1]{fig/n_jon.jpg}& 0.83162177 \\ \hline \end{tabular} }\vspace{-1cm} \\ \end{table} \section{Conclusion and Future Work} \label{conclusion} This work aimed to improve the performance of facial expression recognition in the wild. To achieve that, we proposed applying an adversarial method to disentangle expression representations from other factors of variation in facial images. We improve state-of-the-art results \cite{li2018occlusion} on the AffectNet benchmark to \textbf{60.53\%} accuracy, \textbf{without using any additional data}. We also show that the reconstruction constraint is detrimental to the disentangling performance. Our work boosts the performance on the FER task, yet we see a room for improvement when disentangling \emph{known} causal factors of variation. This is in line with the findings of \cite{Locatello2018} too. Therefore, in a preliminary set of experiments, we disentangle the identity representation from the expression representation and vise versa, by imposing additional adversarial loss on expression representation similar to eq.\ref{adv_gan}, using identity labels instead. The qualitative results in Fig.\ref{fig89} show a clear disentangling between expression and identity representations on the CK+ dataset \cite{lucey2010extended}. Where $X_1$ and $X_2$ are the original images, and $X^{'}_1$ is obtained by decoding both representations of $X_1$, and so is $X^{'}_2$ from $X_2$. $X_{1}^{''}$, and $X_{2}^{''}$ are synthesized by swapping the expression and identity representations of $X_1$ and $X_2$. Therefore, as a future work, we plan to examine disentangling multiple known factors of variation and generalize this work to multiple datasets. \bibliographystyle{splncs04}
{'timestamp': '2020-08-19T02:10:03', 'yymm': '2008', 'arxiv_id': '2008.07001', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07001'}
arxiv
\section{Introduction}~\label{sec:intro} Detecting and describing local features (\ie interest points) for the purpose of finding correspondences between images is an important task in computer vision. The estimation of correspondences between a pair of images, \ie image matching or feature matching, is a crucial step in many pipelines in SLAM, Visual Odometry, Structure-from-Motion, Image-based localization, Panorama stitching \etc. These computer vision tasks are the main building blocks for many applications in Augmented and Mixed Reality, Robotics and Autonomous Driving. Hand-crafted features such as SIFT~\cite{sift} and ORB~\cite{orb} are still dominant for estimating correspondences in existing systems such as COLMAP~\cite{colmap1} and ORB-SLAM~\cite{orbslam}. Motivated by ability of neural networks to learn representations that are invariant, much focus recently has been spent on using deep learning to train neural networks to describe and/or detect local features (see a survey by Csurka and Humenberger~\cite{csurka2018handcrafted}). For local features in particular, it is desirable to have representations that are invariant or robust to nuisance changes, which are mainly due to either viewpoint variation or appearance variation due to illumination and weather changes. Many SOTA detectors and descriptors (\eg R2D2~\cite{r2d2,r2d2_neurips}, D2-Net~\cite{d2net}, ASLfeat~\cite{aslfeat}, ContextDesc~\cite{contextdesc}, \etc) exploit large structure-from-motion reconstructions with semi-dense multi-view stereo depth estimates during their training to learn descriptors (and sometimes detectors) that are robust to viewpoint changes. These SfM reconstructions are now easier to obtain due to software packages like COLMAP~\cite{colmap1,colmap2}, but careful filtering of pixels is still required to obtain high quality depth maps~\cite{megadepth}. In addition to SfM reconstructions, there is another computationally cheap source of training data: synthetically warped images with known homography transformations. The synthetically warped images can be generated from millions of images available from the internet~\cite{imagenet,mscoco}. Recently proposed models such as Superpoint~\cite{superpoint}, PN~\cite{yan2019unsupervised}, and R2D2~\cite{r2d2} use this source of data for training, sometimes in addition to other sources of data that capture viewpoint changes. Learning features that are invariant to illumination or weather changes is challenging as suitable data is not easy to acquire. We show that color augmentations at training time increases robustness to appearance changes, but it is not sufficient by itself. SfM systems can build 3D models from internet images that are captured at different times and weather conditions. Hence training on this data introduces some robustness to appearance changes. However, building 3D models from images captured under extreme changes is much more challenging, \eg reconstructing 3D models from day and night images~\cite{radenovic2016dusk}. Another data source for appearance robustness is webcam footage archives~\cite{amos1,amos2,amospatches,verdie2015tilde}, where stationary cameras throughout the world broadcast imagery for many years. However, this source of data has its own challenges: (i) There are moving objects in the frames, which are difficult to detect, \eg is an appearance change between two frames due to a shadow cast by a tree, or a grey car that is parked on the street?; (ii) Very few cameras are completely stationary, as the camera mount can sometimes be readjusted or wind could introduce small, but noticeable motion; (iii) Majority of webcams have low resolution, limited dynamic range, bad focus, etc. Amos Patches~\cite{amospatches} proposes a pipeline to deal with these challenges with an additional manual verification at the end of the process. Despite large amount of webcam data, the resulting Amos Patches dataset consists of only 1350 images (50 images per 27 cameras). Robustness to day-night variation using image stylization was proposed in R2D2 method~\cite{r2d2}. Day images from Aachen dataset~\cite{aachen1,sattler2018benchmarking} were converted to night images using image stylization~\cite{Li_2018_ECCV}. This resulted in improvement of descriptors for day to night feature matching, as during training each day image would have a corresponding night images with exactly the same content. Ablation study showed that this improved performance on Aachen Day-Night Localization challenge. However, only Aachen images were stylized, and only to a night style. So, appearance variations associated with weather or season changes were not explicitly modelled. Second, image stylization was not applied to web images that were used for synthetic homography training. We investigate how local feature robustness to appearance variation can be improved with image stylization. Image stylization allows us to generate \emph{multiple} stylizations for the same image, \eg single day image can be stylized using 10 different night images as target styles, resulting in 10 night images with the same content and viewpoint. Furthermore, the same image can be stylized to different conditions, like snow, rain or night, see Figure~\ref{fig:style:example}. We conduct controlled experiments to compare how much gain does image stylization provide over other augmentation strategies in the literature under same evaluation conditions. We show that a model trained with synthetic homographies and image stylizations outperforms SOTA models trained with 3D correspondences. % Finally, we demonstrate competitive scores on multiple benchmarks and challenges that evaluate visual localization under illumination, weather, and season changes. \begin{figure}[t] \centering \includegraphics[width=.9\linewidth]{figures/teaser.pdf} \caption{Method overview. We train feature networks using original and stylized image pairs. Crops are extracted from the original and stylized images using random homographies. Image stylization and synthetic homography augmentation together allow us to learn features that are robust to appearance and viewpoint changes. } \label{fig:f_pipeline} \end{figure} \section{Method}\label{sec:method} For increased robustness of local features we train feature networks using original-stylized image pairs. Here, we describe how we generate stylized images and losses used for feature network training. \subsection{Image Stylization} \begin{figure*}[ht!] \centering \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/orig.jpg} \caption{Original} \end{subfigure}% ~ \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/cloud.png} \caption{cloud} \end{subfigure}% ~ \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/dusk.png} \caption{dusk} \end{subfigure}% ~ \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/mist.png} \caption{mist} \end{subfigure}% ~ \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/night.png} \caption{night} \end{subfigure}% ~ \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/rain.png} \caption{rain} \end{subfigure}% ~ \begin{subfigure}[t]{.14\textwidth} \centering \includegraphics[width=\textwidth]{figures/ch1_small/snow.png} \caption{snow} \end{subfigure} \caption{Example image stylizations applied to an image (a). Stylized images have extreme appearance changes, while the content of the original image is preserved. For example, the tree on the right and the details of the roof are reconizable in stylized images.}\label{fig:style:example} \end{figure*} Style transfer method takes as input 2 images, $C$ and $S$ and produces an image $C_S$ which has content of image $C$, but the style of image $S$. Similar to R2D2~\cite{r2d2} we use \cite{Li_2018_ECCV} for image stylization, as it preserves edges and objects after stylization, unlike other methods designed for artistic style transfer, \eg~\cite{gatys2015neural}. We model appearance variation in 6 styles/categories: cloud, dusk, mist, night, rain, and snow. For each style, there are 10 style images (see Figure~\ref{fig:styles}), which were manually selected from the set of contributing views of Amos Patches dataset~\cite{amospatches}. For each image in the training set, we generate 60 stylized images, 10 for each of 6 style categories. \begin{figure*}[ht!] \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20130808_115028.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20130816_002140.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20130815_132144.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20130817_065141.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20130818_225149.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20131012_142417.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20130818_185147.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20131007_045102.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20130912_155417.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20130830_234300.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20131012_075302.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20131125_104532.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20130828_144648.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20131027_223008.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20131015_171641.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20130907_214525.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20131019_144639.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20140109_181233.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20130829_120008.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20131217_155312.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170131_145304.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20131029_032103.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20131206_210005.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20141221_180736.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20130909_102518.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20140630_101223.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170208_143551.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20131227_094239.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20131223_153011.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20170110_094721.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20131013_130917.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20170220_052304.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170217_084535.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20141221_033719.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20141123_181226.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20170111_105417.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20170109_131554.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20170223_165410.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170301_133520.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20170101_015302.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20141228_130741.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20170117_085302.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20170307_202526.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20170317_050322.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170308_215312.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20170110_200654.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20170318_084539.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20170119_080606.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20170426_050329.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20170320_112533.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170506_110536.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20170119_025313.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20170322_072402.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20170215_094726.png} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/cloudy/20170504_100319.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/dusk/20170427_041537.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/mist/20170519_151722.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/night/20170310_002401.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/rainy/20170501_110319.png} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/styles_sub_10_resized/snow/20170428_054359.png} \end{minipage} \vspace{2pt} \centering \begin{minipage}{.13\textwidth} \centering cloudy \end{minipage} \begin{minipage}{.13\textwidth} \centering dusk \end{minipage} \begin{minipage}{.13\textwidth} \centering mist \end{minipage} \begin{minipage}{.13\textwidth} \centering night \end{minipage} \begin{minipage}{.13\textwidth} \centering rainy \end{minipage} \begin{minipage}{.13\textwidth} \centering snow \end{minipage} \caption{Style images manually selected from contributing views of Amos Patches dataset~\cite{amospatches}. See Figure~\ref{fig:stylized} for corresponding stylization results. There are 10 style examples for each style category.} \label{fig:styles} \end{figure*} \begin{figure*} \centering \begin{minipage}{.8\textwidth} \textbf{(a) Original Image}\\ \end{minipage} \\ \begin{minipage}{.8\textwidth} \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/644_db.jpg} \end{minipage} \centering \begin{minipage}{.8\textwidth} \centering \hrulefill\vspace{15pt}\par \setbox0=\hbox{% \begin{tabular}{|l|} \\ \hline \end{tabular} } \end{minipage} \\ \vspace{-3pt} \centering \begin{minipage}{.8\textwidth} \textbf{(b) R2D2 stylization results}\\ \end{minipage} \\ \begin{minipage}{.8\textwidth} \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/r2d2/644_st_1884.jpg} \end{minipage} \centering \begin{minipage}{.8\textwidth} \centering \hrulefill\vspace{15pt}\par \setbox0=\hbox{% \begin{tabular}{|l|} \\ \hline \end{tabular} } \end{minipage} \\ \vspace{-3pt} \centering \begin{minipage}{.8\textwidth} \textbf{(c) Our stylization results}\\ \end{minipage} \\ \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130808_115028___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130816_002140___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130815_132144___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130817_065141___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130818_225149___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131012_142417___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130818_185147___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131007_045102___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130912_155417___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130830_234300___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131012_075302___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131125_104532___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130828_144648___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131027_223008___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131015_171641___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130907_214525___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131019_144639___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20140109_181233___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130829_120008___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131217_155312___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170131_145304___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131029_032103___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131206_210005___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20141221_180736___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20130909_102518___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20140630_101223___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170208_143551___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131227_094239___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131223_153011___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170110_094721___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20131013_130917___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170220_052304___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170217_084535___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20141221_033719___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20141123_181226___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170111_105417___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170109_131554___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170223_165410___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170301_133520___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170101_015302___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20141228_130741___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170117_085302___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170307_202526___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170317_050322___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170308_215312___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170110_200654___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170318_084539___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170119_080606___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170426_050329___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170320_112533___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170506_110536___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170119_025313___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170322_072402___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170215_094726___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170504_100319___cloudy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170427_041537___dusk.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170519_151722___mist.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170310_002401___night.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170501_110319___rainy.jpg} \end{minipage} \begin{minipage}{.13\textwidth} \centering \includegraphics[height=0.06\textheight]{figures/r2d2_vs_us/us/644_st_20170428_054359___snow.jpg} \end{minipage} \centering \begin{minipage}{.13\textwidth} \centering cloudy \end{minipage} \begin{minipage}{.13\textwidth} \centering dusk \end{minipage} \begin{minipage}{.13\textwidth} \centering mist \end{minipage} \begin{minipage}{.13\textwidth} \centering night \end{minipage} \begin{minipage}{.13\textwidth} \centering rainy \end{minipage} \begin{minipage}{.13\textwidth} \centering snow \end{minipage} \caption{ From top to bottom: (a) Day image from Aachen Day-Night benchmark. (b) Night image stylization result used to train R2D2 model. (c) Our image stylization results using style images from Figure~\ref{fig:styles}. Notice how different style images for the same category produce different results. Having multiple style images increases appearance variation of our training data.}\label{fig:stylized} \end{figure*} \subsection{Local Feature Model} In this section we briefly discuss learned feature point method that we experimented with. The reader is encouraged to check original papers for R2D2~\cite{r2d2,r2d2_neurips}. R2D2 architecture consists of L2-Net~\cite{l2net} backbone with two heads: last 128-dimensional feature layer divided by $L2$ norm to produce descriptors, and element-wise square of the last 128-dimensional feature layer followed by two separate 1x1 convolutions and softmax to produce a reliability mask and repeatability mask. The neural network is trained on a batch of pairs of 192x192 crops of images, with known warp field between crops that are estimated either from a synthetic homography or 3D reprojection (computed by optical flow with epipolar constraint). The objective is to optimize repeatability and reliability masks of feature points and the associated descriptors. The repeatability loss encourages the repeatability mask to be similar for the pairs of crops, and encourages peakyness of masks: \begin{equation} \mathcal{L}_{rep}(I, I', U) = \mathcal{L}_{cosim}(I, I', U) + \lambda(\mathcal{L}_{peaky}(I) + \mathcal{L}_{peaky}(I')) \end{equation} where both $\mathcal{L}_{rep}$ and $\mathcal{L}_{peaky}$ loss terms are enforced in a $N \times N$ window around each pixel. Hence, varying the value of $N$ changes the predicted repeatability mask, with smaller values of $N$ increasing the total number of detections in an image and larger values of N reducing the total number of detections and encouraging more repeatable points to be detected. Instead of contrastive or triplet loss, R2D2 maximizes the average precision of descriptors in image $I$ that query image $I'$, so that the matching descriptor of image $I'$ is closest among all descriptors of $I'$ in terms of Euclidean distance. Hence, the reliability mask $\mathbf{R}$ and descriptors are optimized jointly as \begin{equation} \mathcal{L}_{AP_\kappa}(i, j) = 1 - \left[ AP(i,j) \mathbf{R}_{ij} + \kappa(1-\mathbf{R}_{ij})\right], \end{equation} where $\kappa=0.5$ is used to encourage the reliability mask to either pay a fixed penalty, or optimize the descriptors for better average precision. In our experiments we found that the training is more stable when we set $\kappa$ as the mean average precision of the batch if the mean average precision is lower than 0.5, \ie $\kappa=min(0.5, 0.5\sum_{i,j} AP(i,j))$. As discussed in section~\ref{sec:intro}, internet images that were used to build a 3D model of a place may have varying appearance. In order to fairly measure the benefits of image stylization, we explicitly describe the training data. At test time, we follow the procedure in R2D2. First, the image is repeatedly downsampled by a factor of $\sqrt[4]{2}$, until the maximum size of the image is 1024. Next, the image is repeatedly processed by the network and downsampled by a factor of $\sqrt[4]{2}$, until both dimensions of the image are less than 256. Non-maximum suppression is applied to the predicted repeatability mask at each scale. Pixel coordinates that have repeatability or reliability scores below 0.7 are removed. Preserved pixel locations across all scales are sorted by detection scores, which is a product of repeatability and reliability scores. A fixed number of top detections are extracted for feature matching. \section{Experiments} In this section we: \begin{enumerate} \item Describe evaluation task used for measuring feature robustness, \item Investigate if image stylization provides better feature robustness than alternative approaches, \end{enumerate} \subsection{Evaluation Task} Our experiments are focused on visual localization task. We found that alternative benchmarks, such as homography estimation~\cite{hpatches_dataset} or Structure-from-Motion reconstructions~\cite{schonberger2017comparative} have limited appearance variation, which makes evaluation of robustness to appearance variations difficult. Visual localization is the task of estimating a camera pose of a query image $Q$ in a pre-captured scene. A database of $N_{d}$ images with known poses is provided, and the algorithm is tested on a set of $N_{q}$ query images that do not overlap with the database images. In this work, we focus on image-retrieval based methods, where for each query we first retrieve top $K=20$ images according to image-retrieval method such as DenseVLAD~\cite{vlad1,vlad2,densevlad} or NetVLAD~\cite{netvlad}, and then compute 2D-2D correspondences using detections and descriptions computed by local feature networks. The pose of the query is solved using COLMAP's bundle adjuster using estimated correspondences and known poses of the database images as the constraint. The estimated pose is compared against ground-truth to compute success rate of localization. Localization attempt for a query is successful if the estimated camera position and camera orientation are both within certain thresholds. The localization success is measured at $(0.25m, 2^\circ)$, $(0.5m, 5^\circ)$, $(5m, 10^\circ)$ translation and rotation thresholds. Feature matching is only one part of a visual localization system, other components such as image retrieval method can have large influence on the localization performance. Indeed, if image retrieval method is not robust to appearance changes, and retrieved images are not from the same part of the scene as the query image, then the localization attempt is bound for failure regardless of the features used to compute the pose. Hence, it is important to account for image retrieval method used for experiments. Unless otherwise specified, we use ``retrievalSfM120k-resnet101-gem'' model of Radenović~\etal~\cite{radenovic1,radenovic2}. Furthermore, the number of features extracted from the query and/or the retrieved images also changes the localization performance. When low number of features is extracted from the images, then both the detector and descriptor need to be robust to appearance changes. However, if a large number of features is extracted, then the effect of the robustness of the detector is diminished, as the robustness of the descriptor becomes more important. \paragraph{Aachen Day-Night v1.0~\cite{aachen1,sattler2018benchmarking}} There are $N_{d}=4328$ database images captured in Aachen, Germany at daytime throughout two years with a hand-held camera. There are $N_{q}=824$ daytime query images and $N_{q}=98$ night-time query images captured with a mobile phone with software HDR. The benchmark measures success for day queries and night queries separately. For night-time only competition, there is a list of image pairs that contain day-day and day-night image pairs, which one needs to compute correspondences for. However, if one is competing in day \emph{and} night tracks simultaneously, then the submission would also need to estimate top $K$ images for each query (if they the localization system is based on a image-retrieval method). Hence, the performance also depends on the method used to retrieve nearest images. \paragraph{Aachen Day-Night v1.1~\cite{aachen11}} This is an updated version of Aachen Day-Night challenge with a larger set of reference images and night-time queries. Specifically, there are $N_{d}=6697$ database images, $N_{q}=824$ daytime query images and $N_{q}=191$ night-time query images captured with a mobile phone. Similarly to v1.0, the day and night queries are measured separately, and there is a separate list of image pairs provided by the benchmark for night-time only evaluation. \paragraph{Extended CMU Seasons~\cite{cmuseasons,sattler2018benchmarking}} Extended CMU Seasons dataset is built on CMU Visual Localization dataset~\cite{cmuseasons} and consists of $N_{d}=60937$ database images captured in Pittsburgh, US over a period of one year with cameras mounted on a car. There are $N_{q}=56613$ query images which consist of multiple sequences traverse by the car. Both database and query images depict urban, suburban and park scenes captured at different seasons. \paragraph{SILDA Weather and Time of Day~\cite{silda}} SILDA benchmark consists of $N_{d}=8334$ and $N_{q}=6064$ images captured on a spherical camera around Imperial College in London over a period of 12 months. The database consists of daytime images captured at clear and rainy weathers. The queries are made under 3 conditions: daytime images during snowy weather (labelled as snow), dusk-time images during clear days (evening) and night-time images during clear days (night). \paragraph{RobotCar Seasons~\cite{robotcar,sattler2018benchmarking}} RobotCar Seasons dataset is a subset of RobotCar dataset~\cite{robotcar} which consists of images captured by cameras mounted on a car, collected over a period of 12 months. There are 49 locations that do not overlap, and multiple capture conditions such as overcast, dawn, dusk, \etc for each location. The overcast footage with $N_{d}=26121$ frames is used as database images. The other conditions with and $N_{q}=11934$ frames are used as queries. When localizing, we know each query's location (out of 49 locations) and so the image retrieval and pose estimation is done using database images corresponding to that location only. \paragraph{RobotCar Seasons v2~\cite{robotcar,sattler2018benchmarking}} RobotCar Seasons v2 dataset extends RobotCar Seasons v1 dataset~\cite{robotcar} by also releasing around half of query images from RobotCar Seasons v1 as database images. The rest of footage is used as query images. \begin{table*}[ht] \resizebox{\textwidth}{!}{ \begin{tabular}{l|cc|cc|ccc} & \multicolumn{2}{c|}{Aachen v1.1~\cite{aachen11}} & \multicolumn{2}{c|}{RobotCar~\cite{robotcar,sattler2018benchmarking}} & \multicolumn{3}{c}{SILDA~\cite{silda}}\\ & day & night & day-overcast & other & evening & snow & night \\ \hline 5k R2D2-WA~\cite{r2d2} & $87.6 / 94.2 / 98.5$ & $61.8 / 79.1 / 91.6$ & $56.4 / 80.5 / 95.2$ & $12.8 / 26.3 / 36.0$ & $31.4 / 64.6 / 83.9$ & $0.2 / 14.6 / 63.2$ & $28.6 / 53.6 / 77.9$ \\ 5k R2D2-WAS~\cite{r2d2} & $88.0 / 94.3 / 98.2$ & $66.0 / 80.1 / 96.3$ & not finished & not finished & $31.7 / 64.2 / 86.9$ & $2.8 / 14.2 / 66.3$ & $29.8 / 53.7 / 77.9$ \\ 5k R2D2-WASF~\cite{r2d2} & $87.5 / 94.4 / 98.9$ & $70.2 / 84.3 / 96.3$ & $56.5 / 80.6 / 95.0$ & $19.1 / 34.3 / 46.1$ & $31.4 / 65.0 / 85.8$ & $1.4 / 15.4 / 63.9$ & $29.8 / 54.0 / 78.4$ \\ \hline\hline 5k R2D2-WAS*F & $88.1 / 94.7 / 98.8$ & $68.1 / 84.3 / 96.9$ & $56.5 / 80.6 / 96.0$ & $20.6 / 40.2 / 52.4$ & $31.8 / 65.9 / 86.6$ & $2.6 / 14.6 / 64.2$ & $30.6 / 53.8 / 78.4$ \\ 5k R2D2-P & $87.9 / 94.7 / 98.5$ & $68.1 / 81.7 / 94.8$ & $56.3 / 80.7 / 95.9$ & $17.5 / 31.9 / 42.4$ & $31.6 / 65.2 / 85.1$ & $0.3 / 12.2 / 64.4$ & $28.7 / 53.4 / 78.4$ \\ 5k R2D2-P-CA & $87.4 / 94.7 / 98.4$ & $66.5 / 83.8 / 95.8$ & $56.3 / 80.5 / 95.3$ & $20.8 / 38.4 / 50.2$ & $31.7 / 65.2 / 84.9$ & $1.0 / 12.7 / 64.4$ & $28.8 / 53.5 / 78.6$ \\ 5k R2D2-P-O2S & $87.9 / 94.5 / 98.3$ & $72.3 / 88.0 / 97.4$ & $56.4 / 80.5 / 94.9$ & $21.6 / 40.2 / 53.0$ & $31.9 / 65.2 / 87.7$ & $2.9 / 14.9 / 67.8$ & $30.5 / 53.8 / 78.8$ \end{tabular} } \caption{Evaluation results for Aachen v.1.1, RobotCar and SILDa localization benchmarks. Scores represent localization success rate of queries for $(0.25m, 2^\circ)$, $(0.5m, 5^\circ)$, $(5m, 10^\circ)$ translation and rotation thresholds.} \label{tab:loc_bench} \end{table*} \begin{table}[ht] \centering \resizebox{0.49\textwidth}{!}{ \begin{tabular}{l|cc|c} & \multicolumn{2}{c}{Aachen v1~\cite{aachen1}} & \multicolumn{1}{c}{Aachen v1~\cite{aachen1}} \\ & day & night & night-only \\ \hline 5k R2D2-WA~\cite{r2d2} & $84.3 / 92.5 / 96.8$ & $67.3 / 78.6 / 83.7$ & $61.2 / 74.5 / 84.7$ \\ 5k R2D2-WAS~\cite{r2d2} & $85.2 / 93.4 / 97.0$ & $72.4 / 81.6 / 92.9$ & $69.4 / 83.7 / 95.9$ \\ 5k R2D2-WASF~\cite{r2d2} & $85.3 / 93.1 / 97.3$ & $71.4 / 82.7 / 92.9$ & $65.3 / 81.6 / 94.9$ \\ \hline 5k R2D2-WAS*F & $85.9 / 93.7 / 97.5$ & $72.4 / 87.8 / 94.9$ & $73.5 / 85.7 / 100.0$ \\ 5k R2D2-P & $85.0 / 93.1 / 97.1$ & $72.4 / 82.7 / 89.8$ & $66.3 / 76.5 / 84.7$ \\ 5k R2D2-P-CA & $84.5 / 92.5 / 96.8$ & $75.5 / 83.7 / 91.8$ & $67.3 / 79.6 / 92.9$ \\ 5k R2D2-P-O2S & $84.7 / 92.8 / 96.8$ & $76.5 / 87.8 / 95.9$ & $73.5 / 85.7 / 99.0$ \end{tabular} } \caption{Evaluation results for Aachen Day-Night v.1 localization benchmark. We use image-retrieval based method to evaluate day and night queries. We also show evaluation with night queries only, using provided list of image pairs. Scores represent localization success rate of queries for $(0.25m, 2^\circ)$, $(0.5m, 5^\circ)$, $(5m, 10^\circ)$ translation and rotation thresholds.} \label{tab:loc_bench2} \end{table} \subsection{Investigation of Appearance Augmentations} In this section we compare image stylization to appearance augmentation strategies used in the literature: color augmentation~\cite{albumentations}, night style transfer in R2D2~\cite{r2d2} and multiple style transfers described in section~\ref{sec:method}. In this section compare trained models on Aachen v1.1, RobotCar Seasons v1 and SILDa benchmarks. For all 3 methods we use Radenovic~\etal~\cite{radenovic1,radenovic2} to extract top $K=20$ nearest neighbors for each query for feature matching. We extract 5000 keypoints from query and retrieved images in these experiments. Next, we describe models that we used for comparison. First, we used three baseline models of R2D2 (N=16). R2D2 uses three types of images: random web images (W), day images from Aachen dataset (A), and night stylization to Aachen dataset day images (S). So, \textbf{R2D2-WA} and \textbf{R2D2-WAS} are trained with synthetic homographies and color augmentations from corresponding image sets. Finally, \textbf{R2D2-WASF} also uses optical flow between day images of Aachen dataset on top of \textbf{R2D2-WAS} training data. The total number of image pairs used to train \textbf{R2D2-WAS} and \textbf{R2D2-WASF} models is 3636. R2D2-WA, R2D2-WAS and R2D2-WASF models were trained for 25 epochs with a fixed learning rate. Next, we describe models trained by us: \textbf{R2D2-WAS*F} is trained using 6 styles described in section~\ref{sec:method} to stylize Aachen day images to different style categories (see Figure~\ref{fig:stylized}), while web images only have color augmentation. The optical flow correspondences are used only between Aachen day and day images similar to R2D2-WASF. For each training epoch we randomly sample for the pool of stylized image so that the total number of batches in each epoch is the same as used to train R2D2-WASF model. \textbf{R2D2-P}, \textbf{R2D2-P-CA}, and \textbf{R2D2-P-O2S} models are trained on images from Phototourism dataset, where we randomly sample 300 images from each scene of the training set to produce a set of 3900 images. \textbf{R2D2-P} is trained on these 3900 images and synthetic homographies without color augmentation. \textbf{R2D2-P-CA} is trained using synthetic homographies with color augmentation. For color augmentation we use Albumentations~\cite{albumentations} library to generate random color transforms of training images. \textbf{R2D2-P-O2S} is trained on images from Phototourism dataset and synthetic homographies with image stylization and color augmentation as described in section~\ref{sec:method}. For each training epoch we randomly sample one stylized image out of 60 available for each original image. So, each training epoch consists of 3900 pairs, which is only slightly more than 3636 used by baseline models. R2D2-WAS*F, R2D2-P, R2D2-P-CA, and R2D2-P-O2S were trained for 70 epochs with exponentially decaying learning rate with warm-up of 5 epochs. We evaluated these models on Aachen v1.1, RobotCar and SILDa benchmarks in table~\ref{tab:loc_bench}. We also show evaluation results for Aachen v1 in table~\ref{tab:loc_bench2}. First, we can see that color augmentation is important, especially for RobotCar dataset, by comparing scores of R2D2-P and R2D2-P-CA. If we compare R2D2-WA and R2D2-P-CA, we can see that Phototourism images and more aggressive color augmentation strategies help, especially for RobotCar and night queries of Aachen v1 and Aachen v1.1 benchmarks. One could hypothesize that Phototourism images are more varied than WA images, and may be some of the scenes are more similar to RobotCar images than W or A images. However, it is surprising that we can outperform R2D2-WA model with R2D2-P-CA model on Aachen challenges, especially when R2D2-WA has seen Aachen day images while R2D2-P-CA model has not seen them. This result suggests that tuning color augmentation during training is more important than images used for training. There is, however, a slight score reduction of R2D2-P-CA compared to R2D2-WA for one of thresholds of snow queries of SILDa, but this is a very challenging category for all models. It is clear that image stylization in addition to color augmentation is beneficial for localization when comparing R2D2-WA vs R2D2-WAS scores or R2D2-P-CA vs R2D2-P-O2S scores. The improvements are consistent and significant, especially for non-day queries in all benchmarks. Next, we can see that stylizing images with multiple style categories and multiple style examples is very beneficial. Indeed, when comparing R2D2-WASF and R2D2-WAS*F the performance on Aachen v1.1 and SILDA datasets is comparable, but we get significant improvements in RobotCar dataset and night queries of Aachen v1 datasets. Finally, we can see that when training with synthetic homographies and multiple style categories we can train R2D2-P-O2S model that is generally more competitive then R2D2-WASF model in the localization benchmarks. Note the difference in scores in Aachen v1, Aachen v1.1, RobotCar datasets. This is significant in two ways. First, it means that we can train feature networks for localization task without SfM reconstructions. So, a feature network trained on raw images could potentially be used in an SfM pipeline to produce a 3D model with higher appearance coverage. Second, it suggests that for localization tasks, the 3D occlusion effects are not as significant as appearance variations. \section{Challenges} \subsection{Long-Term Visual Localization at ECCV 2020} The challenge focuses on visual localization in 3 conditions/tracks: \begin{enumerate} \item Visual Localization for Autonomous Vehicles: where localization systems submitted to the competition are evaluated on Extended CMU Seasons, RobotCar Seasons v2, and SILDa Weather and Time of Day datasets. \item Visual Localization for Handheld Devices: Aachen Day-Night v1.1 and InLoc~\cite{inloc,inloc2} datasets are used for evaluation of submissions. \item Local Features for Long-term Localization: the submissions are evaluated using night-time queries of Aachen Day-Night v1.1 benchmark using provided image pairs. \end{enumerate} In each track, the submissions are evaluated on listed datasets for all 3 thresholds. The ranking of localization systems is determined with Schulze method. Our submission uses R2D2 features trained on images from Phototourism dataset~\cite{imw_challenge} using synthetic homographies and image stylization (original to stylized). Except for ``Local Features for Long-term Localization'' track which provides image pairs, we use image-retrieval based localization method. So, for each query image, top $K=20$ images are retrieved from the database using Radenovic~\etal~\cite{radenovic1,radenovic2}. We extract 10000 features from images for ``Local Features for Long-term Localization'' challenge and 5000 for other challenges (both query and retrieved images) . See tables~\ref{tab:ltvl:auto},~\ref{tab:ltvl:hand}, and~\ref{tab:ltvl:local} for scores in each of the tracks, respectively. We note that we only used a single query image for localization in ``Autonomous Vehicles'' track, while the benchmark allows to localize from multiple frames. For example, in SILDa dataset the query image is one of the two spherical images of the camera rig, which means that the camera pose of the query image can be estimated by querying the database using opposite view of the camera rig. \begin{table*}[ht] \resizebox{\textwidth}{!}{ \begin{tabular}{l|ccc|cc|ccc} & \multicolumn{3}{c|}{Extended CMU Seasons~\cite{cmuseasons,sattler2018benchmarking}} & \multicolumn{2}{c|}{RobotCar Seasons v2~\cite{robotcar,sattler2018benchmarking}} & \multicolumn{3}{c}{SILDA~\cite{silda}}\\ & urban & suburban & park & day all & night all & evening & snow & night \\ \hline 5k R2D2-P-O2S & $93.8 / 96.6 / 98.2$ & $83.5 / 86.8 / 90.5$ & $76.4 / 80.9 / 85.7$ & $0.0 / 0.0 / 0.0$ & $0.0 / 0.0 / 0.0$ & $31.9 / 65.2 / 87.7$ & $2.9 / 14.9 / 67.8$ & $30.5 / 53.8 / 78.8$ \\ \end{tabular} } \caption{Scores in ECCV 2020 Long-Term Visual Localization for Autonomous Vehicles challenge.} \label{tab:ltvl:auto} \end{table*} \begin{table*}[ht] \centering \resizebox{0.7\textwidth}{!}{ \begin{tabular}{l|cc|cc} & \multicolumn{2}{c|}{Aachen v1.1~\cite{aachen11}} & \multicolumn{2}{c}{InLoc~\cite{inloc,inloc2}} \\ & day & night & duc1 & duc2 \\ \hline 5k R2D2-P-O2S & $87.1 / 94.7 / 98.3$ & $74.3 / 86.9 / 97.4$ & $39.4 / 58.1 / 70.2$ & $41.2 / 61.1 / 69.5$ \\ \end{tabular} } \caption{Scores in ECCV 2020 Long-Term Visual Localization for Handheld Devices challenge.} \label{tab:ltvl:hand} \end{table*} \begin{table}[ht] \centering \begin{tabular}{l|c} & \multicolumn{1}{c}{Aachen v1.1~\cite{aachen11}} \\ & night \\ \hline 10k R2D2-P-O2S & $69.6 / 86.9 / 97.9$ \\ \end{tabular} \caption{Scores in ECCV 2020 Long-Term Visual Localization Local feature challenge.} \label{tab:ltvl:local} \end{table} \subsection{Map-based Localization for Autonomous Driving} This challenge also evaluates a localization system, where the task is to estimate 6 degrees of freedom relative pose between queries and database images. The images are collected using car-mounted grayscale stereo camera. The database images are stereo video frames from one continuous sequence captured on the 7-th of April 2020 around 10:20. The query images are frames from two sequences captured on the 24-th of March around 17:45 and 23-rd of April around 19:37. Hence, robustness to illumination change and weather change is important for this challenge. Please see Figure~\ref{fig:mlad} for examples. The evaluation measures localization success rate, \ie the percentage of queries where the translation error between the estimated and ground-truth poses is within a threshold. The accuracy is measured at 0.1m, 0.2m, and 0.5m thresholds. The list of image pairs for estimating correspondences is provided by the benchmark. \begin{figure*}[ht] \centering \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/ref/1586247632337008896.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test0/1585068331627779840.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test1/1587663420788365312.png} \end{minipage} \centering \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/ref/1586247658638071040.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test0/1585068400564946176.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test1/1587663460256458240.png} \end{minipage} \centering \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/ref/1586247913662674944.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test0/1585068407824963840.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test1/1587663480815506688.png} \end{minipage} \centering \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/ref/1586248007646897152.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test0/1585068475574127616.png} \end{minipage} \begin{minipage}{.3\textwidth} \centering \includegraphics[width=0.99\textwidth]{figures/mlad/test1/1587663505994566144.png} \end{minipage} \vspace{2pt} \centering \begin{minipage}{.3\textwidth} \centering (a) Reference \end{minipage} \begin{minipage}{.3\textwidth} \centering (b) test\_sequence0 \end{minipage} \begin{minipage}{.3\textwidth} \centering (c) test\_sequence1 \end{minipage} \caption{Random sample of reference and query images of MLAD challenge. The images show significant illumination variations, hard shadows, specularities and lense flares.} \label{fig:mlad} \end{figure*} Our scores together with baseline scores of competing method can be seen in table~\ref{tab:mlad}. Notice how additional stylization augmentation during training noticeably improves scores for `test\_sequence1', which is more challenging than `test\_sequence0'. \begin{table*}[ht] \centering \begin{tabular}{l|c|c} & test\_sequence0 & test\_sequence1 \\ \hline Superpoint & $15.5 / 27.5 / 47.5$ & $9.0 / 19.4 / 36.4$ \\ Superpoint + SuperGlue & $21.2 / 33.9 / 60.0$ & $12.4 / 26.5 / 54.4$ \\ D2-Net & $12.5 / 29.3 / 56.7$ & $7.5 / 21.4 / 47.7$ \\ 5k R2D2-WASF N=16 & $21.5 / 33.1 / 53.0$ & $12.3 / 23.7 / 42.0$ \\ \hline 5k R2D2-P-O2S N=16 & $20.9 / 33.2 / 54.8$ & $13.2 / 25.3 / 45.7$ \\ 10k R2D2-P-O2S N=8 & $22.3 / 34.1 / 57.4$ & $13.2 / 26.0 / 47.8$ \\ \end{tabular} \caption{Scores in Map-based Localization for Autonomous Driving challenge.} \label{tab:mlad} \end{table*} \section{Conclusion} In this work we investigate if image stylization can improve robustness of local features to illumination, weather and season changes. We experimented with multiple appearance augmentation techniques and demonstrated better robustness when augmentation with image stylization is used during training. We also show that stylizing images with multiple styles and style examples is better than stylizing with a few examples. Our models are competitive in visual localization benchmarks, outperforming baseline models, despite training without 3D correspondences. Our experiments were done with R2D2 model, but in future versions of this paper we plan to extended experiments by evaluate other local feature networks, such as D2-Net~\cite{d2net} and Superpoint~\cite{superpoint}, when trained with stylized images. % {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-08-18T02:19:11', 'yymm': '2008', 'arxiv_id': '2008.06959', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06959'}
arxiv
\section{Introduction} Many news articles in recent years have criticized face recognition as being ``biased'', ``sexist'' or ``racist'' \cite{Lohr2018,Hoggins2019,Doctorow2019,Santow2020}. Various papers summarized in Related Work have reported that face recognition is less accurate for females. Accuracy also varies between racial groups, and age ranges, but this paper focuses on the female / male difference. Surprisingly, given the media attention on the issue, the underlying cause(s) of lower accuracy for females are heretofore unknown. The popularity of deep CNN algorithms perhaps naturally gives rise to the common speculation that the cause is female under-representation in the training data. But recent studies show that simply using a gender-balanced training set does not result in balanced accuracy on test data \cite{Albiero2020_train, Albiero2020_gender}. This paper is the first to present experimental results that explain the causes of lower face recognition accuracy for females, on datasets where this result is observed in previous research. To promote reproducible and transparent results, we use a state-of-the-art deep CNN matcher and datasets that are available to other researchers. Our experiments show that gendered hairstyles result in, on average, more of the face being occluded for females, and that the inherent variability between different female faces is lower. \section{Related Work} \label{sec:related_work} Drozdowski et al. \cite{Drozdowski2020} give a current, broad survey on demographic bias in biometrics. Here we focus on selected prior works dealing specifically with female / male accuracy difference. The earliest work we are aware of to report lower accuracy for females is the 2002 Face Recognition Vendor Test (FRVT) \cite{frvt}. Evaluating ten algorithms of that era, identification rates of the top systems are 6\% to 9\% higher for males. However, for the highest-accuracy matcher, accuracy was essentially the same. In a 2009 meta-analysis of results from eight prior papers, Lui et al. \cite{Lui2009} concluded that there was a weak pattern of lower accuracy for females, and noted interactions with factors such as age, expression, lighting and indoor/outdoor imaging. Beveridge et al. \cite{Beveridge2009} analyzed results for three algorithms on a Face Recognition Grand Challenge \cite{frgc} dataset, and found that males had a higher verification rate for the two higher-accuracy algorithms and females had a higher verification rate for the third, lower-accuracy algorithm. Klare et al \cite{Klare2012} presented results from three commercial off-the-shelf (COTS) and three research algorithms showing that females had a worse receiver operating characteristic (ROC) curve for all six, and also showed example results for which females had both a worse impostor distribution and a worse genuine distribution. The above works are from before the deep convolutional neural network (CNN) wave in face recognition. Related works since the rise of deep CNN matchers report similar results. Cook et al. \cite{cook2018} analyze images acquired using eleven different automated kiosks with the same COTS matcher, and report that genuine scores are lower for females. Lu et al. \cite{Lu2018} use deep CNN matchers and datasets from the IARPA Janus program in a detailed study of the effect of various covariates, and report that accuracy is lower for females. Howard et al. \cite{bio_rally} report higher false match rates for African-American and Caucasian females under age 40. For subjects over 40, African-American females again had a higher false match rate, but Caucasian females had a lower false match rate than Caucasian males. However, the dataset is the smallest of the recent papers on this topic, with just 363 subjects, divided into 8 subsets for this analysis. Vera-Rodriguez et al. \cite{Vera-Rodriguez2019} use a Resnet-50 and a VGGFace matcher with the VGGFace2 dataset \cite{vggface2}, and report that females have a worse ROC for both. Albiero et al. \cite{Albiero2020_gender} use the ArcFace matcher with four datasets, and report that the general pattern of results is that females have a worse ROC curve, impostor distribution and genuine distribution. Similarly, Krishnapriya et al. \cite{KrishnapriyaTTS} show that both the ArcFace and the VGGFace2 matcher, which are trained on different datasets and with different loss functions, result in a worse ROC curve, impostor distribution and genuine distribution for females, for both African-American and Caucasian image cohorts. Grother et al. \cite{frvt3}, in the 2019 FRVT focused on demographic analysis, found that females have higher false match rates (worse impostor distribution), and that the phenomenon is consistent across a wide range of different matchers and datasets. Relative to the genuine distribution, they report that women often have higher false negative error rates, but also note that there are exceptions to this generalization. The general pattern across these works, for a broad variety of matchers and datasets, is that face recognition accuracy is lower for females, with females having a worse impostor distribution and a worse genuine distribution. Several researchers have speculated cosmetics use as a cause of the gender gap in accuracy \cite{Klare2012, cook2018, Lu2018}. Dantcheva et al. \cite{can_facial_cosmetics} and others have documented how the use of cosmetics can degrade face recognition accuracy. In scenarios where females have substantial cosmetics use and males do not, this is a possible cause of the accuracy gender gap. However, Albiero et al \cite{Albiero2020_gender} showed that cosmetics plays at most a minor role in the MORPH dataset, which is the main dataset also used in this paper. Other speculated causes include more varied hairstyles for females \cite{Albiero2020_gender} and shorter height for women, leading to non-optimal camera angle \cite{Grother2010, cook2018}. Buolamwini and Gebru \cite{gendershades}, Muthukumar et al. \cite{Muthukumar} and others have looked at the accuracy of algorithms that predict gender from a face image, and found lower accuracy for females. Gender classification of a face image is a related problem but distinct from face recognition. Very few works attempt to identify the cause(s) of the accuracy gender gap. For example, the recent NIST report on demographic effects \cite{frvt3} lists ``analyze cause and effect’’ as an item under ``what we did not do’’. However, Albiero et al. \cite{Albiero2020_gender} reported on experiments to determine if cosmetics use, facial expression, forehead occlusion by hair, or downward-looking camera angle could explain the worse impostor and genuine distributions observed for females. They found that these factors, either individually or together, did not significantly impact the gender gap in accuracy. A popular speculation is that accuracy is lower for females because they are under-represented in the training data. Albiero et al. \cite{Albiero2020_train} trained matchers from scratch using male / female ratios of 0/100, 25/75, 50/50, 75/25 and 100/0. They found that explicitly gender-balanced training data does not result in balanced accuracy on test data, and that in fact a 25\% male / 75\% female training set resulted in the least-imbalanced test accuracy, but was generally not the training mix that maximized female, male, or average accuracy. \input{figures/original_dists} \section{Lower Recognition Accuracy For Females} The results in Figure \ref{fig:auth_imp} are representative of the consensus across many different matchers and datasets as covered in the Related Work. Note that the female impostor distribution ranges over higher similarity scores, indicating a higher false match rate (FMR), and also that the female genuine distribution ranges over lower similarity scores, indicating a higher false non-match rate (FNMR). The MORPH dataset \cite{MORPH, MORPH_site} was originally collected to support research in face aging, and has been widely used in that context. In the last few years, it has also been used in the study of demographic variation in accuracy \cite{KrishnapriyaTTS, Albiero2020_train, Albiero2020_gender, albiero2019does, krishnapria_cvprw_2019}. MORPH contains mugshot-style images that are nominally frontal pose, neutral expression and acquired with controlled lighting and an 18\% gray background. We curated the MORPH 3 dataset in order to remove duplicate images, twins, and mislabeled images. The results in Figure \ref{fig:auth_imp} are for a subset of MORPH 3 that contains: 35,276 images of 8,835 Caucasian males, 10,941 images of 2,798 Caucasian females, 56,245 images of 8,839 African-American males, and 24,857 images of 5,929 African-American females. The Notre Dame dataset is a subset of the Face Recognition Grand Challenge dataset \cite{frgc}, made available by the authors of a recent work in this area \cite{Albiero2020_gender}. It contains frontal images, higher resolution than MORPH, with uniform background, for 261 Caucasian males (14,345 images) and 169 Caucasian females (10,021 images). Thus the number of subjects is an order-of-magnitude smaller than MORPH, and subjects have more images on average. ArcFace \cite{arcface} is a state-of-the-art deep CNN matcher. The instance of ArcFace used here corresponds to a set of publicly-available weights \cite{insightface}, trained on the MS1MV2 dataset, which is a publicly-available, ``cleaned'' version of MS1M \cite{ms1_celeb}. We estimate that MS1MV2 is about 73\% male / 27\% female in number of subjects and 67\% male / 33\% female in number of images \cite{Albiero2020_train}. There should be zero overlap of subjects between MS1MV2 and the datasets generating the results in Figure \ref{fig:auth_imp}. The lower accuracy for females can be quantified in terms of the separation between the female and male impostor and genuine distributions. The cross-gender and same-gender d-prime values are shown in Table \ref{tab:d_prime}. For all three datasets, the female impostor distribution is shifted toward higher similarity scores than the male impostor distribution, the female impostor distribution is shifted toward lower similarity scores, with the result that the impostor-to-genuine separation is lower for females. \section{Less ``Pixels On the Face'' In Female Face Images} \input{figures/samples} \input{figures/d_prime} \input{figures/heatmap} This section considers the face images that are input to the deep CNN, the fraction of the image that represents ``pixels on the face'', and how this differs between female and male. The faces in the MORPH and Notre Dame images are detected and aligned using RetinaFace \cite{retinaface}. This results in the 112x112 image with face centered in standard location that is the input to the deep CNN. Examples are shown in Figure \ref{fig:mean_faces}. To obtain a binary mask that indicates which pixels represent face and which do not, we use the modified Bilateral Segmentation Network (``BiSeNet'') to segment the faces (\cite{bisenet}, implementation at \cite{bisenet_github}). A pre-trained version of BiSeNet segments face images into regions. For our purposes, ``face'' is the union of BiSeNet regions 1 to 13, corresponding to skin, eyebrows, eyes, ears, nose and mouth. BiSeNet regions corresponding to neck, clothes, hair and hat are excluded. Examples of the face/non-face masks are shown in Figure \ref{fig:mean_faces}. These masks are used to compute heatmaps for face being visible at each pixel, for female and male images. The value of each heatmap pixel is from 0 to 1, reflecting the fraction of the female (male) face images for which that pixel is labelled as face. Figure \ref{fig:heatmap} shows the female and male heatmaps and the difference between them. The chin in the male heatmap extends slightly further toward the bottom. This reflects the ``biology'' of females and males having, on average, different head size / shape. Another difference is that the ear region and the sides of the face are less prominent in the female heatmap. This reflects gender-associated hairstyles, where female hairstyles more frequently occlude the ears and part of the sides of the face. The difference heatmaps summarize all of this, with blue representing pixels that more frequently labeled face for males than for females, and red representing the opposite. The heatmaps make it clear that, {\it on average, female face images contain fewer ``pixels on the face'' than male face images, and that gendered hairstyles are a major underlying cause.} A different view of this information is the distribution of the fraction of the image that represents the face. The ``\% face'' distributions compared in Figure \ref{fig:skin_dist} show that the proportion of female face images is larger in the range of approximately 25\% to 45\%, and the proportion of male face images is larger in the range of about 45\% to 70\%. Again it is clear that, on average, the female face images contain less information about the face. Note the correlation of the difference in the \% face distributions in Figure \ref{fig:skin_dist} and the difference in the genuine distributions in Figure \ref{fig:auth_imp}. The most pronounced difference in the \% face distributions is for MORPH African-American, which also has the most pronounced difference in genuine distributions. The most similar \% face distributions are for Notre Dame Caucasian, which also has the most similar genuine distributions. \input{figures/skin_dist} \section{Equal Face Info Flips Genuine Distribution Difference} The previous section shows that the observation that face recognition accuracy is lower for females is based on images in which the female face images contain less information about the face. Given this, it is natural to ask what happens if the dataset is controlled to have equal information in female and male face images. We created a version of the dataset designed to minimize the difference in information between the female and male face images. First, we masked the area outside of the 10\% level in the female heatmap, in all female and male images. Because the female face region is generally a subset of the male, this establishes the same maximum set of pixels containing face information in all images, and preserves a large majority of the available face information. However, this still leaves a bias of greater information content for male images because, as the comparison heatmap shows, any given pixel is generally labeled as face for a higher fraction of the male images than the female images. Therefore, as a second step, for each female image, we selected the male image that had the maximum intersection-over-union (IoU) of pixels labeled as face in the two images. The difference heatmap for this nearly info-equalized set of images, and the resulting impostor and genuine distributions, are shown in Figure \ref{fig:equalized_images}. These results are for a set of 4,730 Caucasian female images (2,095 subjects) and 4,730 Caucasian male images (2,799 subjects), and 12,383 African-American female images (4,656 subjects) and 12,383 African-American male images (5,414 subjects) for MORPH, and 2,442 Caucasian female images (160 subjects) and 2,442 Caucasian male images (238 subjects) for Notre Dame. The difference heatmaps show that the difference in information between female and male images is effectively minimized. Remaining differences at any pixel are generally less than 5\% and are roughly balanced between female and male. The impostor and genuine distributions for the information-equalized images show a fundamental change from those for the original dataset. While the impostor distribution for females is still worse than for males, {\it the genuine distribution for females is now the same as, or slightly better than, the genuine distribution for males.} \input{figures/equalized_images} Note that this change in the comparison of the female and male genuine distributions occurs solely from creating an approximately information-equalized test set. The matching algorithm is the same, and was trained on the MS1MV2 dataset which has known female under-representation. This suggests that the result that females have a worse genuine distribution was, in effect, based on bias in the test data rather than bias in the training data. \section{Impostor Difference Reflects Between-Subject Variation} \label{sec:unequal} The information-equalized dataset shows that females have a genuine distribution as good or better than males, but the impostor distribution for females is still worse. To explore how and why this can be the case, we employ a concept that was once ubiquitous in face recognition, but that may be less known to those entering the field since the wave of deep CNNs - ``eigenfaces'' based on principal component analysis (PCA) \cite{Turk1991, Turk2001}. The essence of eigenfaces is to learn, from a set of training images, a face space that accounts for the most variation possible in a linear combination of orthogonal dimensions. While eigenfaces have been used for gender classification (e.g., \cite{Valentin1997}), we are not aware of any previous comparison of the dimensionality of face spaces computed separately for females and males. We computed the face space separately for females and for males, using one image with the highest fraction of pixels labeled as face for each person, with skin pixels outside of a 10\% mask zeroed. For simplicity of comparison, we randomly selected the same number of males as there are females. This resulted in 2,798 images each for MORPH Caucasian females and males, 5,929 images each for MORPH African-American females and males, and 169 images each for Notre Dame Caucasian. \input{figures/pca_eigenfaces} Figure \ref{fig:eigenfaces} compares the face space for females and males in terms of the percent of variation accounted for by a given number of eigenfaces. For MORPH Caucasian, females need 187 eigenfaces to capture 95\% of variation, whereas males need 222 eigenfaces. Thus, 95\% of the variation in face images of different persons is captured in a face space of about 10\% lower dimension for females than for males. For MORPH African-American, females need 229 eigenfaces to capture 95\% of the variation, whereas African-American males need 287 eigenfaces. In this case, 95\% of the variation in face images between different persons is captured in a face space of about 20\% lower dimension for females. For Notre Dame Caucasian, the result is different, as females require more eigenfaces than males, 82 to 80. The reason for this difference is not immediately obvious, but the Notre Dame dataset is different in several respects. One, there are only 169 subjects / images contributing to each face space. Two, the subjects are overwhelming young, with over 90\% of both female and male subjects in the age range 18-29, whereas the large majority of the subjects in the MORPH African-American and MORPH Caucasian are 30 or older. Three, and perhaps related to the small number of subjects almost all of whom are young, a much smaller number of eigenfaces is needed to reach 95\% of variation. The curves in Figure \ref{fig:eigenfaces} are for the central masked face regions. The results are similar if the original 112x112 images are used. For example, for MORPH Caucasian, females need 303 eigenfaces and males need 331 to capture 95\% of variance. Overall, the implication of this face space analysis is that, for a given dimension of face space, images of two different females are more similar than images of two different males. To determine if the size of the Notre Dame dataset is the problem, we create male and female subsets of MORPH Caucasian images, with same number of subjects and same age distribution as the Notre Dame dataset. Figure \ref{fig:morph_c_match_nd_pca} shows that when this subset of MORPH data is used, the result is similar to the Notre Dame dataset. \input{figures/morph_c_match_nd_pca} \section{Face Spaces and Impostor Distributions} The previous section shows that, for the same number of subjects and images, the male image set requires a larger dimension of face space than the female image set to account for the same percent variation. For the same dimensionality of face space, a greater percent of the variation in female face appearance is accounted for. In face space, faces of two different females are more similar-appearing on average than faces of two different males. We conjecture that this is an explanation for why the male impostor distribution is centered at a lower similarity value than the female impostor distribution. \input{figures/pca_removal} To investigate this further, we select a subset of male face images that generates a face space that better matches that of the female image set. We select the same number of males as there are females, and use one image per person, and we select the male images that have the lowest reconstruction error at 80\% variance. This selection flipped the relative position of the female and male PCA curves as seen in Figure \ref{fig:pca_removal}. We then compare the impostor distribution of the males random selection and the 80\% variance selection. Figure \ref{fig:pca_removal} shows that the impostor distribution for males and females is closer when the PCA curve is flipped, meaning that when males have less variation in between-subject, their impostor matches are similar to women. We were able to reproduce the PCA inverting experiment with the MORPH Caucasian and Notre Dame dataset, but not on MORPH African-American. The original difference in the PCA between African-American males and females is larger than the other two datasets, and when we remove male images with highest error rate, females still require less components to achieve the same variation. This issue exists even if we reduce womens' data to half, so that we can have more male data to remove, achieving a much closer PCA curve, but that does not flip and does not come as close as the MORPH Caucasian and Notre Dame dataset do. In our experiments, to achieve a more similar impostor distribution across gender, the males' PCA curve must be higher (require less components) than the females, if they are near-equal, male impostor distribution is still better. \section{Conclusions and Discussion} The results in Figure \ref{fig:auth_imp} are representative of the consensus of previous research that face recognition accuracy is lower for females. The most extensive study in this area, in terms of number of different matchers and datasets considered, is the recent NIST report on demographic effects \cite{frvt3}. This report found that females consistently have higher FMR (worse impostor distribution), and generally also have higher FNMR (worse genuine distribution) but that there are exceptions to the higher FNMR generalization. However, the studies covered in Related Work are done with test sets that are largely uncontrolled with respect to differences between female and male images. One recommendation for future studies on demographic differences in face recognition accuracy is to include information such as the \% face distributions or the face difference heatmap for the test images. This would encourage an awareness of how test data may come with a built-in ``bias'' toward observing certain accuracy differences. Female / male differences in size and shape of the face are well known and have long been studied in diverse fields such as ergonomics \cite{Zhuang2010}, anthropology \cite{Holton2014}, and surgery \cite{Farkas2005}. Female and male faces also change differently with age \cite{Albert2007}. As a matter of biology, the range of size and shape of the female face is smaller than the range of size and shape of the male face. In the face recognition context, this becomes evident in an eigenface comparison of the female and male ``face spaces''. Thus, an initial condition for face matchers is the fact that, on average, two different female faces actually do appear more similar than two different male faces. The impostor distribution for females is naturally centered at higher similarity values that the impostor distribution for males. Any face matching algorithm that computes a similarity score without, in effect, classifying the face as female or male and allowing that to influence the score, seems likely to have different female / male impostor distributions. The range of face size and shape being smaller for females can also cause the distribution of genuine scores for females to be centered at higher similarity values than for males. This is the result seen for the information-equalized dataset in Figure \ref{fig:equalized_images}. The fact that the opposite is commonly found in female / male comparisons of accuracy, with the female genuine distribution worse than the male, is due to effects of gendered hairstyles combined with biological differences in face size and shape. Most of the difference in the \% face distributions in Figure \ref{fig:skin_dist} is due to the effects of gendered hairstyles. Is face recognition technology sexist? The worse genuine distribution seems due primarily to the gender differences in hairstyles. The worse impostor distribution seems due primarily to the biological differences in the range of female and male face appearance. So, the ``sexist'' result of lower accuracy for females seems largely due to a combination of biological differences and gendered hairstyle conventions, and not to face recognition methods and training datasets. Future work could include analyzing the female/male difference for an Asian image cohort, or other cohorts. \section*{Acknowledgment} The authors would like to thank Ross Beveridge, Alice O'Toole and Volker Blanz for helpful discussions on this project.
{'timestamp': '2020-08-18T02:20:27', 'yymm': '2008', 'arxiv_id': '2008.06989', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06989'}
arxiv
\section{Introduction} Machine learning has shown superiority over humans for tasks like image recognition, speech recognition, security-critical applications like a bot, malware or spam detection. However. machine learning has been proven to be susceptible to carefully crafted adversarial examples. In recent years, research on the generation and development of defenses against such adversarial examples has been on the rise. These adversarial examples help to make the models more robust by highlighting the gap between sensory information processing in humans and the decisions made by machines. Attack algorithms have been formulated for image classification problems by \cite{carlini2017magnet}, \cite{Goodfellow2014} . A classic example of an adversarial attack is that of a self-driving car crashing into another car because it ignores the stop sign. The stop sign being an adversarial example that an adversary intentionally replaced for the original stop sign. An example in the textual domain can be that of a spam detector that fails to detect a spam email. The spam email is an example of an adversarial attack in which the attacker has intentionally changed a few words or characters to deceive the spam detector. \par The attacks can be broadly classified based on the amount of information available to the attacker as black-box or white-box attacks. White box attacks are those in which the attacker has full information about the model’s architecture, model weights, and the examples it has trained. Black-box attacks refer to those attacks in which only the final output of the model is accessible to the attacker. Black-box attacks can be further classified into 3 types based. The first type involves those attacks in which the probability scores to the outputs are accessible to the attacker referred to as the ’score-based black-box attacks’. The second type of attack involves the case where information of the training data is known to the attacker. The third attack type is the one in which only the final decision of the classifier is accessible by the attacker, with no access to the confidence scores of the various classes. We shall refer to the third type of attack as the Hard Label Black-Box attack.\par In the NLP domain, researchers have mainly formulated attacks in the white box setting\cite{ebrahimi2017hotflip},\cite{li2018textbugger} with complete knowledge of gradients or the black-box setting with confidence scores accessible to the attacker\cite{gao2018black},\cite{li2018textbugger},\cite{alzantot2018generating},\cite{jin2019bert}. As per our knowledge, there has been no prior work done to formulate adversarial attacks against NLP classifiers in the hard label black-box setting. We emphasize hard label black-box attacks to be an important category of attacks much relevant to the real-world applications as the confidence scores can easily be hidden to avoid easy attacks.\par Adversarial attacks on Natural Language models have to fulfill certain rules to qualify them as a successful attack: (1) Semantic Similarity- meaning of the crafted example should be the same as that of the original text, as judged by humans (2) Syntactic correctness: The crafted examples should be grammatically correct (3) Language Fluency: The generated example should look natural. \cite{jin2019bert} proposed TextFooler which aimed at preserving these three properties while generating adversarial examples. \par We focus on the text classification task which is used for sentiment analysis, spam detection, topic modeling. Sentiment analysis is widely used in the online recommendation systems, where the reviews/comments are classified into a set of categories that are useful while ranking products or movies \cite{medhat2014sentiment}. Text classification is also used in applications critical for online safety like online toxic content detection \cite{nobata2016abusive}. Such applications involve classifying the comments or reviews into categories like irony, sarcasm, harassment, and abusive content. \par Adversarial attacks on text classifiers consist of two main steps. First, identifying the important words in the text. Second, introducing perturbations in those words. For finding the important words, gradients are used in the white box setting and confidence scores in the black-box setting. In the absence of gradients or confidence scores in the hard-label black-box setting, it is non-trivial to locate important words. In the second step, there can be either character level perturbation, like, introducing space, replacements with visually similar characters, or word level perturbation by replacement of the word with its synonym. The selection of a character-level perturbation or synonym for replacement is based on the decrease in confidence value of the original class on introducing the perturbation. In the absence of confidence scores, there are no direct indicators to help select any type of perturbation unless the replacement of any single word leads to misclassification of the entire text, which is not always the case. \par In our work, we come up with heuristics to help determine the important sentences and words in the first step and, select appropriate perturbation in the second step. The heuristics help us select a synonym for a replacement for each of the important words, in such a way that with each successive replacement we move towards the decision boundary. Our main contributions are as follows: \begin{enumerate} \item We propose a novel approach to formulate natural adversarial examples against NLP classifiers in the hard label black-box setting. \item We test our attack algorithm on three state-of-the-art classification models over two popular text classification tasks. \item We improve upon the grammatical correctness of the generated adversarial examples. \item We also decrease the memory requirement for the attack as compared to published attack systems involving word-level perturbations. \end{enumerate} \section{Attack Design} \subsection{Problem Formulation} Given an input text space $X$ and a set of $n$ labels , $Y = \{Y_1, Y_2, ..., Y_n\}$, we have a text classification model $F: X \rightarrow Y $ which maps from the input space $X$ to the set of labels $Y$. Let there be a text $x \in X$ which is correctly predicted by the model to be belonging to the class $y \in Y$ i.e. $F(x) = y$. We also have a semantic similarity function $Sim: X \times X \rightarrow [0,1] $. Then, a successful adversarial attack changes the text $x$ to $x_{adv}$, such that $$F(x_{adv}) \neq F(x)$$ $$ Sim (x, x_{adv}) \geq \epsilon$$ where $\epsilon$ is the minimum similarity between original and adversarial text. Let us consider a binary classification model with labels $ \{Y_0, Y_1\}$ which we want to attack. We are given a text $T \in X$ having $m$ sentences, $S = \{s_1, s_2, ..., s_m\}$. The classification model correctly predicts $T$ to be belonging to class $Y_0$ i.e. $F(T) = Y_0$. We input each of the $m$ sentences to $F$ and get their individual labels. Let $A$ and $B$ form a partition of $S$ such that $F(a) = Y_0, \forall a \in A$ and $\mathcal{P}$ (A) be the power set of $A$. Let $\mathcal{A}_r$ be a set of $r$-combinations of $A$. We define another set $G = \{B \cup c \ | c \in \mathcal{P} (A) \} \}$. We refer to each of the elements in $G$ as an '\textbf{aggregate}'. \subsection{Threat Model} We consider the attack in the black-box setting, where an attacker does not have any information about the model weights or architecture and is allowed to query the model with specific inputs and get the final decision of the classifier model as an output. Further, the class confidence scores are not provided to the attacker in the output, making it a hard-label black-box attack. Although NLP APIs provided by Google, AWS and Azure do provide the confidence scores for the classes, but in a real-world application setting, like toxic content detection on a social media platform, the confidence scores are not provided, thereby making it a hard label black-box setting. Such an attack scenario also helps to gauge the model robustness. \subsection{Methodology} The proposed methodology for generating adversarial text has three main steps: \textbf{Step 1: Sentence Importance Ranking}: We observe that when people convey opinions or emotions, not all the sentences convey the same emotion, few sentences are just facts without any emotion or sentiment. Other sentences can also be stratified based on varying levels of intensity. This forms the basis of our sentence ranking algorithm which helps to prioritize our attack on specific portions of the text in order of importance. \par We assume that different sentences in the text contribute to the overall class decision to a varying level of intensity. Each of the sentences can either support or oppose the final decision of the classifier and the intensities which they do so are additive. Consider an example of sentiment analysis, where the labels are positive and negative. The assumption of additivity of sentence class intensity, also helps us to infer that sentences in set $B$ when joined together to form a text, will belong to class $Y_1$. Hereby, we refer to the same as the class of set $B$ or the classifier's decision of set $B$. \par We define the importance of a sentence in set $A$ by its ability to change the classifier's decision of set $B$ from $Y_1$ to $Y_0$. If an individual sentence from set $A$ when added to set $B$ is able to change the class of set $B$ from $Y_1$ to $Y_0$, then we consider the sentence to belong to \textbf{\textit{level 1 importance}}. More generally, if a sentence from set $A$ is able to change the classifier's decision of set $B$ only when it is put together with some subset of $A$ with at least $k-1$ sentences, then the sentence belongs to \textit{\textbf{level k importance}}. The $k-1$ other sentences in all such subsets also belong to \textit{\textbf{level k importance}}. Also, once the importance of a sentence is fixed at the $k^{th}$ level we do not consider it in subsequent levels. \\ {\SetAlgoNoLine% \begin{algorithm} \KwIn{Original Sentences set $S$ , ground truth label $y_0$, classifier $F(.)$ } \KwOut{Sentence Importance Ranking} SentsSentiment $\leftarrow$ Find original labels of sentences in $S$ \; OrigLabelSents $\leftarrow$ Sentences with Label $Y_0$ \; OtherLabelSents $\leftarrow$ Sentences with Label $\neq Y_0$ \; Let OrigLabelSents$_P$ represent set of all $P$ sentence combinations from OrigLabelSent \; OrigLabelAggregates $\leftarrow \phi$ \; $P \leftarrow 1$ \; \While{OrigLabelSents} { TopSentImp$_P$ $\leftarrow \phi$ \; \For{Comb in OrigLabelSents$_P$} {AGG $\leftarrow$ Add $Comb$ to $OtherLabelSents$ and join it to form string \; \If{$F(AGG) = Y_0$} { OrigLabelAggregates $\leftarrow$ Add $AGG$\; \For{sent in Comb} { SentImp[$sent$] $\leftarrow$ P \; TopSentImp$_P$ $\leftarrow$ Add $sent$}} } Delete sentences in TopSentImp$_P$ from OrigLabelSents \; $P \leftarrow P + 1$ \; \If{$P > Length(OrigLabelSents)$} {Add remaining sentences in OrigLabelSents to TopSentImp$_P$ \;} } \Return SentImp , OrigLabelAggregates \caption{Sentence Importance Ranking} \end{algorithm}}% {\SetAlgoNoLine% \begin{algorithm} \KwIn{Original text $X$ , ground truth label $Y_0$, classifier $F(.)$, semantic similarity threshold $\epsilon$, cosine similarity matrix } \KwOut{Adversarial example $X_{adv}$ } Initialization: $X_{adv} \leftarrow X$\; Segment $X$ into sentences to get set $S$\; SentImp, OrigLabelAggs = GetSentenceImp(S)\; WordImpScores = GetWordImp (SentImp)\; Create a set $W$ of all words $w_i \in X$ sorted by the descending order of their wordImpScores\; MISCLASSIFIED $\leftarrow$ False \; \For{$w_j$ in $W $} { \If{MISCLASSIFIED}{ break\;} CANDIDATES = GetSynonyms($w_j$)\; CANDIDATES $\leftarrow$ POSFilter (CANDIDATES) \; CANDIDATES $\leftarrow$ SEMANTICSIMFilter (CANDIDATES) \; FINCANDIDATES $\leftarrow$ Sort CANDIDATES by semantic similarity \; CHANGED $\leftarrow$ False \; \For{$c_k$ in FINCANDIDATES}{ $X' \leftarrow $ Replace $w_j$ with $c_k$ in $X_{adv}$ \; \If{$F(X') \neq Y_0$}{ $X_{adv} = X'$ \; CHANGED $\leftarrow$ True \; MISCLASSIFIED $\leftarrow$ True \; } \If{NOT CHANGED} { SENT $\leftarrow$ Get the sentence in which $w_j$ belongs s.t $F$(SENT) = $Y_0$ \; $X' \leftarrow $ Replace $w_j$ with $c_k$ in SENT\; \If{$F(X')\neq Y_0$ \;} {$X_{adv} = X'$\; CHANGED $\leftarrow$ True \;}} \If{NOT CHANGED} {OrigLabelAGG $\leftarrow$ Get the aggregate in which $w_j$ belongs s.t. $F(AGG) = Y_0$ \; $X' \leftarrow $ Replace $w_j$ with $c_k$ in OrigLabelAGG \; \If{$F(X')\neq Y_0$ \;} {$X_{adv} = X'$\; CHANGED $\leftarrow$ True \; } } }} \caption{TextDecepter} \end{algorithm}}% \textbf{Step 2: Word importance ranking}: After finding the importance of sentences in step 1, we need to find the importance ranking of the words to be attacked in these sentences. We observe that words with a certain Part of Speech (POS) tags are more important than others. For example, for a sentiment classification task, adjectives, verbs, adverbs are more important than nouns, pronouns, conjunctions, or prepositions. Further, we consider adjectives to be more important than adverbs. Consider a sentence, “The movie was very bad”. In this sentence, “bad” is the adjective and shapes the sentiment of the sentence. The adverb “very” increases the intensity of the adjective, making the predicted class confidence score increase further. \\ \textbf{Step 3: Attack}: We use the word Level perturbations in order of word importance obtained from the previous step. We select synonyms to replace the original words using cosine distance between word vectors. Further, to maintain the syntax of the language, only those synonyms having the same POS tags as that of the original word are considered for further evaluations. Experiments are done using, both, coarse and fine POS tag masks. \par Let us look at the details of each of these steps: \begin{enumerate} \item Synonym extraction: We use the word embedding by \cite{mrkvsic2016counter} which obtained state-of-the-art performance on SimLex-999, a dataset designed by \cite{hill2015simlex} to measure how well different models judge the semantic similarity between words. \item POS checking: To maintain the syntax of the adversarial example generated, we filter out the synonyms which have a different POS tag than the original word. We experiment with, both, coarse and fine POS tagging. \end{enumerate} We select a synonym to replace a particular word if its usage leads to one of the following: \begin{enumerate} \item Misclassification of the entire text. \item Misclassification of the original labeled sentence to which the target word belongs. \item Misclassification of the original label aggregate to which the target word belongs. \end{enumerate} \par If multiple synonyms fulfill the rules, then the one which fulfills the rule of higher preference is selected. If multiple synonyms fulfill the highest preference rule, then that synonym is selected whose placement in the review is semantically nearest to the original review. We terminate the algorithm once the text misclassifies, or when all the important words have been iterated over.\par The justification for the higher preference of sentence than the aggregate to which it belongs comes from the additivity assumption. Consider a sentence $v \in A$, $\{v\} \in \mathcal{A}_r$. Now, add it to set $B$ to form an 'aggregate', i.e. $B \cup \{v\} \in G$. Assuming the additivity of class intensities of sentences, we can easily see that when sentences in $B \cup \{v\}$ are joined to form a piece of text, it either belongs to class $Y_1$ or, in case, it belongs to class $Y_0$, then the intensity of class $Y_0$ is lesser when compared to $v$ alone. In other words, an 'aggregate' belonging to class $Y_0$ has lesser intensity of class $Y_0$ when compared with individual sentences belonging to class $Y_0$ which are part of that aggregate. Hence, a synonym which can flip the decision of the classifier, both, on the sentence and the aggregate (initially classified as $Y_0$) to which the sentence belongs would be preferred against a synonym which is just able to change the classifier's decision on the aggregate alone. \\ \par \textbf{Step 4: Reset insignificant replacements} \\ Consider a directed acyclic graph, where a node represents a text and a directed edge between two nodes means that the latter node text can be obtained by replacement of a word $w$ in former node text by its most semantically similar synonym $w'$, given that the synonym has the same POS tag as the original word. Further, the weight of each edge is 1. Then, crafting an adversarial example from a given piece of text can be formulated as a path finding problem as follows; find a path from an initial node $T$ to final node $T'$, such that $F(T) = Y_0$ and $F(T') \neq Y_0$. The sentence and word ranking algorithm decide the order of perturbation. Thereafter, we use the aggregates belonging to the original class as heuristics to guide our graph search. The algorithm stops once the text misclassifies. Although, the heuristics help us in finding a path, but they do not guarantee if it is the shortest path. In the absence of confidence scores of classes, the problem of finding the shortest path has an exponential search space. So, once the given text is turned adversarial, the algorithm visits all the replaced words and resets those replacements without which the perturbed text remains adversarial. \subsection{Time Complexity} Let there be $n$ sentences in a text and $m$ words in total. \begin{enumerate} \item Getting the class label of each of the individual sentences: $O(n)$ \item Sentence Importance ranking: The algorithm takes all possible combinations of sentences from the set of original labeled sentences and insert each of them to the set of sentences which do not have the original label. Hence, the time complexity of this step becomes $O(2^n)$. \item Word importance ranking: \begin{enumerate} \item Sort the original labeled sentences in order of their importance ranking: $O (n \log n)$ \item Iterate over all the words in the sorted sentences and make the word perturb sequence: $O(m)$ \item Generation of cosine similarity matrix of words in text with 65 thousand words in the vocabulary: $O(m)$ \end{enumerate} \item Pick the top $k$ synonyms for each of the candidate words that are to be perturbed. The cosine similarity matrix consists of similarity of each of the words in the text with all the words in the vocabulary. We sort the similarity values for each word with all the other words in the vocabulary. Hence, amounting to total time complexity of $O(m)$ \item Attack: Replace each of the $k$ synonyms of a word in the original text, the original labeled aggregates (obtained from sentence importance ranking step), and the original labeled sentences to which they belong. Hence, the time complexity of this step becomes $O(kmn)$. \item Removal of insignificant perturbations: $O(m)$ \end{enumerate} \par Hence, the overall time complexity of the attack framework becomes $O(2^n)+ O(kmn)$ \subsection{Memory requirement} The generation of adversarial texts requires that we are able to get the synonyms for a particular word during the attack phase. Hence, a cosine similarity matrix is kept in the RAM to quickly generate synonyms for a particular word. In our attack framework, we keep the cosine similarity of only the words in the text that is being attacked, with all the 65 thousand words in the vocabulary. It is an improvement over the memory requirement in the attack framework of TextFooler \cite{jin2019bert} which keeps the cosine similarity matrix of all the 65 thousand words in the vocabulary, constituting a square matrix of size 65 thousand, consuming nearly 17 GB of RAM if single-precision floating-point format is used. \section{Attack Evaluation: Sentiment Analysis} We evaluate our attack methodology on generating adversarial texts for sentiment analysis tasks. Sentiment Analysis is a text classification task that identifies and characterizes the sentiment of a given text. It is widely used by businesses to get the sentiment of customers towards their product or services, by analyzing reviews or survey responses. \subsection{Datasets and Models} We study the effectiveness of our attack methodology on sentiment classification on IMDB and Movie Review (MR) datasets. We target three models: word-based convolutional neural network (WordCNN) \cite{kim2014convolutional}, word-based long-short term memory (WordLSTM) \cite{hochreiter1997long}, and Bidirectional Encoder Representations from Transformers (BERT) \cite{devlin2018bert}. We attack the pre-trained models open-sourced by \cite{jin2019bert} and evaluate our attack algorithm on the same set of 1000 examples that the authors had used in their work. We also run the attack algorithm against Google Cloud NLP API. The summary of the datasets used by \cite{jin2019bert} for training the models are in Table ~\ref{tab:table1} and their original accuracy are given in Table \ref{tab:table2} \begin{table}[h] \centering \begin{tabular}{c|c|ccc} \hline \textbf{Task} & \textbf{Dataset} & \textbf{Train} & \textbf{Test~} & \textbf{Avg Len} \\ \hline \multirow{2}{*}{\textbf{Classification}} & MR & 9K & 1K & 20 \\ & IMDB & 25K & 25K & 215 \\ \hline \\ \end{tabular} \caption{Overview of the datasets used by \cite{jin2019bert} for training the models } \label{tab:table1} \end{table} \begin{table}[h] \centering \begin{tabular}{cccc} \hline & \textbf{wordCNN} & \textbf{wordLSTM} & \textbf{BERT} \\ \hline \textbf{MR} & 79.9 & 82.2 & 85.8 \\ \textbf{IMDB} & 89.7 & 91.2 & 92.2 \\ \hline \\ \end{tabular} \caption{Original accuracy of the target models on standard test sets} \label{tab:table2} \end{table} \subsection{Evaluation Metrics} \begin{enumerate} \item Attack success rate: We first measure the accuracy of the target model on the 1000 test samples and call it original accuracy. Then, we measure the accuracy of the target models against the adversarial samples generated from the same test samples and call it after-attack accuracy. The difference between the original accuracy and the after-attack accuracy of a classification model is called the attack success rate. \item Percentage of Perturbed words: The percentage of words replaced by their synonyms on an average gives us a metric to quantify the change made to a given text. \item Semantic similarity: It tells us the degree to which the two given texts carry a similar meaning. We use the Universal Sentence Encoder to measure the Semantic Similarity between original and adversarial text. Since my main aim is to generate adversarial texts, we just control the semantic similarity to be above a certain threshold. \item Number of queries: The average number of queries made to the target model tells us the efficiency of the attack model. \end{enumerate} \section{Results} \subsection{Automatic Evaluation} We report our results of the hard label black-box attacks in terms of automatic evaluation on two text classification tasks using coarse and fine POS masks. The main results are summarized in Tables ~\ref{tab:table3} and \ref{tab:table11}. Our attack algorithm is able to bring down the accuracy of all the major text classification models with an attack success rate greater than 50\% for all the models. Further, the percentage of perturbed words is nearly 3\% for all the models on the IMDB dataset and between 10-16\% for all the models on the MR dataset. In the IMDB dataset, which has an average word length of 215 words, our attack model is able to conduct successful attacks by perturbing less than 7 words on average. That means that our attack model can identify the important words in the text and makes subtle manipulations to mislead the classifiers. Overall, our algorithm can attack text classification models pertaining to sentiment analysis with an attack success rate greater than 50\%, no matter how long the text sequence or how accurate the target model. Further, our model requires the least amount of information among all the models it is compared with. \par The attack model is also able to attack GCP NLP API and brings down the accuracy from 76.4\% to 16.7\% for the MR dataset. Further, it changes only 10.2\% of the words in the text to generate the adversary. The results are unprecedented as we have achieved the results without having any information about the confidence scores of the classes involved. The attack algorithm and the carefully crafted adversarial texts can be utilized for the study of interpretability of the BERT model \cite{feng2018pathologies}. \par The query number is almost linear to the text length, with a ratio in (6,10) which is at par with \cite{jin2019bert} and \cite{li2018textbugger}. \begin{table*}[h] \centering \begin{tabular}{lcc|cc|cc|c} \hline ~ & \multicolumn{2}{c|}{\textbf{wordCNN}} & \multicolumn{2}{c|}{\textbf{wordLSTM}} & \multicolumn{2}{c|}{\textbf{BERT}} & \textbf{GCP NLP API} \\ \hline & \textbf{MR} & \textbf{IMDB} & \textbf{MR} & \textbf{IMDB} & \textbf{MR} & \textbf{IMDB} & \textbf{MR} \\ \textbf{Original Accuracy} & 78 & 89.4 & 80.7 & 90.3 & 90.4 & 88.3 & 76.4 \\ \textbf{After-attack accuracy} & 18.9 & 17.3 & 18.9 & 32.5 & 42.3 & 30.9 & 16.6 \\ \textbf{Attack Success rate} & 75.8 & 80.6 & 76.6 & 64.0 & 53.2 & 65.0 & 78.3 \\ \textbf{\% Perturbed Words} & 12.1 & 3.1 & 12.2 & 2.8 & 15.6 & 2.1 & 11.8 \\ \textbf{Query number} & 133.2 & 1368.6 & 123.2 & 1918.1 & 189.5 & 1719.7 & 126.8 \\ \hline \textbf{Average Text Length} & 20 & 215 & 20 & 215 & 20 & 215 & 20 \\ \hline \\ \end{tabular} \caption{Automatic evaluation results on text classification datasets (using coarse POS mask)} \label{tab:table3} \end{table*} \begin{table*}[h] \centering \begin{tabular}{lcc|cc|cc|c} \hline ~ & \multicolumn{2}{c|}{\textbf{wordCNN}} & \multicolumn{2}{c|}{\textbf{wordLSTM}} & \multicolumn{2}{c|}{\textbf{BERT}} & \textbf{GCP NLP API} \\ & \textbf{MR} & \textbf{IMDB} & \textbf{MR} & \textbf{IMDB} & \textbf{MR} & \textbf{IMDB} & \textbf{MR} \\ \cline{2-8} \textbf{Original Accuracy} & 78 & 89.4 & 80.7 & 90.3 & 90.4 & 88.3 & 76.4 \\ \textbf{After-attack accuracy} & 20.7 & 18.9 & 21.2 & 34.4 & 45.9 & 33.3 & 16.6 \\ \textbf{Attack Success rate} & 73.5 & 78.9 & 73.7 & 61.9 & 49.2 & 62.3 & 78.3 \\ \textbf{\% Perturbed Words} & 12.2 & 3.1 & 12.0 & 2.6 & 14.6 & 2.2 & 10.2 \\ \textbf{Query number} & 112.5 & 1230.0 & 107.0 & 1650.5 & 159.0 & 1507.4 & 109.6 \\ \hline \textbf{Average Text Length} & 20 & 215 & 20 & 215 & 20 & 215 & 20 \\ \hline \\ \end{tabular} \caption{Automatic evaluation results on text classification datasets (using fine POS mask)} \label{tab:table11} \end{table*} \subsection{Benchmark Comparison} We compare our attack against state-of-the-art adversarial attack systems on the same target model and dataset. For GCP NLP API, we compare our attack results against \cite{li2018textbugger} and \cite{gao2018black} on MR datasets. With wordCNN and wordLSTM as the target models, the comparison is against \cite{li2018textbugger}, \cite{alzantot2018generating}, \cite{jin2019bert}. The results of the comparison are summarised in table ~\ref{tab:table4} and ~\ref{tab:table5}. The lower attack success rates, when compared to the other attack systems, can be attributed to the fact that our attack system does not make use of confidence scores of the classes that other published systems do. \begin{table*}[h] \centering \begin{tabular}{lcc} \hline \textbf{Attack System} & \textbf{Attack Success Rate} & \textbf{\%Perturbed Words} \\ \hline \textbf{Li et al \cite{li2018textbugger}} & 86.7 & 6.9 \\ \hline \textbf{Alzantot al \cite{alzantot2018generating}} & 97.0 & 14.7 \\ \hline \textbf{Jin et al. \cite{devlin2018bert}} & 99.7 & 10.0 \\ \hline \textbf{Ours} & \textbf{64.0} & \textbf{2.4} \\ \hline \\ \end{tabular} \caption{Comparison of our attack system against other published systems with wordLSTM as the target model (Dataset: IMDB) } \label{tab:table4} \end{table*} \begin{table*}[h] \centering \begin{tabular}{lccc} \hline \multicolumn{1}{c}{\textbf{Attack System}} & \textbf{Original Accuracy} & \textbf{Attack Success Rate} & \textbf{\%Perturbed Words} \\ \hline \textbf{Gao et al. \cite{gao2018black}} & 76.7 & 67.3 & 10 \\ \textbf{Li et al. \cite{li2018textbugger}} & 76.7 & 86.9 & 3.8 \\ \textbf{Ours} & 76.4 & 78.1 & 10.2 \\ \hline \\ \end{tabular} \caption{Comparison of our attack system against other published systems with Google Cloud NLP API as the target model (Dataset: MR) } \label{tab:table5} \end{table*} \begin{table*}[h!] \centering \begin{tabular}{lll} \hline & & \textbf{Movie Review (Positive (POS) $\leftrightarrow$ Negative (NEG))} \\ \hline \multirow{6}{*} & \textbf{Original (Label: NEG)} & i firmly \textit{\textbf{believe}} that a good video game movie is going to show up soon i also believe that resident evil is not it \\ & \textbf{Attack (Label: POS} & i firmly \textit{\textbf{feel}} that a good video game movie is going to show up soon i also believe that resident evil is not it \\ \cline{2-3} & \textbf{Original (Label: POS)} & strange and \textit{\textbf{beautiful}} film \\ & \textbf{Attack (Label: NEG)} & strange and \textit{\textbf{resplendent}} film \\ \cline{2-3} & \textbf{Original (Label: POS)} & the lion king was a roaring \textit{\textbf{success}} when it was released eight years ago , but on imax it \textit{\textbf{seems}} better, not just bigger \\ & \textbf{Attack (Label: NEG} & the lion king was a roaring \textit{\textbf{attainment}} when it was released eight years ago , but on imax it \textit{\textbf{transpires}} better , not just bigger \\ \hline \\ \end{tabular} \caption{Examples of original and adversarial sentences from MR (GCP NLP API) } \label{tab:table7} \end{table*} \subsection{Human Evaluation} Following the practice of \cite{jin2019bert}, we perform human evaluation by sampling 100 adversarial examples from the MR dataset with the WordLSTM. We perform three experiments to verify the quality of our adversarial examples. First, the human judges are asked to give the grammaticality score of a shuffled mix of original and adversarial text on a scale of 1-5. As shown in Table, the grammaticality of the adversarial texts with fine POS tag mask is closer to the original texts when compared with coarser POS tag mask. However both of the scores are above 4 meaning that using, both, coarse and fine POS tags result in smooth adversarial texts. \par Second, the judges assign classification labels to a shuffled set of original and adversarial texts, for both coarse and fine POS masks. The results show that the overall agreement between the labels of the original and adversarial text for both the cases are quite high, 92\% and 93\% respectively. This suggests that improving the grammaticality of the adversarial texts using a fine POS mask does not contribute much to the overall meaning of the texts to humans. \par Third, the judges determine whether the adversarial texts retain the meaning of the original text. The judges are given three options, 1 for similar, 0.5 for ambiguous, and 0 for dissimilar. The average sentence similarity score is 0.88 when a fine POS mask is used compared to 0.86 when a coarse POS mask is used for synonym-selection, suggesting a marginal improvement in sentence similarity scores in the former. \begin{table*}[h] \centering \begin{tabular}{lp{13cm}l} \hline \ & \multicolumn{1}{c}{\textbf{ Movie Review (Positive (POS)$\leftrightarrow$ Negative (NEG))}} \\ \hline \\ \textbf{Original (Label: NEG)} & after the book i became very \textbf{\textit{sad}} when i was watching the movie . i am agree that sometimes a film should be different from the original novel but in this case it was more than acceptable . some examples: 1 ) why the ranks are different ( e.g. lt . diestl instead of sergeant etc.) 2 ) the final screen is very \textbf{\textit{poor }}and makes diestl as a soldier who feds up himself and wants to die . but it is not true in 100 \% . just read the book . he was a bull - dog in the last seconds as well . he did not want to die by wrecking his gun and walking simply towards to michael \& noah . so this is some kind of a happy end which does not fit at all for this movie . \\ \\ \textbf{Attack (Label: POS)} & after the book i became very \textbf{\textit{bleak }}when i was watching the movie . i am agree that sometimes a film should be different from the original novel but in this case it was more than acceptable . some examples:1 ) why the ranks are different ( e.g. lt . diestl instead of sergeant etc.) 2 ) the final screen is very \textbf{\textit{flawed }}and makes diestl as a soldier who feds up himself and wants to die . but it is not true in 100 \% . just read the book . he was a bull - dog in the last seconds as well . he did not want to die by wrecking his gun and walking simply towards to michael \& noah . so this is some kind of a happy end which does not fit at all for this movie .~ \\ \\ \hline \\ \textbf{Original (Label: NEG)} & seriously , i do n't understand how justin long is becoming increasingly popular . he either has the best agent in hollywood , or recently sold his soul to satan . he is almost \textit{\textbf{unbearable}} to watch on screen , he has little to no charisma , and \textit{\textbf{terrible}} comedic timing . the only film that he has attempted to anchor that i 've remotely enjoyed was waiting ... and that is almost solely because i 've worked in a restaurant . but i digress . aside from it 's \textit{\textbf{terrible}} lead , this film has loads of other debits . i understand that it 's supposed to be a \textit{\textbf{cheap}} popcorn comedy , but that does n't mean that it has to completely insult our intelligence , and have writing so incredibly hackneyed that it borders on offensive . lewis black 's considerable talent is wasted here too , as he is at his most incendiary when he is unrestrained , which the pg-13 rating certainly wo n't allow . the film 's sole bright spot was jonah hill ( who will look almost unrecognizable to fans of the recent superbad due to the amount of weight he lost in the interim ) . his one liners were funny on occasion , but were certainly not enough to make this anywhere close to bearable . if you just want to completely turn your brain off ( or better yet , do n't have one ) then maybe you 'd enjoy this , but i ca n't recommend it at all . \\ \\ \textbf{Attack (Label: POS)} & seriously , i do n't understand how justin long is becoming increasingly popular . he either has the best agent in hollywood , or recently sold his soul to satan . he is almost \textit{\textbf{terrible}} to watch on screen , he has little to no charisma , and \textit{\textbf{spooky}} comedic timing . the only film that he has attempted to anchor that i ' ve remotely enjoyed was waiting ... and that is almost solely because i ' ve worked in a restaurant . but i digress . aside from it 's \textit{\textbf{spooky}} lead , this film has loads of other debits . i understand that it 's supposed to be a \textit{\textbf{miserly}} popcorn comedy , but that does n't mean that it has to completely insult our intelligence , and have writing so incredibly hackneyed that it borders on offensive . lewis black 's considerable talent is wasted here too , as he is at his most incendiary when he is unrestrained , which the pg-13 rating certainly wo n't allow . the film 's sole bright spot was jonah hill ( who will look almost unrecognizable to fans of the recent superbad due to the amount of weight he lost in the interim ) . his one liners were funny on occasion , but were certainly not enough to make this anywhere close to bearable . if you just want to completely turn your brain off ( or better yet , do n't have one ) then maybe you 'd enjoy this , but i ca n't recommend it at all . \\ \hline \\ \\ \end{tabular} \caption{Examples of original and adversarial sentences from IMDB (BERT) } \label{tab:table8} \end{table*} \begin{table*}[h!] \centering \begin{tabular}{ccc} \hline & \textbf{Fine POS filter} & \textbf{Coarse POS filter} \\ \hline \textbf{Original} & 4.5 & 4.5 \\ \textbf{Adversarial} & 4.3 & 4.1 \\ \hline \\ \end{tabular} \caption{Grammaticality of original and adversarial examples for MR (BERT) ON 1-5 scale} \label{tab:table9} \end{table*} \begin{table*}[h] \centering \begin{tabular}{ll} \hline & \textbf{Movie Review (Positive (POS) $\leftrightarrow$ Negative (NEG))} \\ \hline \textbf{Original (Label: POS)} & she may not be real , but the \textbf{laughs }are \\ \textbf{Attack (Label: NEG) using coarse POS tags} & she may not be real , but the \textbf{\textit{kidding }}are \\ \textbf{Attack (Label: NEG) using fine POS tags} & she may not be real , but the \textbf{\textit{chuckles }}are \\ \hline \textbf{Original (Label: NEG)} & falsehoods pile up , \textbf{\textit{undermining }}the movie 's reality and stifling its creator 's comic voice \\ \textbf{Attack (Label: POS) using coarse POS tags} & falsehoods heaps up , \textbf{\textit{jeopardizes~}}the movie 's reality and stifle its creator 's comic voice \\ \textbf{Attack (Label: POS) using fine POS tags} & falsehoods heaps up , \textbf{\textit{jeopardizing~}}the movie 's reality and stifle its creator 's comic voice \\ \hline \\ \end{tabular} \caption{Qualitative comparison of adversarial attacks with coarse and fine POS tagging for synonyn selection. Target Model is wordLSTM } \label{tab:table6} \end{table*} \newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}} \begin{table*}[h] \centering \begin{tabular}{cccccc} & \textbf{Orig Acc.} & \multicolumn{2}{C{2cm}}{\textbf{After-Attack accuracy}} & \multicolumn{2}{C{2cm}}{\textbf{\% Perturbed words}} \\ & & \textbf{w/ agg.} & \textbf{w/o agg.} & \textbf{w/ agg.} & \textbf{w/o agg.} \\ \hline \textbf{IMDB} & 88.3 & 30.9 & 63.2 & 2.1 & 0.6 \\ \textbf{MR} & 90.4 & 42.4 & 75 & 13.6 & 10.1 \\ \hline \\ \end{tabular} \caption{Comparison of the after-attack accuracies of the BERT model with and without using aggregates for synonym selection } \label{tab:table10} \end{table*} \subsection{Comparison of Fine and Coarse POS tag filter} Part of Speech (POS) tags can be of two types: Coarse-grained (Noun, Verb, Adjective, etc.) or Fine-grained (Noun-proper-singular, noun-proper-plural, verb-past, verb-present, etc). TextDecepter uses a POS mask to reject those synonyms which do not belong to the same POS as that of the original word when they are placed in the text. A Fine-grained POS mask helps to maintain grammaticality to a greater extent when compared to the coarse-grained POS mask as demonstrated in Table \ref{tab:table6}. However, during human evaluation, we observed that improving the grammaticality of the adversarial texts for sentiment classification dataset using fine POS does not contribute much to the overall understanding of the text for humans. We recommend using the appropriate POS mask depending on the grammaticality requirement for the context in which adversarial texts are being generated. \section{Discussion} \subsection{Ablation study} \textbf{Aggregates} The most critical step of our algorithm is the use of aggregates, which belong to the original class, to select or reject synonyms for replacement. To validate the effectiveness of this step we remove the usage of aggregates and select a synonym for replacement only when its presence is able to misclassify the original text. The results for the BERT model are shown in table \ref{tab:table10} . After removing the sentence importance ranking step, we see that the after-attack accuracy increases by 32\% for IMDB and 35\% for MR dataset, respectively. This suggests the importance of aggregates for selecting synonym for replacement, the removal of which renders the attack ineffective. The aggregates generated in the sentence importance ranking step help us to select those synonyms which can take the original text towards misclassification. \section{Conclusion} We propose a hard label black-box attack strategy for text classification tasks. We also conduct extensive experimentation on sentiment analysis datasets to validate our attack system. We also conduct human evaluation to validate the grammatical and semantic correctness of the generated adversarial examples. The attack algorithm uses the assumption of additivity of class intensities of sentences to craft adversarial examples and achieves attack success rate of more than 50 \% against state-of-the-art text classification models. The adversarial examples generated can be utilized to improve the existing text classification models for sentiment analysis by including them in the training dataset. The attack algorithm can also be used to gauge the robustness of text classification models pertaining to sentiment analysis. We also improved upon the memory requirement for the attack, as compared to the other comparative attack frameworks. As a future line of work, it would be imperative to run the attack algorithm on multi-class classification and textual entailment tasks to test the generalization capability of the proposed methodology. \section*{Acknowledgment} I thank Prof. Sunil Shende for insightful discussions. I especially appreciate Kalyan Alapati and Dheenadhyalan Kumaraswamy for helping with human evaluation. \bibliographystyle{IEEEtran}
{'timestamp': '2020-12-29T02:22:38', 'yymm': '2008', 'arxiv_id': '2008.06860', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06860'}
arxiv
\section{Introduction} Nowadays, a growing number of short videos are generated and uploaded to Taobao. Among these videos, user-generated videos are massive in volume and share unique product experiences, such as the individual preference for the product usage scenario or usage strategy. When recommending these videos to customers for product promotion, accompanying a description that narrates the uploader-preferred highlights depicted in the product video is essential for successful promotion, \textit{i}.\textit{e}., attracting potential customers with similar interests or preferences to buy the same product. Different from traditional video-to-text generation problems which mainly concern what exists or happens in the video, this problem cares about what the video uploader wants to highlight. We name this particular problem as \textit{product-oriented} video captioning. \begin{figure}[!t] \begin{center} \includegraphics[width=0.9\columnwidth]{./figures/FirstPage.pdf} \caption{ An illustration of \textit{product-oriented} video captioning. (a) A real-world product video recommendation scenario. (b) A showcase of the product aspects, user-generated video, and a video caption. (c) An illustration of how \textit{Poet} contribute to product promotion. } \vspace{-0.4cm} \label{fig:application} \end{center} \end{figure} \begin{sloppypar} Product-oriented video captioning naturally requires a fine-grained analysis of prominent product characteristics depicted in the video. However, without some general understanding of the product, it can be hard even for a human to grasp what the uploader mainly concerns based on the isolated video. To this end, we view leveraging product-related knowledge as a fundamental ability for product-oriented video captioning. Concretely, we take the structured product aspects from the associated product as prior knowledge since they are easy to acquire (most user-generated videos in e-commerce have on-sell product associations.) and concise in meaning. The structured product aspects arranged by product sellers contain general and basic information necessary for fine-grained video understanding. Figure \ref{fig:application} reveals the task definition, the application scenario in Mobile Taobao, and how automatic tools contribute to product promotion \footnote{\label{foot1}For the original Chinese descriptions as well the desensitized datasets, please refer to \url{https://github.com/shengyuzhang/Poet}}. \end{sloppypar} \iffalse 这两个原因其实是同一个,不能加入product的信息,就做不到product oriented 通过video caption和video tone两个任务的本质区别,提出video tone的挑战,比如: 1) how to incorporate the product information for product oriented video tone; 2) how to model spatial interactions between region-region and region-background within frames 等 Video tone是否可以认为是producte oriented video caption?? \fi Recent advances in deep neural networks \cite{Wang_Wang_Huang_Wang_Tan_2018,Liu_Ren_Yuan_2018,Tang_Wang_Wang_Xu_2017}, especially the RNNs, have convincingly demonstrated high capability in handling the general video captioning problem. Most of them \cite{Venugopalan_Rohrbach_Donahue_Mooney_Darrell_Saenko_2015,Yao_Torabi_Cho_Ballas_Pal_Larochelle_Courville_2015,Pan_Xu_Yang_Wu_Zhuang_2016} incorporate an RNN based encoder-decoder structure with/without attention mechanisms to perform sequential frames encoding and sequential words decoding. However, \textit{product-oriented} video captioning poses some unique challenges. A first challenge comes from mining the product characteristics from the user-generated product videos and capturing the dynamic interactions of these characteristics within and across frames, as well as exploring the interactions between the product and the background scene. We name this fundamental requirement as product-oriented video modeling, which is essential for discovering what the uploader highlights. Another challenge relates to the joint modeling of discrete product aspects and the video. The cross-modal nature of these inputs makes the modeling even more challenging. To address these challenges, we propose an approach, named \textbf{P}roduct-\textbf{o}riented Vid\textbf{e}o Cap\textbf{t}ioner and abbreviated as \textbf{\textit{Poet}}. For product-oriented video modeling, \textit{Poet} first represents the product parts as graph nodes and build a spatial-temporal video graph. Then, \textit{Poet} encapsulates the proposed spatial-temporal inference module to perform long-range temporal modeling of product parts across frames and spatial modeling of product parts within the same frame. We also mix a spatial frame node into the video graph to explore the interactions between the foreground (product) and the background (scene). For the second challenge, we propose the knowledge leveraging module, which comprises the knowledge filtering process and knowledge aggregation process. To accommodate the \textit{product-oriented} video captioning research, we build two large-scale datasets, named buyer-generated fashion video dataset (BFVD) and fan-generated fashion video dataset (FFVD), from Mobile Taobao. There are 43,166 and 32,763 <video, aspects, description> triplets in BFVD and FFVD, respectively. On the language side, descriptions in these two datasets have an extensive vocabulary and considerable product details. Compared with captions in existing video datasets that mostly describe the main objects and the overall activities, descriptions in BFVD and FFVD reflect the characteristics of product-parts, the overall appearance of the product, and interactions between products and backgrounds. Such new features present unique challenges for \textit{product-oriented} video captioning and also for general video analysis. To summarize, this paper makes the following key contributions: \begin{sloppypar} \begin{itemize} \item We propose to investigate a real-world video-to-text generation problem, \textit{product-oriented} video captioning, to automatically narrate the user-preferred product characteristics inside user-generated videos. \item We propose a novel Poet framework for \textit{product-oriented} video captioning via simultaneously capturing the user-preferred product characteristics and modeling the dynamic interactions between them with a product-oriented spatial-temporal graph. \item We introduce a novel knowledge leveraging module to incorporate the product aspects for product video analysis by performing knowledge filtering, dynamic memory writing, and knowledge attending. \textit{Poet} yields consistent quantitative and qualitative improvements on two \textit{product-oriented} video captioning datasets \footref{foot1} that are collected in Mobile Taobao. \end{itemize} \end{sloppypar} \section{Related Works} \subsection{Video to Text Generation} Most deep learning based video-to-text generation methods \cite{Venugopalan_Xu_Donahue_Rohrbach_Mooney_Saenko_2015,Venugopalan_Rohrbach_Donahue_Mooney_Darrell_Saenko_2015,Yao_Torabi_Cho_Ballas_Pal_Larochelle_Courville_2015,Pan_Xu_Yang_Wu_Zhuang_2016,Wang_Ma_Zhang_Liu_2018,Ma_Cui_Dai_Wei_Sun_2019,Shi_Cai_Joty_Gu_2019,Zhu_Jiang_2019,Barati_Chen_2019,Xu_Yao_Zhang_Mei_2017,Yang_Xu_Wang_Wang_Han_2017,zhou2020progress} focus on sequence-to-sequence modeling and employ RNN based encoder-decoder structures. Typically, S2VT \cite{Venugopalan_Rohrbach_Donahue_Mooney_Darrell_Saenko_2015} firstly formulates video-to-text as a sequence to sequence process. SALSTM \cite{Yao_Torabi_Cho_Ballas_Pal_Larochelle_Courville_2015} improves the decoding process using the effective soft-attention mechanism. HRNE \cite{Pan_Xu_Yang_Wu_Zhuang_2016} builds a hierarchical RNN design for representing videos. RecNet \cite{Wang_Ma_Zhang_Liu_2018} proposes to re-produce the input frames features after decoding. More recently, there are works exploiting object-level features in representing the videos \cite{Zhang_Peng_2019,Yang_Han_Wang_2017,Hu_Chen_Zha_Wu_2019,Wang_Xu_Han_2018} for video description generation. They mainly propose to detect salient objects and employ RNNs to model the temporal structure between them. However, they are not directly applicable to \textit{product-oriented} video captioning for the following two reasons: 1) \textit{product-oriented} video captioning requires even more fine-grained video analysis, \textit{i}.\textit{e}., product-part characteristic recognition. 2) These methods neglect the spatial interactions between region-region and region-background within frames. \textit{Poet} represents both the detected product-parts and the whole frames as spatial-temporal graphs and employs the graph neural network to model the interactions between product-parts and product-background. \subsection{Knowledge enhanced Video Analysis} Incorporating external in-domain knowledge is a promising research direction \cite{pan2019multiple} for video analysis. There are mainly two kinds of external knowledge, \textit{i}.\textit{e}., knowledge graph and topically related documents (\textit{e}.\textit{g}., Wikipedia). Knowledge graph based methods \cite{Gao_Zhang_Xu_2019,Gao_Zhang_Xu_2018} typically retrieve the knowledge graph from off-the-shelf knowledge bases such as ConceptNet 5.5 \cite{Speer_Chin_Havasi_2017} and employ the graph convolution network \cite{Kipf_Welling_2017} to perform knowledge reasoning. These methods are not suitable for our task since there are no well-defined relationships among product aspects. For document-based approaches, Venugopalan \textit{et al}. \cite{Venugopalan_Hendricks_Mooney_Saenko_2016} uses the Wikipedia corpus to pre-train a language model (LM) and proposes the late/deep fusion strategies to enhance the decoding RNN with the LM. Whitehead \textit{et al}. \cite{Whitehead_Ji_Bansal_Chang_Voss_2018} first retrieves the relevant document and then use the pointer mechanism to directly borrow entities in the decoding stage. Different from these works, \textit{Poet} performs knowledge leveraging in the product-oriented spatial-temporal inference stage. \section{Methods} \subsection{Overview} After data preprocessing (details in Section \ref{Data Collection}), we represent each product-oriented video as frame-level features $\{\mathbf{f}_{i} \in \mathbb{R}^{D_f} \}_{i = 1,\dots,N_f}$ where $\mathbf{f}_{i}$ is the $D_v$ length feature vector for the $i$th frame $f_i$, and product-part features $\{ \mathbf{p}_{i,j} \in \mathbb{R}^{D_p} \}_{j=1,\dots,N_p}$ where $\mathbf{p}_{i,j} $ is the $D_p$ length feature vector for the $j$th product-part in the $i$th frame. The video-associated product aspects are $ \{ a_k \}_{k = 1,\dots,N_a} $ and we use the embedding layer to learn an aspect embedding $\mathbf{a}_k \in \mathbf{R}^{D_a}$ of dimension $D_a$ for the $k$th aspect $a_k$. We aim to generate a video description $\{w_m\}_{m=1,\dots,N_w}$ that narrates the preferred product characteristics of e-commerce buyers/fans. We firstly build a product-oriented spatial-temporal video graph (See Figure \ref{fig:schema}), which contains both frame nodes and product-part nodes. With the graph representation, the encoder of \textit{Poet} mainly incorporates two sub-modules, \textit{i}.\textit{e}., the spatial-temporal inference module for graph modeling, and the knowledge leveraging module for product aspects modeling. These sub-modules can be easily stacked to obtain a progressive knowledge retrieval and knowledge enhanced visual inference process. In the next several subsections, we will formally introduce the building blocks comprising \textit{Poet}, including the graph building process, the spatial-temporal inference module, the knowledge leveraging module, and the attentional RNN-based decoder in detail. \subsection{Product-oriented Video Graph Modeling} \subsubsection{Graph Building} To better capture the highlights (\textit{i}.\textit{e}., preferred product characteristics) inside the product videos, we propose to represent the videos as spatial-temporal graphs. \vpara{Nodes} Different from previous works \cite{Zhang_Peng_2019,Yang_Han_Wang_2017,Hu_Chen_Zha_Wu_2019,Wang_Xu_Han_2018} that represent the objects as graph nodes, we represent product parts as nodes to capture the dynamic change of these fine-grained details along the timeline. Product-part features are extracted by a pre-trained CNN-based detector (details in \ref{Data Collection}), and thus these features naturally contain spatial cues. However, since we do not model the product parts along the timeline using RNNs, there is no concept of frame order in the modeling process. To this end, we add an order-aware embedding $\mathbf{o}_i \in \mathbb{R}^{D_p}$ to each product-part feature, which is similar to the position embedding strategy employed in sequence learning \cite{gehring2017convolutional,lu2019vilbert}. $\mathbf{o}_i$ stands for the embedding for the frame order $i$. Sharing similar spirit, we further obtain the type-aware product-part representation by adding the part-type embedding $\mathbf{t}_j \in \mathbb{R}^{D_p}$, which stands for the $j$th part for a particular product, such as waistline and hem. Then, the enhanced product-part feature $\mathbf{p}^e_{i,j}$ can be obtained by: \begin{align} \mathbf{p}^e_{i,j} = \mathbf{p}_{i,j} + \mathbf{o}_i + \mathbf{t}_j, \end{align} Besides the product-part nodes, we further incorporate the frame node into each frame graph to capture the product as a whole and exploit the correlations between the products and the backgrounds. Similar to the product-part feature, we add the order-based embedding $\mathbf{o}_i$ and a special type embedding $\mathbf{t}_{[\textrm{frame}]}$ for obtaining the frame-order concept and the frame-type concept, respectively. \begin{align} \mathbf{f}^e_{i} = \mathbf{f}_{i} + \mathbf{o}_i + \mathbf{t}_{[\textrm{frame}]}. \end{align} We then project the product-part features and the frame features into a common space by employing two linear transformations, \textit{i}.\textit{e}., $\mathbf{W}_p \in \mathbb{R}^{D_{pf} \times D_{p}}$ and $\mathbf{W}_f \in \mathbb{R}^{D_{pf} \times D_{f}}$. \begin{align} \mathbf{v}^p_{i,j} = \mathbf{W}_p \mathbf{p}^e_{i,j} + \mathbf{b}_p, \ \ \mathbf{v}_{i, [\textrm{frame}]} = \mathbf{W}_f \mathbf{f}^e_{i} + \mathbf{b}_f. \end{align} $\mathbf{b}_p, \mathbf{b}_f \in \mathbb{R}^{D_{pf}}$ are the bias terms. Therefore, each frame graph contains $N_p$ product-part nodes $\{ v^p_{i,j} \}_{j=1,\dots,N_p}$ with representations $\{ \mathbf{v}^p_{i,j} \}_{i=1,\dots,N_p}$ and one frame node $v_{i,[\textrm{frame}]}$ with representation $\mathbf{v}_{i,[\textrm{frame}]}$. There are totally $N_f$ frame sub-graphs in the whole graph. \vpara{Edges} To capture the correlations among product-parts within the same frame as well as the interactions between global frame context (\textit{e}.\textit{g}., background, the product as a whole) and local part details, we propose a baseline method by fully connecting the product-part nodes and frame node within each frame graph. To obtain a comprehensive understanding and the dynamic change of product-parts across different viewpoints, we fully connect the nodes of the same type (including the frame type) from all frames. The edge weights are obtained using a fully-connected layer: \begin{align} \mathbf{e}_{\iota,\kappa} = \mathbf{W}_e [\mathbf{v}_{\iota}, \mathbf{v}_{\kappa}] + \mathbf{b}_e, \end{align} where $\mathbf{e}_{\iota,\kappa} \in \mathbb{R}$ is the weight of edge between node $v_{\iota}$ and $v_{\kappa}$. We use a linear transformation $\mathbf{W}_e \in \mathbb{R}^{1 \times 2*D_{pf}}$ with a bias term $\mathbf{b}_e \in \mathbb{R}$ to estimate the correlation of two nodes. $[,]$ denotes the concatenation operation. For convenience, we use $G_v$ to denote the initial video graph and intermediate video graphs since only nodes feature representations are updated. \subsubsection{Spatial-temporal Inference} Although previous works \cite{Yang_Han_Wang_2017,Hu_Chen_Zha_Wu_2019,Wang_Xu_Han_2018} have proposed to capture the fine-grained region-of-interests such as objects and \cite{Zhang_Peng_2019} proposes to represent these fine-grained cues as graphs, they all use RNN-based modeling which can be inefficient for its internally recurrent nature and can be less effective in modeling interactions of regions within a frame since these regions have no natural temporal dependencies. To this end, we employ the flexible graph neural networks for spatial-temporal inference. Existing works performing video graph modeling for video relation detection \cite{Qian_Zhuang_Li_Xiao_Pu_Xiao_2019}, temporal action localization \cite{Zeng_Huang_Tan_Rong_Zhao_Huang_Gan_2019}, and video action classification \cite{Wang_Gupta_2018} often leverage the off-the-shelf Graph Convolutional Networks \cite{kipf2016semi} for information propagation. We propose a new modeling schema by separately modeling the root node and neighbor nodes when aggregation. For neighbor nodes information aggregation, we use an element-wise max function for its effectiveness in the experiment: \begin{align} \mathbf{\bar v}_{\iota, \varsigma}^n = \max_{\kappa} \{\mathbf{e}_{\iota,\kappa} * \mathbf{v}_{\kappa, \varsigma}, v_\kappa \in \mathcal{N}(v_\iota) \}, \end{align} where $\mathcal{N}(v_\iota)$ denotes the neighbor nodes set of the root node $v_\iota$ and $\mathbf{v}_{\kappa,\varsigma}$ is $\varsigma$th element in the feature vector of node $v_\kappa$. We note the edge weight $\mathbf{e}_{\iota,\kappa}$ will be re-computed for each information propagation process. We then perform separate modeling for the root node and the neighbor nodes: \begin{align} \mathbf{\bar v}_\iota = \mathbf{W}_n \mathbf{\bar v}_{\iota}^n + \mathbf{b}_n + \mathbf{W}_r \mathbf{v}_\iota + \mathbf{b}_r, \end{align} where $\mathbf{W}_n, \mathbf{W}_r$ are linear transformations to project the root representation and the aggregated neighbors representation into a common space. $\mathbf{b}_n,\mathbf{b}_r$ are the bias terms. This schema further incorporates an element-wise function for re-weighting the importance of each position as well as a short-cut connection: \begin{align} \mathbf{\tilde v}_\iota = \sigma(\mathbf{W}_n^a \mathbf{\bar v}_{\iota}^n + \mathbf{b}_n^a + \mathbf{W}_r^a \mathbf{v}_\iota + \mathbf{b}_r^a) * \mathbf{\bar v}_\iota + \mathbf{v}_\iota. \end{align} where $*$ denotes the Hadamard product. Matrices $\mathbf{W}_n^a, \mathbf{W}_r^a$ and the corresponding biases $\mathbf{b}_n^a, \mathbf{b}_r^a$ model the position-wise importance. $\sigma$ denotes the element-wise sigmoid function. \subsection{Product-aspects Leveraging} \subsubsection{Knowledge Filtering} Leveraging product aspects as knowledge is an essential part of obtaining the basic product information first and a better understanding of the user-generated product videos later. Different from other kinds of external knowledge (\textit{e}.\textit{g}., Knowledge Base and Wikipedia), the aspects of the associated product contain noised values that may hurt the performance of product video understanding. For example, there can be both \texttt{black-white} and \texttt{red-blue} color choices for a certain t-shirt on sell while the buyer/fan may love the \texttt{black-white} one and wear it in the video. We therefore devise a knowledge filtering module based on the hard attention mechanism to filter noised values such as \texttt{red-blue} for each video. Formally, given the nodes features $\{\mathbf{v}_\tau\}_{\tau=1,\dots,N_f * (N_p + 1)}$ in the video graph $G_v$ and product aspect embeddings $\{\mathbf{a}_k\}_{k=1,\dots,N_a}$, we perform knowledge filtering by: \begin{align} & \mathbf{v}^\circ = \frac{1}{N_f * (N_p + 1)} \sum_\tau \mathbf{v}_{\tau}, \\ &\mathbf{\alpha}_k = \sigma(\mathbf{W}_{h}[ \mathbf{a}_k, \mathbf{v}^\circ] + \mathbf{b}_{h}), \label{eq:importance} \\ & \bar A = \{ a_{s} | \frac{ \exp(\mathbf{\alpha}_{s}) }{\sum_k \exp( \mathbf{\alpha}_{k}) } > \beta_{s} \}, \end{align} where $\bar A$ denotes the filtered aspect set, which includes aspect $a_{s}$ with importance $\mathbf{\alpha}_{s}$ over a certain threshold $\beta_{s}$. We empirically set the threshold to the uniform probability $1 / N_a$. The importance indicator $\mathbf{\alpha}_k$ is computed using a linear transformation $\mathbf{W}_{h}$ and a bias term $\mathbf{b}_{h}$. We use the global (or averaged-pooled) representation $\mathbf{v}^\circ$ of the video graph as the filtering context since we aim to remove aspects that are irrelevant to any part of the video. We add a sigmoid function $\sigma$ to prevent large importance scores, which may lead to a small filtered aspect set after the scores being forward to the $softmax$ function. \subsubsection{Dynamic Memory Modeling} Previous works that incorporate external knowledge for video description generation \cite{Whitehead_Ji_Bansal_Chang_Voss_2018,Venugopalan_Hendricks_Mooney_Saenko_2016} often leverage the knowledge in the decoding stage, \textit{i}.\textit{e}., using pointer mechanism to directly borrow the words/entities from the knowledge document or using attention mechanism to update the decoder hidden state. We propose to progressively retrieve relevant knowledge in the encoding stage, which enables a better understanding of the video for capturing user-preferred product highlights. Specifically, we employ a memory network \cite{Glehre_Chandar_Cho_Bengio_2018,Weston_Chopra_Bordes_2015,Sukhbaatar_Szlam_Weston_Fergus_2015} based approach and enhance it with dynamic memory writing: \begin{align} & \mathbf{\bar a}_{s} = \alpha_{s} * (\mathbf{W}_a \mathbf{a}_{s} + \mathbf{b}_a) + (1 - \alpha_{s}) * (\mathbf{W}_{gl} \mathbf{v}^\circ + \mathbf{b}_{gl} ), \label{eq:memwrite} \\ & \mathbf{\omega}_{\tau,s} = \mathbf{W}_\omega \tanh(\mathbf{W}_m [\mathbf{v}_\tau, \mathbf{\bar a}_{s}] + \mathbf{b}_m), \\ & \mathbf{\hat v}_\tau = \gamma * \mathbf{v}_\tau + \sum_{s} \mathbf{\bar \omega}_{\tau,s} * \mathbf{\bar a}_{s} , \ \textrm{where} \ \mathbf{\bar \omega}_{\tau,s} = \frac{ \exp( \mathbf{\omega}_{\tau,s} ) }{\sum_{o} \exp( \mathbf{\omega}_{\tau,o} ) }. \label{eq:a3} \end{align} where the memory writing process (Equation \ref{eq:memwrite}) borrows the importance factor $\alpha_{s}$ from Equation \ref{eq:importance} (Note that the importance factor $\alpha_{s}$ is in the range $(0, 1)$ after the $\sigma$ function.) This process helps inhibit relatively irrelevant aspect information (with smaller $\alpha_{s}$) and enliven the more relevant ones (with larger $\alpha_{s}$). $\gamma$ controls to what extend the final representation $\mathbf{\hat v}_\tau$ depends on the initial representation $\mathbf{v}_\tau$ and we empirically set it to $0.5$. \subsection{Progressive Inference Encoder} Since the spatial-temporal inference module and the knowledge leveraging module updates the node representation without modifying the graph structure, we can easily stack multiple STI modules and multiple KL modules. Poet builds the inference encoder by progressively and alternatively performing STI and KL as depicted in Figure \ref{fig:schema}. In such a design, we aim to not only obtain higher-order graph reasoning (i.e., with access to remote neighbors) but also propagate the leveraged knowledge to the whole graph by the following STI modules. We denote the combination of one STI and one KL as one graph reasoning layer. We use two-layers graph reasoning in the experiment and we observe stacking more layers, which may make node representations over-smoothing and not distinct (i.e., all nodes contain similar information), will lead to a minor performance drop. \subsection{Decoder} Following many previous works \cite{Zhu_Jiang_2019,Liu_Ren_Yuan_2018}, we build the decoder with the RNN (here we use gated recurrent unit $GRU$ \cite{Cho_Merrienboer_Bahdanau_Bengio_2014}) and soft attention mechanism. We first initialize the hidden state of $GRU$ as the global representation of the knowledge-aware video graph: \begin{align} \mathbf{h}_0 = \mathbf{v}^\circ = \frac{1}{N_f * (N_p + 1)} \sum_\tau \mathbf{v}_{\tau}, \end{align} For each decoding step $t$, we attend to each node inside the video graph and aggregate the visual cues using the weighted sum: \begin{align} & \mathbf{\varrho}_{\tau} = \mathbf{W}_\varrho \tanh(\mathbf{W}_{md} [\mathbf{v}_\tau, \mathbf{h}_t] + \mathbf{b}_{md}), \\ & \mathbf{\hat h}_t = \sum_{\tau} \mathbf{\bar \varrho}_{\tau} * \mathbf{v}_{\tau} , \mathrm{where} \ \mathbf{\bar \varrho}_{\tau} = \frac{ \exp( \mathbf{\varrho}_{\tau} ) }{\sum_{\tau} \exp( \mathbf{\varrho}_{\tau} ) }, \end{align} where $ \mathbf{W}_\varrho, \mathbf{W}_{md}$ are linear transformations and they together model the additive attention \cite{Cho_Merrienboer_Bahdanau_Bengio_2014} with the bias term $\mathbf{b}_{md}$. $\mathbf{\bar \varrho}$ is the attention weights. The $t$th decoding process can be formulated as: \begin{align} \mathbf{h}_{t+1} = GRU(\mathbf{h}_{t}, [\mathbf{\hat w}_t, \mathbf{\hat h}_t]), \end{align} where $\mathbf{\hat w}_t$ denotes the embedding of the predicted word $w_t$ at step $t$. For training objectives, we take the standard cross-entropy loss: \begin{align} \mathcal{L} = - \sum_{t} \log p\left(w_t\right). \end{align} \section{Experiments} \subsection{Product-oriented Video Datasets} \label{Data Collection} \vpara{Data Collection} We collect two large-scale product-oriented video datasets, \textit{i}.\textit{e}., buyer-generated fashion video dataset (BFVD) and fan-generated fashion video dataset (FFVD) for \textit{product-oriented} video captioning research. Data samples from both datasets are collected from Mobile Taobao. We collect the videos, the descriptions, and the associated product aspects to form the datasets. Each recommended video has been labeled as buyer-generated or fan-generated by the platform. These two kinds of data are originally generated by users with different background knowledge and intentions. Buyers often focus on the general appearance, salient characteristics, and emotions while descriptions generated by fans often reflect deep insights and understandings about the products. Therefore, we regard these two kinds of videos as individual datasets since they may pose different challenges for modeling. Data collected from real-world scenario may contain noises and we select videos with PV (page views) over 100,000 and with CTR (click through rate) larger than 5\%. Videos and descriptions of high quality are more likely to be recommended (more PVs) and clicked (bigger CTR). \begin{table}[t] \centering \caption{ Comparing BFVD and FFVD with exiting video-to-text datasets (e-comm stands for e-commerce). } \setlength{\tabcolsep}{2.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|cccccc} \multicolumn{1}{c|}{Dataset} & Domain & \#Videos & \#Sentence & \#Vocab & Dur(hrs) \\ \hline \hline MSVD \cite{Chen_Dolan_2011} & open & 1,970 & 70,028 & 13,010 & 5.3 \\ TACos \cite{Regneri_Rohrbach_Wetzel_Thater_Schiele_Pinkal_2013} & cooking & 123 & 18,227 & 28,292 & 15.9 \\ TACos M-L \cite{Rohrbach_Rohrbach_Qiu_Friedrich_Pinkal_Schiele_2014} & cooking & 185 & 14,105 & - & 27.1 \\ MPII-MD \cite{Rohrbach_Rohrbach_Tandon_Schiele_2015} & movie & 94 & 68,375 & 24,549 & 73.6 \\ M-VAD \cite{Torabi_Pal_Larochelle_Courville_2015} & movie & 92 & 55,905 & 18,269 & 84.6 \\ VTW \cite{Zeng_Chen_Niebles_Sun_2016} & open & 18,100 & - & 23,059 & 213.2 \\ MSR-VTT \cite{Xu_Mei_Yao_Rui_2016} & open & 7,180 & 200,000 & 29,316 & 41.2 \\ Charades \cite{Sigurdsson_Varol_Wang_Farhadi_Laptev_Gupta_2016} & human & 9,848 & - & - & 82.01 \\ ActivityNet \cite{Krishna_Hata_Ren_FeiFei_Niebles_2017} & activity & 20,000 & 10,000 & - & 849 \\ DiDeMo \cite{Hendricks_Wang_Shechtman_Sivic_Darrell_Russell_2017} & open & 10,464 & 40,543 & - & - \\ YouCook2 \cite{Zhou_Xu_Corso_2018} & cooking & 2,000 & - & 2,600 & 175.6 \\ VATEX \cite{Wang_Wu_Chen_Li_Wang_Wang_2019} & open & 41,300 & 826,000 & 82,654 & - \\ \hline \hline BFVD & e-comm & 43,166 & 43,166 & 30,846 & 140.4 \\ FFVD & e-comm & 32,763 & 32,763 & 34,046 & 252.2 \\ \hline \end{tabular} \vspace{-0.4cm} \label{table:Data} \end{table} \vpara{Data Statistics} As a result, we collect 43,166 <video, aspects, description> triplets in BFVD and 32,763 triplets in FFVD. The basic statistics and comparison results with other frequently used video captioning datasets are listed in Table \ref{table:Data}. The distinguishing characteristics of BFVD and FFVD are 1) these datasets can be viewed as an early attempt to promote video-to-text generation for the domain of e-commerce. 2) Concerning the total number and total length of videos, BFVD and FFVD are among the largest. 3) As for language data, BFVD and FFVD contain a large number of unique words, and the ratio of $\frac{\#Vocab}{\#Setences}$ is among the largest. These statistics indicate that BFVD and FFVD contain abundant vocabulary and little repetitive information. 4) BFVD and FFVD associate corresponding product aspects, which permit not only the product-oriented video captioning research as we do but also a broad range of product-related research topics such as multi-label video classification for e-commerce. \vpara{Data Preprocessing} For descriptions, we remove the stop words and use Jieba Chinese Tokenizer \footnote{\url{https://github.com/fxsjy/jieba}} for tokenization. To filter out those noised expressions such as brand terms and internet slang terms, we remove tokens with frequency less than 30. Descriptions with tokens more than 30 will be shortened, and the max length for product aspects is 12. Following the standard process, we add a \texttt{<sos>} at the beginning of each description and a \texttt{<eos>} at the last. For videos, we inspect 30 frames for each video and extract the product-part features for each frame using this detector \cite{liu2018deep}\footnote{\url{https://github.com/fdjingyuan/Deep-Fashion-Analysis-ECCV2018}} pre-trained on this dataset \cite{Liu_Yan_Luo_Wang_Tang_2016}. For each frame, the product-part detector will produce a prediction map with the same width/height as the input frame. Each pixel value at a particular part-channel (note that the number of channels is the same as the number of product parts) indicates how likely this pixel is belonging to this part. We then apply the prediction map on the activations obtained from an intermediate layer (by resizing the probability map first, apply softmax on this map to obtain probability weights and finally weighted sum over the intermediate activations per part channel) to obtain part features. Specifically, we use the activations from \textit{pooled\_5} and result in $8 \times 64$ features vectors for 8 product-parts. We mean-pool the activations from layer \textit{conv4} as the representation for each frame. For train/val/test split, we employ a random sampling strategy and adopt 65\%/5\%/30\% for the training set, validation set, and testing set, respectively. Therefore, we have 21,554/1,658/9,948 data samples for FFVD and 28,058/2,158/12,950 data samples for BFVD. \begin{table*}[t] \centering \caption{ Qualitative results of the proposed \textit{Poet} with diverse competitors. Comparisons concern generation quality (NLG metrics), product aspect capturing, and generation diversity. \textit{Poet} achieves the best results on two \textit{product-oriented} video captioning datasets. } \setlength{\tabcolsep}{6.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{c|l|cccc|c|cc} & & \multicolumn{4}{c}{NLG Metrics} & \multicolumn{1}{c}{Aspect} & \multicolumn{2}{c}{Lexical Diversity} \\ \multicolumn{1}{c|}{Dataset} & \multicolumn{1}{c|}{Methods} & BLEU-1 & METEOR &ROUGE\_L & CIDEr & Prediction & $n=4 (\times 10^5)$ & $n=5 (\times 10^6)$ \\ \hline \hline \multirow{7}{*}{BFVD} & AA-MPLSTM & 11.31 & 6.02 & 10.08 & 9.76 & 54.31 & 2.94 & 3.20 \\ & AA-Seq2Seq & 11.96 & 6.14 & 11.05 & 11.67 & 54.85 & 4.74 & 4.52 \\ & AA-HRNE & 11.82 & 5.98 & 10.23 & 11.86 & 55.98 & 5.02 & 4.73 \\ & AA-SALSTM & 11.78 & 5.88 & 10.18 & 11.57 & 55.93 & 5.10 & 4.90 \\ & AA-RecNet & 11.17 & 6.01 & 11.05 & 11.67 & 54.94 & 5.06 & 4.92 \\ & Unified-Transformer & 11.28 & 6.32 & 10.43 & 12.66 & 55.12 & 3.35 & 2.91 \\ & PointerNet & 12.09 & 6.34 & 11.19 & 12.58 & 56.01 & \textbf{5.36} & 5.02 \\ \cmidrule{2-9} \cmidrule{2-9} & \iffalse\rowcolor{SeaGreen1!20!}\fi \textit{Poet} & \textbf{14.55} & \textbf{7.11} & \textbf{12.13} & \textbf{13.48} & \textbf{56.69} & 5.16 & \textbf{5.10}\\ \hline \multirow{7}{*}{FFVD} & AA-MPLSTM & 14.52 & 7.96 & 13.85 & 17.38 & 61.63 & 3.15 & 3.22 \\ & AA-Seq2Seq & 14.77 & 7.87 & 13.74 & 18.54 & 62.01 & 4.08 & 3.69 \\ & AA-HRNE & 13.58 & 6.75 & 12.06 & 20.10 & 60.39 & 4.32 & 3.88 \\ & AA-SALSTM & \textbf{16.25} & 7.72 & 14.63 & 19.46 & 62.17 & 4.58 & 4.20 \\ & AA-RecNet & 15.11 & 8.03 & 14.18 & 19.08 & 62.21 & 4.45 & 4.02 \\ & Unified-Transformer & 14.39 & 7.42 & 13.45 & 21.00 & 62.01 & 3.39 & 2.90 \\ & PointerNet & 15.28 & 7.77 & 14.02 & 18.85 & 61.30 & 4.40 & 3.99 \\ \cmidrule{2-9} \cmidrule{2-9} & \iffalse\rowcolor{SeaGreen1!20!}\fi \textit{Poet} & 16.04 & \textbf{8.06} & \textbf{14.82} & \textbf{21.71} & \textbf{62.70} & \textbf{4.60} & \textbf{4.25} \\ \hline \end{tabular} \label{tab:qualitative} \vspace{-0.3cm} \end{table*} \subsection{Evaluation Measurements} \begin{sloppypar} \vpara{Natural Language Generation Metrics} Concretely, we adopt four numerical assessment approaches, BLEU-1 \cite{papineni2002bleu} for sanity check, METEOR \cite{banerjee2005meteor} based on unigram precision and recall, ROUGE\_L \cite{lin2004rouge} based on the longest common subsequence co-occurrence, CIDEr \cite{vedantam2015cider} based on human-like consensus. With the user-written sentences as references, these measurements can help evaluate the generation fluency as well as whether the generation model captures the user-preferred highlights depicted in the video. \end{sloppypar} \vpara{Product Aspects Prediction} Since leverging product aspects as knowledge is essential for product video understanding, it is necessary to evaluate how well the generation model captures such information. We follow the evaluation protocol proposed in KOBE \cite{Chen_Lin_Zhang_Yang_Zhou_Tang_2019} and view the aspects prediction accuracy as the indicator. \vpara{Lexical Diversity} The above measurements mainly concern the generation quality (fluency, highlight capturing, and aspects capturing), and they cannot explicitly evaluate the generation diversity. As we know, repetitive phrases and general descriptions can be less attractive for potential buyers. Therefore, as in KOBE \cite{Chen_Lin_Zhang_Yang_Zhou_Tang_2019}, we view the number of unique n-grams of the sentences generated when testing as the indicator of the generation diversity. We empirically choose 4-grams and 5-grams, following KOBE. \subsection{Comparison Baselines} To evaluate the effectiveness of \textit{Poet}, we compare it with various video description baselines. Since most baselines concern only video information, we re-implement these baselines and add separate encoders (with a similar structure to their video encoders) for product aspect modeling. \begin{enumerate} \item \textit{AA-MPLSTM}. Aspect-aware MPLSTM (originally \cite{Venugopalan_Xu_Donahue_Rohrbach_Mooney_Saenko_2015}) employs two mean-pooling encoders and concatenate the encoded vectors as the decoder input. \item \textit{AA-Seq2Seq}. Aspect-aware Seq2Seq (originally \cite{Venugopalan_Rohrbach_Donahue_Mooney_Darrell_Saenko_2015}) uses an additional RNN encoder for aspect modeling. \item \textit{AA-SALSTM}. Aspect-aware SALSTM (originally \cite{Yao_Torabi_Cho_Ballas_Pal_Larochelle_Courville_2015}) equip the RNN decoder in AA-S2VT with soft attention. \item \textit{AA-HRNE}. Aspect-aware HRNE (originally \cite{Pan_Xu_Yang_Wu_Zhuang_2016}) differs the AA-S2VT by employing hiearachical encoders. \item \textit{AA-RecNet}. For Aspect-aware RecNet, we re-construct not only the frame features (as in RecNet \cite{Wang_Ma_Zhang_Liu_2018}) but also the aspect features. Also, there is an additional aspect encoder. \item \textit{Unified-Transformer}. We modify the Unified Transformer \cite{Ma_Cui_Dai_Wei_Sun_2019} by replacing the live comments encoder with an aspect encoder. \item \textit{PointerNet}. We equip the Seq2Seq model with the entity pointer network, proposed by Whitehead \textit{et al}. \cite{Whitehead_Ji_Bansal_Chang_Voss_2018}, for product aspect modeling. \end{enumerate} \subsection{Performance Analysis} In this section, we examine the empirical performance of \textit{Poet} on two product-oriented video datasets, \textit{i}.\textit{e}., BFVD and FFVD. We concern a couple of the following perspectives. \vpara{Overall generation quality}. By generation quality, we mean both the generation fluency and whether the generated sentences capture user-preferred product characteristics. Referenced-based natural language metrics can help reflect the performance since they directly compare the generated sentences to what the video uploaders describe. In a nutshell, the clear improvement over various competitors and across four different metrics demonstrate the superiority of the proposed \textit{Poet} (as shown in Table \ref{tab:qualitative}, NLG metrics). Specifically, on BFVD, we obtain +2.46 BLEU (relatively 20.3\%) and +0.77 METEOR (relatively 12.1\%) improvement over the best (PointerNet) among the competitors. For FFVD, we observe that fan-generated videos sometimes concern collections of clothes and present them for a specific theme (such as \texttt{dressing guide} or \texttt{clothes that make you look fit}) while only one of the clothes (in the same video) is associated with product aspects. Such a phenomenon may introduce noise and hurt the performance of models designed for single-product modeling. Nevertheless, \textit{Poet} achieves the best performance across the most metrics. We attribute the clear advantage to \textbf{1) product-oriented video graph modeling.} \textit{Poet} represents product parts across frames as spatial-temporal graphs, which can better capture the dynamic change of these characteristics along the timeline and find out those distinguishing highlights that are preferred by the user (\textit{e}.\textit{g}., distinguishing characteristics of one product part can be highlighted in higher frequencies or with close-up views). In contrast, previous models (including the RNN-based and the transformer-based) are inferior in capturing such characteristics since they either model only the frame-level features without fine-grained analysis or only model the videos in a sequential way. \textbf{2) Knowledge enhanced video analysis.} \textit{Poet} firstly perform hard attention to remove \textit{noise aspects} that are of no use for video analysis and then perform dynamic memory writing/attending to progressively enhance the spatial-temporal inference process. This design can be superior over other designs like concatenation or the complex PointerNet design. We will further analyze different knowledge incorporation methods in \textit{Aspect Capturing} and \textit{Ablation studies}. \vpara{Aspect Capturing} Knowledge incorporation methods can be categorized into three sub-groups: 1) \textbf{AA- methods.} We transform a video captioning method into a AA-method by adding a separate encoder, which has a similar structure to the existing visual encoder (such as the hierarchical RNN encoder in HRNE), for the product aspect modeling. We concatenate the encoded aspects feature and the encoded visual feature as the initial decoder input. 2) \textbf{Decoding-oriented methods.} Unified-transformer and PointerNet are decoding-oriented knowledge incorporation methods, which introduce the external knowledge in the decoding stage as an implicit or explicit reference. Unified-transformer implicitly utilizes the knowledge using the multi-head attention mechanism before prediction. PointerNet explicitly view the attended entities (product aspects) as candidate words for prediction and combine the attention weights and the vocabulary probability distribution before prediction. 3) \textbf{Poet}: the analysis-oriented method which aims to obtain a better understanding of the videos with the external knowledge as guidance. The aspect capturing scores are shown in Table \ref{tab:qualitative} (Aspect Prediction). It can be seen that 1) the analysis based method (\textit{Poet}) achieves the best performance on two datasets. As we illustrated earlier, the \textit{product-oriented} video captioning requires a fine-grained analysis of distinguishing characteristics depicted in the video, and the product aspects can better serve as the prior background knowledge to obtain such kind of analysis. 2) The decoding-oriented methods cannot beat the AA- methods on FFVD. This is a reasonable result since the product aspect can be associated with only one cloth in the fan-generated video (as we stated in the \textit{Overall Generation Quality}) and thus directly \textit{borrowing} the aspect words in the decoding may introduce unnecessary local biases. \begin{table}[!t] \centering \caption{ Human judgements on the proposed \textit{Poet} and two typical architectures concerning three task-oriented indicators. } \setlength{\tabcolsep}{5.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|ccc} \multicolumn{1}{c|}{Models} & Fluency & Diversity & Overall Quality \\ \hline \hline AA-RecNet & 2.73 & 3.49 & 3.04 \\ AA-Transformer & 2.66 & 3.37 & 2.95 \\ \hline \hline \textit{Poet} & \textbf{2.88} & \textbf{3.59} & \textbf{3.15} \\ \hline \end{tabular} \label{table:HumanEval} \end{table} \vpara{Generation Diversity} The number of generated unique n-grams of different methods are listed in Table \ref{tab:qualitative} (Lexical Diversity). Besides the generation quality, \textit{Poet} can also generate relatively diversified sentences. The PointerNet achieves the best concerning 4-grams in BFVD, which is reasonable since they externally consider the aspects as candidate decoding words. \begin{figure*}[t] \begin{center} \includegraphics[width=\textwidth]{./figures/Case_Reduced} \caption{ Generation samples of \textit{Poet}, AA-Transformer and AA-Recnet on the FFVD testing set. We present the filtered aspects and the corresponding scores in the proposed knowledge leveraging module. } \vspace{-0.4cm} \label{fig:case} \end{center} \end{figure*} \vpara{Human Evaluation} We agree with AREL \cite{Wang_Chen_Wang_Wang_2018} that human judgement is essential for stable evaluation especially when the captions are highly diverse and creative. Following the human evaluation protocol of KOBE \cite{Chen_Lin_Zhang_Yang_Zhou_Tang_2019} and Li \textit{et al}. \cite{Li_Monroe_Shi_Jean_Ritter_Jurafsky_2017}, we randomly select 1,000 instances from the testing set and distribute them to human annotators. The results are listed in Table \ref{table:HumanEval}. Compared to the typical Transformer-based design and RNN-based design (AA-RecNet), \textit{Poet} generates more fluent (fluency +0.22/+0.15) and diversified (diversity +0.22/+0.10) descriptions. The indicator \textit{Overall Quality} reflects whether the descriptions capture the product characteristics the video uploader hightlights in the video. In terms of this metric, \textit{Poet} still demonstrates a clear performance improvement over AA-Transformer/AA-RecNet by +0.20/+0.11. \begin{table}[!t] \centering \caption{ Ablation study on the generation quality of Knowledge Leveraging module and the pointer mechanism. } \setlength{\tabcolsep}{3.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{c|l|cccc} \multicolumn{1}{c|}{Dataset} & \multicolumn{1}{c|}{Methods} & BLEU-1 & METEOR &ROUGE\_L & CIDEr \\ \hline \hline \multirow{3}{*}{BFVD} & \iffalse\rowcolor{SeaGreen1!20!}\fi \textit{Poet} & \textbf{14.55} & \textbf{7.11} & \textbf{12.13} & \textbf{13.48} \\ & \ \ + pointer & 13.26 & 6.60 & 11.53 & 13.18 \\ & \ \ \ \ \ \ - KL & 12.43 & 6.48 & 10.86 & 12.25 \\ \hline \multirow{3}{*}{FFVD} & \iffalse\rowcolor{SeaGreen1!20!}\fi \textit{Poet} & 16.04 & \textbf{8.06} & \textbf{14.82} & \textbf{21.71} \\ & \ \ + pointer & \textbf{16.13} & 7.79 & 14.50 & 20.57 \\ & \ \ \ \ \ \ - KL & 15.53 & 7.89 & 14.18 & 19.73 \\ \hline \end{tabular} \label{tab:ablation_knowledge} \vspace{-0.3cm} \end{table} \vpara{Case Study} Figure \ref{fig:case} shows two generation cases on the FFVD testing set. In summary, \textit{Poet} generates more fluent and complete sentences than the AA-Transformer and AA-Recnet, which are typical architectures of transformer-based and RNN-based models, respectively. For example, the phrases (such as "\texttt{to in}") generated by AA-Transformer in the first case are confusing, and the whole sentence is incomplete. Besides the generation fluency, \textit{Poet} can generate sentences that better capture the product aspects. In the second case, the phrases "\texttt{soft}" and "\texttt{young fashionistas}" are derived from the aspects "\texttt{soft elastic}", "\texttt{youth}", and "\texttt{fashion}". To further demonstrate the effectiveness of the proposed knowledge leveraging module, we extract and present the filtered aspects with the corresponding scores. We observe that the proposed KL module successfully filter those aspects of no use, such as product sizes (\texttt{XL}) and the release year \textit{2019} in the first case, and the scores of remaining aspects are consistent to the contribution to the final description. Also, Poet can generate creative while accurate words (\textit{e}.\textit{g}., \texttt{casual}) beyond the input aspects set based on its understanding of the video. \subsection{Ablation Studies} We conduct ablation studies to verify the effectiveness of proposed modules within \textit{Poet}. We mainly concern the following two issues: \vpara{When modeling the video as a graph, does the knowledge leveraging module outperform the pointer mechanism?} To answer this question, we construct two models, \textit{i}.\textit{e}., the Poet+pointer model, which directly adds the pointer mechanism to \textit{Poet}, and the Poet+pointer-KL model, which remove the proposed knowledge leveraging module from Poet+pointer model. The experiment results on two datasets are listed in Table \ref{tab:ablation_knowledge}. It can be seen that 1) adding pointer mechanism may hurt the performance in most cases. This further demonstrates the superiority of the analysis-oriented knowledge incorporation method for \textit{product-oriented} video captioning. 2) removing the knowledge leveraging module leads to a clear performance drop (-0.93 CIDEr and relatively 7\% in BFVD), which shows the effectiveness of the proposed module. \vpara{Do all the proposed modules improve the generation quality?} we surgically remove the proposed modules and individually test the performance on BFVD. Table \ref{table:ablation_module} shows the numeric results. We note that removing the KL (knowledge leveraging) module means ignoring the external product aspects totally. The result indicates the merit of leveraging the KL module to enhance the fine-grained video analysis. By "-SPI", we replace the SPI (spatial-temporal inference) module by the popular Graph Convolutional Networks \cite{Kipf_Welling_2017}. The improvement over the GCN verifies the effectiveness of the spatial-temporal inference module. \begin{table}[!t] \centering \caption{ Ablation study of the proposed \textit{Poet} by surgically removing controlling components. } \setlength{\tabcolsep}{2.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|cccc} \multicolumn{1}{c|}{Models} & BLEU-1 & METEOR &ROUGE\_L & CIDEr \\ \hline \hline \textit{Poet} & \textbf{14.55} & \textbf{7.11} & \textbf{12.13} & \textbf{13.48} \\ \hline \ \ - KL & 11.85 & 6.34 & 10.58 & 12.09 \\ \ \ \ \ - STI & 11.90 & 6.09 & 10.31 & 9.52 \\ \hline \end{tabular} \vspace{-0.4cm} \label{table:ablation_module} \end{table} \section{Conclusion} In this paper, we propose to narrate the user-preferred product characteristics depicted in user-generated product videos, in natural language. Automating the video description generation process helps video recommendation systems in e-commerce to leverage the massive user-generated videos for product promotion. We propose a novel framework named \textit{Poet} to perform knowledge-enhanced spatial-temporal inference on product-oriented video graphs. We conduct extensive experiments including qualitative analysis, ablation studies, and numerical measurements concerning generation quality/diversity. Experiment results show the merit of video graph modeling, the proposed spatial-temporal inference module, and the knowledge leveraging module for the \textit{product-oriented} video captioning problem. We collect two user-generated fashion video datasets associated with product aspects to promote not only the \textit{product-oriented} video captioning research, but also various product-oriented research topics such as product video tagging. \section{ACKNOWLEDGMENTS} \begin{sloppypar} The work is supported by the NSFC (61625107, 61751209, 61836002), National Key R\&D Program of China (No. 2018AAA0101900, No. 2018AAA0100603), Zhejiang Natural Science Foundation (LR19F020006), Fundamental Research Funds for the Central Universities (2020QNA5024), and a research fund supported by Alibaba. \end{sloppypar}
{'timestamp': '2020-08-18T02:16:44', 'yymm': '2008', 'arxiv_id': '2008.06880', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06880'}
arxiv
\section{Related Works} Detection of misinformation has become an emerging research topic that is attracting the general public and researchers. In recent years, there is a requirement of a practical approach for the success of the fake news detection problem, which has caused a significant challenge to modern society. Each research paper embraces its ideas related to the different strategies to solve this problem. A substantial group of studies fabricates the concept of developing machine learning classifiers \cite{goyalgait} to automatically detect the misinformation using a variety of news characteristics. Some prior studies show that the performance of fake news deception model improves when using features based on the linguistic characteristics derived from the text content of news stories. Previous work \cite{Castillo:11} has shown that newsworthy articles tend to contain URLs and to have deep propagation trees. They built a classification model based on a set of linguistic features such as special characters, sentiment positive/negative words, emojis, etc. to determine information credibility on twitter. Context-Free Grammar(CFG) parse trees \cite{Feng:12} based on shallow lexical-syntactic features were applied to build the detection model. Lexicon patterns and part-of-speed tags \cite{Qazvinian:11} were also used. Named entities, retweet ratio, and clue keywords \cite{Takahashi:12} were analyzed for the identification of rumor tweets on twitter. Another study used linguistic content such as swear words, emotion words, and pronouns \cite{Gupta:14} to assess the credibility of a tweet. Language style and source reliability of articles \cite{Popat:16} were also used in reporting the claim to determine its likelihood. To differentiate fake news from legitimate news, lexical, syntactic, and semantical \cite{Rosas:18} information was used. A group of other approaches builds fake news detection model based on temporal-linguistic features. News entities \cite{Shu:18} are categorized into content, social, and temporal dimensions reveals mutual relations and dependencies that were used to perform fake news dissemination. A classifier \cite{Zhao:15} was build based on inquiry phrases extracted from user comments. Prior work \cite{Buntain:2017} has shown that leveraging non-expert, crowdsourced workers provides a useful way to detect fake news in popular Twitter threads. The comprehensive technique of identifying fake news on social media \cite{Shu:19} included fake news characterizations on psychology and social theories. Bimodal variational autoencoder with a binary classifier \cite{Khattar:19} based on multimodal (textual+visual)\cite{10.1007/978-3-319-46478-7_12,shah2017multimodal,8290832} information helped classify posts as fake or not. The work of \cite{Rashkin:17} depicted The significance of stylistic cues was described in determining the truthfulness of text. All scraps that contain propaganda techniques and their types \cite{Martino:19} were detected to design a method that performs fine-grained analysis of texts. Another group of researchers \cite{shivangi:19} exploited both the textual and visual features of an article. In \cite{parikh:19}, the framework was proposed based on information captured from an image\cite{8269367,8099896}, processed, and compared the information with the trusted party was used to detect tampered or photoshoot tweets. \begin{figure*} \centering \includegraphics[width=1\linewidth]{images/overview2.pdf} \caption{Flowchart shows how the features are extracted from the news article and then fed to the classifier}\label{fig:overview} \end{figure*} In this paper, we present the extraction of novel features based on Grammarly, Spinbot, and the GloVe-based model. To the best of our knowledge, no previous work has used this kind of approach in extracting features for fake news detection \cite{singhal2019spotfake,singhal2020spotfake+}. \section{Proposed Method} This section precisely describes how we utilize the Spinbot, Grammarly, and GloVe tools to develop a robust yet simple fake news detection system. We give overview of our proposed approach in the Figure~\ref{fig:overview}. First of all, we paraphrase the original article (denoted as $o_i$) and obtain a paraphrased article (denoted as $p_i$). Then, we extract Grammarly features for both the original article and the paraphrased article. Let's denote such a feature extraction function as $f_{gr}(\cdot)$. Similarly, we obtain GloVe based features (denoted as $f_{gl}(\cdot)$) for both original and paraphrased articles. In addition to these proposed features, we also extract some essential features ($f_{es}(\cdot)$) like TF-IDF, emotion, lexical, and so on, again, for both original and paraphrased articles. We concatenate \cite{7484309} these features into $f$ as shown below: \begin{equation} f(o_i,p_i)=f_{gr}(o_i)\cdot f_{gl}(o_i)\cdot f_{es}(o_i)\cdot f_{gr}(p_i)\cdot f_{gl}(p_i)\cdot f_{es}(p_i) \end{equation} which is then fed to the random forest classifier (denoted by $RF\big(\cdot\big)$ function) to output the prediction $y_i$, fake news or real news, as shown below: \begin{equation} y_i=RF\big(f(o_i,p_i)\big). \end{equation} where we essentially predict the authenticity of a given original article and its paraphrased article using a $RF$ model learned through training on labeled data. Let us now discuss each of these steps in greater detail one-by-one. \subsection{Spinbot Paraphrasing} We use paraphrasing to obtain a paraphrased content that looks scholarly. Assuming persons who spread fake news are not so scholarly, such paraphrasing serves two purposes in the false news detection. If they did not use such tools, the paraphrased article would be too distant from the original one, in terms of the features we develop. Also, if they did use it, they will copy-paste the paraphrased article, leading to too much closeness. Either way, fake articles will be distinguishable from real articles that may lie somewhere in-between, neither too close nor too distant. They would not be too close because such automated tools may not completely capture the writer's real intention; so, the writer will change it a bit. We use Spinbot\footnote{https://spinbot.com/} tool for this paraphrasing task. Spinbot is a free automatic article spinning tool that rewrites the human-readable text into additional, readable text and helps in solving problems in optimizing content generation. Spinbot allows us to copy text and paste it into a text box. After selecting a couple of basic options and confirming that one is human, users receive an output of a paraphrased version of the original text entered in the text box below. This tool is vibrant and sophisticated; it makes the content look very scholarly. It rephrases the text by spinning textual data of length up to 10,000 characters in a single go. Spinbot replaces many words with their synonyms to come up with plausibly ``new" content. Spinbot provides unique, quality textual content that can quickly acquire legitimate web visibility in terms of human readership and search engine exposure. Let's denote this tool as $SP$ function that takes $o_i$ as input and outputs $p_i$, as mentioned in Fig.~\ref{fig:overview} and below. \begin{equation} p_i=SP(o_i) \end{equation} \begin{table*} \centering \caption{Grammarly features with their descriptions} \begin{tabular}{ |p{4 cm} | p{12 cm}| } \hline \textbf{Grammarly Feature} & \textbf{Description} \\ \hline Contextual Spelling & This Grammarly feature helps identify misspelled words in the text document and suggests proper spellings related to misspelled words. \\ \hline Grammar & This feature simplifies the writing process by detecting grammar mistakes that include inappropriate use of articles, verb tenses, and misplaced modifiers. \\ \hline Sentence Structure & There are four sentence structures present in the English literature: simple sentences, complex sentences, compound sentences, and complex-compound sentences. This feature checks the proper usage of sentence structure in articles as it detects and prompts the suggestions for correcting missing verbs, faulty parallelism, and incorrect adverb placement. \\ \hline Punctuation & Misplaced punctuation changes the meaning of the sentences at a higher level. This feature spots misplaced punctuation and makes real-time suggestions to correct them. \\ \hline Style & There are four major writing styles: expository, descriptive, persuasive, and narrative. The style feature analyzes the article to improve the communicating method with readers. \\ \hline Vocabulary Enhancement & Grammarly flags vague and redundant words that reduce the value of the content and suggests more engaging synonymous to add variety to articles. \\ \hline Plagiarism & Grammarly's plagiarism checking tool checks 16 billion other articles across the web to correctly identify and cite text that is not 100\% original. \\ \hline Word Count & This feature provides general metrics that include the characters count, word count, and sentence count of the writings. It also renders the time required in reading and speaking the article. \\ \hline Readability & These features indicate text understandability. It computes words and sentences length. It also enumerates the Readability score that measures the reader's likeliness to be understood. \\ \hline Vocabulary & It measures vocabulary depth by identifying words that are not present in the 5,000 most common English words. It also measures the unique words by calculating the number of individual words. \\ \hline \end{tabular} \label{fig:grammarly-features-description} \end{table*} \subsection {Grammarly Features Extraction} The first set of features we extract are mistakes-based, assuming the English writing of the persons who spread fake news is not that good. For capturing these mistakes, we use Grammarly. Grammarly is a proofreading application that uses artificial intelligence and natural language processing in developing tools to detect mistakes in grammar, spelling, punctuation, word choice, and style. It is a comprehensive writing tool that provides real-time suggestions to correct these errors. Grammarly checks writings on various aspects such as tone detection, confident language, politeness, formality level, and inclusive language before making a decision. Grammarly scans the document with an AI assistant, automatically detects mistakes, suggests corrections, and shows the rationale behind those suggestions. Interestingly, it can detect up to 250 types of errors. Table~\ref{fig:grammarly-features-description} shows Grammarly's significant features with their description \cite{grammarly:19}. Table~\ref{fig:grammarly-features-comparison} shows the Grammarly Features extracted from fake and legitimate news articles shown in Table~\ref{tab:example_fake_legitimate}. There are numerous features for which the values are very different for these examples, thanks to the assumption made. \begin{table \centering \caption{This table shows Grammarly features extracted for fake and legitimate news articles mentioned in Table~\ref{tab:example_fake_legitimate} where $A$ signifies fake news and $B$ signifies legitimate news} \resizebox{0.45\textwidth}{!}{% \begin{tabular}{ | p{3 cm}|p{2 cm} | p{2 cm} | } \hline \textbf{Grammarly Features} & \textbf{News A} & \textbf{News B} \\ \hline {\bf Overall Score} & 74 & 97 \\ {\bf Correctness Alerts} & 7 & 0 \\ {\bf Clarity} & mostly clear & a bit unclear \\ {\bf Clarity Alerts} & 2 & 2 \\ {\bf Engagement} & engaging & very engaging \\ {\bf Engagement Alerts} & 1 & 0 \\ {\bf Delivery} & just right & just right \\ {\bf All alerts} & 10 & 2 \\ {\bf Characters} & 562 & 476 \\ {\bf Words} & 106 & 71 \\ {\bf Sentences} & 5 & 4 \\ {\bf Reading Time} & 25 sec & 17 sec \\ {\bf Speaking Time} & 48 sec & 32 sec \\ {\bf Word Length} & 4.3 & 5.6 \\ {\bf Sentence Length} & 21.2 & 17.8 \\ {\bf Readability Score} & 72 & 58 \\ {\bf Unique Words} & 63 & 79 \\ {\bf Rare Words} & 18 & 29 \\ {\bf Plagiarism} & 0 & 90 \\ \hline \end{tabular}} \label{fig:grammarly-features-comparison} \end{table} \begin{figure* \centering \includegraphics[width=\textwidth]{images/GloVe.pdf} \caption{Glove-based Feature Generation}\label{fig:accumulator_vector_generate} \end{figure*} \subsection{Glove-based Feature Extraction} GloVe embedding is a popular word embedding algorithm. Given the word, it can output a numeric feature vector of $n$ dimensions. Since we need to classify articles, not words, we use a codebook approach to represent an article, as explained below. We first build a corpus using different words present in a domain. Let us say there is a total of $m$ words in the corpus. We use Glove to convert this corpus into an embeddings corpus, which can be seen as a matrix of dimensions $m\times n$, stacking all the feature vectors vertically. We then apply k-means \cite{macqueen1967some,7025663,7457899,jerripothula2017co,jerripothula2015group} on embeddings corpus to divide the matrix into $k$ clusters of feature vectors. We compute the means of feature vectors in different clusters and assign them as codes in our embeddings codebook. The idea is to develop a frequency-table depending upon how many times different words in an article fall close to different codes in our codebook. This frequency-table of the article is what we call as GloVe-based feature. Fig.~\ref{fig:accumulator_vector_generate} depicts our entire approach of generating the GloVe-based feature. \subsection{Essential Features Extraction} Our essential features can be classified into three categories: basic, TF-IDF, and emotion. Let us discuss each of them one-by-one. \subsubsection{Basic} We extract basic features set consisting of 7 types of lexical features includes Unique word count, Stopword count, URL count, Mean word length, Hashtag count, Numeric count, and Uppercase count for each news article. \subsubsection{TF-IDF} We extract unigrams and bigrams derived from the TF-IDF representation of each news article. Term Frequency Inverse Document Frequency (TF-IDF) \cite{Jones:04} gives us information on term frequency through the proportion of inverse document frequency. Words with a small-term rate in each document but have high possibility to appear in records with similar topics will have higher TF-IDF, while words like function words though frequently appear in every report, will have low TF-IDF because of lower inverse document frequency. \subsubsection{Emotion Lexicon} We perform sentiment analysis on the corpus of the news articles using Textblob \cite{textblob:18}. Sentiment analysis \cite{9153789} determines the attitude or the emotion of the writer, i.e., whether it is positive, neutral, or negative. The {\em sentiment} function of Textblob returns two properties, polarity, and subjectivity. Polarity returns float value, which lies in the range of [-1,1] where the ``1" stands for a positive statement, and ``-1" stands for a negative comment. Subjective sentences refer to personal opinion, emotion, or judgment, whereas objective refers to factual information. Subjectivity also returns a float number, which lies in the range of [0,1]. \subsection{Feature Concatenation and Predictive Modeling} Different features obtained for both the original and the paraphrased articles are all concatenated into a feature vector. We apply $5$-fold cross-validation to develop our random forest classifier for predicting whether an article is fake or real. Random forest is an ensemble tree-based learning algorithm that fits decision trees on the sub-samples of data and then aggregates the accuracy and controls over-fitting. \section{Experimental Results} In this section, we first describe different datasets and how we evaluate our approach. Then, we discuss different results we obtain by evaluating our method on these datasets while comparing them with the prior arts on these datasets. \subsection{Datasets and Evaluation} Our experiments are conducted on two publicly available benchmark datasets of fake news detection \cite{Rosas:18}, namely {\em Celebrity} and {\em FakeNewsAMT}. The FakeNewsAMT is collected by combining manual and crowdsourcing annotation efforts, including a corpus of 480 news articles, incorporating six news domains (i.e., Technology, Business, Education, Sports, Politics, and Entertainment). The news of the FakeNewsAMT dataset was obtained from various mainstream websites in the US, such as ABCNews, CNN, USAToday, NewYorkTimes, FoxNews, Bloomberg, and CNET, among others. Table~\ref{tab:example_fake_legitimate} shows examples of fake and legitimate news articles drawn from FakeNewsAMT dataset \cite{Rosas:18}. The Celebrity dataset contains 500 celebrity news articles, collected directly from the web. The news of the Celebrity dataset was obtained predominately from online magazines such as Entertainment Weekly, People Magazine, Radar Online, and other entertainment-oriented publications. The distribution of both the categories of news (fake and legitimate) are evenly distributed in both the datasets. We have extended these two datasets with our rich features. \begin{table* \caption{Example of fake and legitimate news article} \begin{center} \begin{tabular}{|p{1.5 cm}|p{2 cm}|p{12 cm}|} \hline \textbf{Article} & \textbf{Type} & \textbf{Content} \\ \hline $A$ & Fake News & Super Mario Run to leave app store The once popular Super Mario Run will be taken out of the Google play and apple app store on Friday. Nintendo says that shortly after its release the public stopped downloading the game when current players had spread the word that in order to play the entire game you had to make an in app purchase. Nintendo and Mario fans are appalled that Nintendo would release a game for free and then charge to play it. Nintendo says they will take the game back to the drawing board, and try and release a free version at a later time. \\ \hline $B$ & Legitimate News & How does nutrition affect children's school performance? As politicians debate spending and cuts in President Donald Trump's proposed budget, there have been questions about the effects of nutrition programs for kids. From before birth and through the school years, there are decades-old food programs designed to make sure children won't go hungry. Experts agree that the nutrition provided to millions of children through school meal programs is invaluable for their health. \\ \hline \end{tabular} \label{tab:example_fake_legitimate} \end{center} \end{table*} We analyze our method's performance using measurement metrics like Confusion Matrix and Accuracy. \begin{figure \centering \begin{minipage}{0.3\textwidth} \includegraphics[width=\textwidth]{images/confusion_matrix_celeb.pdf} \caption{Confusion matrix for the Celebrity dataset} \label{fig:confusion_matrix_celeb} \end{minipage} \hfill \begin{minipage}{0.3\textwidth} \includegraphics[width=\textwidth]{images/confusion_matrix_fake.pdf} \caption{Confusion matrix for the FakeNewsAMT dataset} \label{fig:confusionMatrix_amt} \end{minipage} \end{figure} \begin{table \centering \caption{Classification results for Celebrity dataset} \label{tab:results_celebrity} \resizebox{0.25\textwidth}{!}{% \begin{tabular}{ |l|l| } \hline \bf Features (\# features) & \bf Accuracy \\ \hline Glove based feature vector (200) & 0.71 \\ Basic (14) & 0.60 \\ Grammarly (19) & 0.63 \\ TF-IDF (100) & 0.76 \\ Emotion(4) & 0.57 \\ \hline All features (337) & 0.78 \\ \hline \end{tabular}} \end{table} \begin{table \centering \caption{Classification results for FakeNewsAMT dataset} \resizebox{0.25\textwidth}{!}{% \begin{tabular}{|l|l|} \hline \bf Features (\# features) & \bf Accuracy \\ \hline Glove based feature (200) & 0.56 \\ Basic (14) & 0.59 \\ Grammarly (19) & 0.96 \\ TF-IDF (100) & 0.54 \\ Emotion (4) & 0.48 \\ \hline All features (337) & 0.95 \\ \hline \end{tabular}} \label{tab:results_fakenews} \end{table} \subsection{Results and Comparisons} The confusion matrix corresponding to the Celebrity and FakeNewsAMT is given in Figure~\ref{fig:confusion_matrix_celeb} and ~\ref{fig:confusionMatrix_amt}. Tables~\ref{tab:results_celebrity} and ~\ref{tab:results_fakenews} give the 5-fold cross-validation accuracy which we get on Celebrity and FakeNewsAMT datasets, respectively, using individual and combined features. Notably, we achieve an accuracy of 78\% and 95\% when using all the features. It entails the fact that our proposed method predicts a high number of news articles correctly. Table~\ref{tab:celebrity_comparison} and ~\ref{tab:fakenewsamt_comparison} compares our results with the recent works \cite{Saikh:20}, \cite{Barua:19}, \cite{Rosas:18}, and \cite{Dabas:18}. Our results are quite competitive. \begin{table \centering \caption{Comparison of the proposed method with previous results for the Celebrity dataset} \resizebox{0.25\textwidth}{!}{% \begin{tabular}{|c|c|} \hline {\bf Model} & {\bf Test Accuracy (\%)} \\ \hline Linear SVM \cite{Rosas:18} & 76 \\ \hline F-NAD \cite{Barua:19} & {\bf 82.61} \\ \hline Model 1 \cite{Saikh:20} & 76.53 \\ \hline Model 2 \cite{Saikh:20} & 79 \\ \hline Proposed Work & 78 \\ \hline \end{tabular}} \label{tab:celebrity_comparison} \end{table} \begin{table \centering \caption{Comparison of the proposed method with previous results for the FakeNewsAMT Dataset} \resizebox{0.25\textwidth}{!}{% \begin{tabular}{|c|c|} \hline {\bf Model} & {\bf Test Accuracy (\%)} \\ \hline Linear SVM \cite{Rosas:18} & 74 \\ \hline EANN \cite{Dabas:18} & 75.6 \\ \hline F-NAD \cite{Barua:19} & 81 \\ \hline Model 1 \cite{Saikh:20} & 77.08 \\ \hline Model 2 \cite{Saikh:20} & 83.3 \\ \hline Proposed Work & {\bf 95} \\ \hline \end{tabular}} \label{tab:fakenewsamt_comparison} \end{table} \subsection{Cross-domain Analysis:} We perform cross-domain analysis to test how our proposed method helps distinguish fake news across different domains using all the features. We train our best performing classifier on the FakeNewsAMT dataset and test on the Celebrity dataset and vice-versa. Table~\ref{tab:cross_domain_analysis} captures the comparison of results obtained in cross-domain experiment. These results suggest that our method robustly outperforms the previous works. \begin{table} \centering \caption{Results Obtained in Cross-Domain Analysis for best performing classifier} \label{tab:cross_domain_analysis} \resizebox{0.45\textwidth}{!}{% \begin{tabular}{|l|l|l|c|} \hline \textbf{Training} & \textbf{Testing} & \textbf{System} & \textbf{Accuracy} \\ \hline \multirow{3}{*}{FakeNewsAMT} & \multirow{3}{*}{Celebrity} & Linear SVM \cite{Rosas:18} & 52\% \\ \cline{3-4} & & Model 2 \cite{Saikh:20} & 54.3\% \\ \cline{3-4} & & Proposed Work & \textbf{56\%} \\ \hline \multirow{3}{*}{Celebrity} & \multirow{3}{*}{FakeNewsAMT} & Linear SVM \cite{Rosas:18} & 65\% \\ \cline{3-4} & & Model 2 \cite{Saikh:20} & 68.5\% \\ \cline{3-4} & & Proposed Work & \textbf{70\%} \\ \hline \end{tabular}} \end{table} \subsection{Learning Curve} We also explore how the amount of data affects the classifier accuracy in identifying fake news. We plot the learning curves for the proposed approach and \cite{Rosas:18} on both the datasets using different fractions of data while training, as shown in figure~\ref{fig:learning_curve_celeb} and ~\ref{fig:learning_curve_amt}. These results suggest (1) our proposed method is outperforming the previous work \cite{Rosas:18}, and (2) our learning curve signifies a steady improvement in both the cases. It implies that a large number of training data has the potential to improve model performance. \begin{figure \centering \begin{minipage}{0.45\textwidth} \includegraphics[width=\textwidth]{images/learning_curve_celeb.pdf} \caption{Comparison of the results obtained in Learning Curve experiment with previous work for the Celebrity dataset} \label{fig:learning_curve_celeb} \end{minipage} \hfill \begin{minipage}{0.45\textwidth} \includegraphics[width=\textwidth]{images/learning_curve_fake.pdf} \caption{Comparison of the results obtained in Learning Curve experiment with previous work for the FakeNewsAMT dataset} \label{fig:learning_curve_amt} \end{minipage} \end{figure} \subsection{Multi-Domain Training and Domain-wise Testing} FakeNewsAMT dataset contains news articles of six domains (business, education, politics, technology, sports, and entertainment). In this experiment, we train our classifier on the five available domains out of six and test on the remaining domain news articles. Table~\ref{tab:multi_domain} depicts the comparison of results with previous works. It shows that (1) our model outperforms the past results established in this experiment and (2) our model is best performing in the Politics domain and performing worst in the Business domain. \begin{table \centering \caption{Comparison of Results Obtained in Multi-domain analysis for best performing classifier} \label{tab:multi_domain} \resizebox{0.35\textwidth}{!}{% \begin{tabular}{|l|l|c|} \hline \textbf{Test Domain} & \textbf{Model} & \textbf{Accuracy(\%)} \\ \hline \multirow{3}{*}{Technology} & Linear SVM \cite{Rosas:18} & 90 \\ \cline{2-3} & Model 2 \cite{Saikh:20} & 88.75 \\ \cline{2-3} & Proposed Work & \textbf{98.7} \\ \hline \multirow{3}{*}{Education} & Linear SVM \cite{Rosas:18} & 84 \\ \cline{2-3} & Model 2 \cite{Saikh:20} & 91.25 \\ \cline{2-3} & Proposed Work & \textbf{96.2} \\ \hline \multirow{3}{*}{Business} & Linear SVM \cite{Rosas:18} & 53 \\ \cline{2-3} & Model 2 \cite{Saikh:20} & 78.75 \\ \cline{2-3} & Proposed Work & \textbf{93.7} \\ \hline \multirow{3}{*}{Sports} & Linear SVM \cite{Rosas:18} & 51 \\ \cline{2-3} & Model 2 \cite{Saikh:20} & 73.75 \\ \cline{2-3} & Proposed Work & \textbf{96.2} \\ \hline \multirow{3}{*}{Politics} & Linear SVM \cite{Rosas:18} & 91 \\ \cline{2-3} & Model 2 \cite{Saikh:20} & 88.75 \\ \cline{2-3} & Proposed Work & \textbf{100} \\ \hline \multirow{3}{*}{Entertainment} & Linear SVM \cite{Rosas:18} & 61 \\ \cline{2-3} & Model 2 \cite{Saikh:20} & 76.25 \\ \cline{2-3} & Proposed Work & \textbf{96.2} \\ \hline \end{tabular}} \end{table} \section{Conclusion} In this paper, we addressed the task of identification of fake news using online tools. We introduced two new sets of features, one obtained through Grammarly and another obtained through Glove-based Feature. Additionally, we introduce the paraphrased article in this problem. Our study shows that the usage of features extracted using Grammarly, Spinbot, and GloVe-based model with other essential features such as Basic, Ngrams, and Emotion Lexicon improves the model performance significantly. The combination of these features achieved the best performance with the Random Forest classifier. Our proposed method obtains a testing accuracy of 78\% on the Celebrity news dataset and 95\% on the FakeNewsAMT dataset. \bibliographystyle{IEEEtran}
{'timestamp': '2020-08-18T02:15:49', 'yymm': '2008', 'arxiv_id': '2008.06854', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06854'}
arxiv
\section{Introduction} \label{sec:introduction} Recently, there has been a notable increase in the amounts of spatial data collected by satellites, social networks, and autonomous vehicles. The main method that data scientists use to process this data is through {\em interactive exploratory queries}; i.e., an ad-hoc query that should be answered in a fraction of a second. Existing studies show that a response time of more than a few seconds to these queries would negatively impact the productivity of the users~\cite{LH14}. Unfortunately, existing big-spatial data systems~\cite{eldawy2015spatial,yu2015geospark,XLY+16, BVK+17,TYM+16}, require way more than that to run even the simplest queries, hence, they cannot answer interactive exploratory queries. \begin{figure}[t] \centering \includegraphics[width=0.8\linewidth]{images/trade_off_line} \caption{Trade-off between accuracy and efficiency in AQP} \vspace{-10pt} \label{fig:trade_off} \end{figure} The most viable solution to the interactive exploration problem is approximate query processing (AQP) which uses a small data synopsis, e.g., a sample, to provide an approximate answer within a fraction of a second. This technique provides up-to three orders of magnitude speedup with a very high accuracy for several fundamental problems, including selectivity estimation, clustering, and spatial partitioning~\cite{siddique2019comparing}. Figure~\ref{fig:trade_off} depicts the trade-off between the {\em accuracy} of the approximate answer and the {\em efficiency}, i.e., running time, which is highly correlated with the sample size. Unfortunately, this accuracy/efficiency trade-off is very hard to calculate which discourages many users from using AQP systems. Existing solutions either provide answers without any performance guarantee or make unrealistic assumptions such as uniform distribution or independence between dimensions~\cite{siddique2019comparing,CE17,siddique2019euler++,siddique2018experimental,JAS00,AN00,OR93,agarwal2013blinkdb,LNS90,PIH+96,I93}. This problem is particularly challenging due to the intertwined relationship between the sample size, query parameters, algorithm logic, data distribution, and result accuracy. This paper proposes DeepSampling, a novel deep learning based model to predict the relationship between accuracy and relative sample size for AQP. The main challenge is how to build a model that works well for any spatial data distribution and query parameters. To solve this problem, we build a deep neural network that takes as input the query parameters and a histogram that represents the data distribution. This idea can work in two modes: \emph{1) given a sample size, it estimates the expected accuracy, or 2) given a desired accuracy, it calculates the required sample size.} The idea is generic and can work with any approximate algorithm by building a separate model for each one. DeepSampling can be integrated into any existing spatial data system that supports AQP. To the best of our knowledge, DeepSampling is the first system that supports predictable error AQP for spatial data analysis problems. We run an experimental evaluation on both synthetic and real data on the selectivity estimation problem and the results show that the proposed method can accurately model the delicate relationship between accuracy and sample size and is portable to many distributions. In summary, this paper makes following contributions. (1)~Design a deep learning model for predictable error and response time for AQP in spatial data analysis. (2)~Apply this model to the {\bf selectivity estimation} algorithm to solve two problems, sample size estimation and accuracy prediction. (3)~Validate the model through experiments and publish the pre-trained model for wide use. \section{Related Work} \label{sec:related_works} {\bf Approximate query processing:} AQP is a common method in many spatial data management systems. In AQP, the answer is estimated by executing the query on a small sample of the dataset, instead of scanning entire dataset. AQP is applied on several problems such as selectivity estimation, clustering, and spatial partitioning~\cite{siddique2019comparing}. For example, SpatialHadoop~\cite{eldawy2015spatial}, ScalaGiST~\cite{LCC+14}, Simba~\cite{XLY+16}, SATO~\cite{VAW14} use a sample of the input dataset to compute the minimum bounding rectangles (MBRs) for their spatial partitioning operation. Sampling is also used to cluster very large datasets~\cite{bejarano2011sampling, yu2011sample}. Specially, sampling is the fundamental method for many selectivity estimation algorithms for spatial data~\cite{acharya1999selectivity}. The main idea of AQP is the trade-offs between query response time and accuracy as shown in Figure~\ref{fig:trade_off}. The common drawback of existing systems is the lack of a mechanism to choose a suitable sampling ratio to achieve a desired accuracy. For instance, SpatialHadoop just chooses a fixed $1\%$ sample of dataset to compute partition MBRs, which is not always the best choice. DeepSampling addresses this challenge by suggesting the minimum sampling ratio such that the desired accuracy could be achieved. For non-spatial data, BlinkDB~\cite{agarwal2013blinkdb} provides a bounded errors for standard relational queries. However, BlinkDB assumes the independence of data dimensions, which is not applicable for spatial data. {\noindent \bf Deep learning and spatial data:} In recent years, the research community has witnessed the rapid growth of research projects in the intersection of big spatial data and machine learning~\cite{sabek2019machine}. One of the important research directions is scalable statistical inference systems for big spatial data analysis. For instance, TurboReg~\cite{sabek2018turboreg} is a scalable framework for building spatial logistic regression models. TurboReg is built on top of Markov Logic Network, which is able to predict the presence and absence of spatial phenomena in a geographical area with reasonable accuracy. DeepSPACE~\cite{vorona2019deepspace} is a deep learning-based approximate geospatial query processing engine. DeepSPACE utilize the learned data distribution to provide a quick response for spatial queries with reasonable accuracy. Both TurboReg and DeepSPACE hold the common drawback that they cannot guarantee a required precision of their answers. DeepSampling aims to overcome this issue by providing a prediction model such that the required precision is always met with a reasonable of sampling ratio budget. \section{Selectivity Estimation with Predicted Error and Response Time} \label{sec:method} \begin{figure*}[t] \centering \subfigure[Existing AQP engine]{\includegraphics[scale=0.33]{images/aqp_existing} \label{fig:aqp:existing}} \hspace{12pt} \subfigure[Sample Ratio Estimation]{\includegraphics[scale=0.33]{images/aqp_predict_sampling_ratio} \label{fig:aqp:predict_sampling_ratio}} \hspace{12pt} \subfigure[Accuracy Prediction]{\includegraphics[scale=0.33]{images/aqp_predict_accuracy} \label{fig:aqp:predict_accuracy}} \hspace{12pt} \caption{DeepSampling addresses critical problems on existing AQP systems} \label{fig:aqp} \end{figure*} \subsection{Problem definition} \label{sec:method:problem_definition} This paper focuses on the prediction model for the selectivity estimation problem but the proposed approach can be easily generalized to other problems such as K-means clustering or spatial partitioning. The goal is to find the relationship between accuracy and sample size and toward this goal we define two problems, {\em accuracy prediction} and {\em sample size estimation} which are both defined in this section. First, we will define the accuracy of an approximate answer in the selectivity estimation (SE) problem. \begin{definition}[query accuracy] In the SE problem, given an approximate answer $\pi$ and a ground truth $\Pi$ for query range $Q$, the accuracy of the approximate answer $\pi$ is \begin{equation} acc(\pi,\Pi)=max(0, 1 - |\Pi - \pi|/\Pi) \end{equation} \end{definition} Based on this definition, we define the following two problems: \textbf{Problem 1 (Sampling Ratio Estimation)}: \textit{Given a dataset $D$, a query range $Q$, and a desired accuracy $\alpha$, predict the minimum value of sampling ratio $\sigma$ such that $acc(\pi, \Pi) \ge \alpha$.} \textbf{Problem 2 (Accuracy Prediction)}: \textit{Given a dataset $D$, a query range $Q$, and a sampling ratio $\sigma$, predict the accuracy $\alpha$ such that $|acc(\pi, \Pi) - \alpha|$ is minimized.} Both problems are very important in approximate geospatial query processing. If we could address these problems, the existing spatial database systems could minimize the computation effort for sampling process while still achieving a desired accuracy for their answers. Figure~\ref{fig:aqp} shows how DeepSampling enhances performance of existing approximate query processing systems. Instead of fixing a sampling ratio as Figure~\ref{fig:aqp:existing}, an AQP engine can use Problem~1 to calculate a suggested minimal sampling size to achieve the used-desired accuracy as shown in Figure~\ref{fig:aqp:predict_sampling_ratio}. Conversely, if the system has a fixed sampling ratio, it can apply Problem~2 to estimate the result accuracy as shown in Figure~\ref{fig:aqp:predict_accuracy}. \subsection{Prediction with mixed data sources} \label{sec:method:prediction_mixed_data_sources} \begin{figure}[t] \centering \subfigure[Different distributions]{\input{Experiments/ratio-accuracy-relationship} \label{fig:relationship:datasets}} \subfigure[Different query sizes]{\input{Experiments/ratio-accuracy-selectivity} \label{fig:relationship:selectivity}} \caption{How sampling ratio ($\sigma$) relates to accuracy ($\alpha$)} \label{fig:relationship} \end{figure} In general, we know that the accuracy ($\alpha$) of an approximate answer increases with the sampling ratio ($\sigma$). However, we show in this part that this relationship is more complex than that. Figure~\ref{fig:relationship} shows examples of how these two quantities are related to each other. First, Figure~\ref{fig:relationship:datasets} shows that this relationship highly depends on the dataset distribution. While for all distributions the sampling ratio and accuracy are highly correlated, the relationship is different for each dataset. For example, for the rotated diagonal dataset, the accuracy ranges from 96\% to 99\% for all sampling ratios while for the mixed distribution dataset, the accuracy ranges from 22\% to 90\%. Second, Figure~\ref{fig:relationship:selectivity} shows the relationship for different query sizes. This time, we see that the relationship highly depends on the query size as well. These observations show how challenging the problem is. To build an accurate model, we need to take into account the input data distribution and the query size. For other problems, the query size could be replaced with other query parameters, e.g., the number of clusters for the K-means clustering problem, or the number of partitions for the spatial partitioning problem. \subsection{DeepSampling architecture} \label{sec:method:model_architecture} \begin{figure}[t] \centering \includegraphics[width=0.5\linewidth]{images/model_architecture} \caption{DeepSampling architecture} \label{fig:model_architecture} \end{figure} Figure~\ref{fig:model_architecture} shows an overview of the proposed architecture of the DeepSampling model. This architecture is used to solve both problems described earlier, {\em sampling ratio estimation} and {\em accuracy prediction}. To avoid repetition, we write between (parentheses) the changes that need to be made for the {\em accuracy prediction} problem. To build an accurate and portable model that accounts for the query size and the data distribution, the proposed model takes two sets of inputs, {\em tabular data} and {\em data distribution}. The \textbf{tabular input layer} consists of data taken from the processing logs which includes the query size ($q$), the sampling ratio ($\sigma$), and the resulting accuracy ($\alpha$). If we need to apply this architecture for other problems, then the query size will be replaced with other query parameters, e.g., number of clusters. Also, the accuracy will be calculated differently. This data is passed to a multi-layer perceptron (MLP) model. MLP is a feedforward neural network with at least three layers of nodes: an input layer, a hidden layer and an output layer. We chose MLP for tabular input since it can be used to learn complex mathematical models by regression analysis~\cite{cybenko1989approximation}. The \textbf{data distribution input layer} catches the distribution of the input dataset. In this paper, we use a uniform histogram which is expected to accurately catch the dataset distribution if computed at a reasonable resolution. The histogram resolution is a system parameter that we study in the experiments section. Since this histogram is a $2$D matrix with spatial relationship between histogram bins, it is fed to a convolutional neural network (CNN) layer. The \textbf{concatenation layer} combines the output of the MLP and CNN layers together and feed them to a fully connected (FC) layer. The final layer of FC is a single node with linear activation so that the model output is the predicted sampling ratio (or accuracy). The \textbf{loss function} of the final node provides a feedback on how accurate the predicted value is. Based on the problem definition in Section~\ref{sec:method:problem_definition}, we use mean absolute percentage error (MAPE) as the loss function which is the average absolute percentage error of actual value $A_t$ and forecast value $F_t$ for all training points $t\in[1,n]$ as shown in Equation~\ref{eqn:mean_absolute_percentage_error}. MAPE is commonly used in regression models since it is very intuitive interpretation for relative errors. \begin{equation} MAPE = \frac{1}{n}\sum_{t=1}^{n} \left|\frac{A_t - F_t}{A_t}\right| \label{eqn:mean_absolute_percentage_error} \end{equation} \section{Preliminary results} \label{sec:experiments} This section gives some preliminary results when applying the proposed approach to the selectivity estimation problem. In particular, we wanted to answer the following questions: \begin{enumerate} \item How accurately does the model account for the data distribution and query size? \item Can the model solve both problems efficiently? \item Is the model portable enough so that we can test it on a new data distribution that was not in the training set? \end{enumerate} \subsection{Experimental setup} \label{sec:experiments:setup} \begin{table}[t] \caption{Parameters for the selectivity estimation (SE) query} \small \begin{tabular}{|l|p{2.0in}|} \hline Parameter & Values (Default) \\ \hline Dataset distribution & Uniform, Gaussian, Diagonal, Sierpinski, Bit, Parcel, Mixed \\ \hline Sampling ratio ($\sigma$) & 0.001, 0.0015,...,0.2 \\ \hline Query size ($q$) & 0.01,0.02,...,0.1. \\ \hline Histogram size ($h$) & $1\times 1$ $\ldots$ ($16\times 16$) $\ldots$ $64\times 64$ \\ \hline \end{tabular} \label{tab:parameters} \end{table} We implement the proposed model in Figure~\ref{fig:model_architecture} using Keras~\cite{chollet2015keras}. The source code, training data and models are available at~\cite{gitdeepsampling}. \textbf{Datasets:} We use both synthetic and real datasets in our experiments. We generated a total of $144$ synthetic datasets using the open-source spatial data generator~\cite{vu2019spatial}. The dataset distributions are listed in Table~\ref{tab:parameters} and the detailed distribution parameters are included in the source code~\cite{gitdeepsampling}. We also used two real datasets: {\tt OSM-Nodes}~\cite{UCRSTAR/OSM2015/all_nodes} and {\tt OSM-Lakes}~\cite{UCRSTAR/OSM2015/lakes}. The real datasets are only used for testing but never for training the model. \textbf{Parameters:} In addition to the dataset distribution, we also vary the sampling ratio ($\sigma$), the query size ($q$), and the histogram size ($h$). The query size is the ratio between the area of the query rectangle and the area of the input minimum bounding rectangle (MBR). Our query workload consists of square queries centered at random locations in the input space. Table~\ref{tab:parameters} summarizes all the parameters that we vary in our experiments. In total, our generated dataset contains $54,720$ data points. \textbf{Metrics:} We use mean absolute percentage error (MAPE) to evaluate the accuracy of a prediction model. The lower the value of MAPE, the better the model is. \textbf{Baseline method:} We compare the proposed model to a linear regression(LR) model which takes the tabular input and predict a numeric output. The reason behind this choice is that we want to see how the dataset distribution input makes a difference to the baseline which only takes query attributes into account. \subsection{Accuracy Prediction} \label{sec:experiments:accuracy_prediction} \begin{figure}[t] \centering \subfigure[Accuracy Prediction problem]{\input{Experiments/accuracy-prediction} \label{fig:experiment:accuracy_prediction}} \subfigure[Sampling Ratio Estimation problem]{\input{Experiments/sampling-ratio-prediction} \label{fig:experiment:sampling_ratio_prediction}} \caption{Accuracy of DeepSampling and linear regression} \label{fig:performance_comparison} \end{figure} In the first experiment, we build a model to predict the average query accuracy, given the sampling ratio, query size and dataset histogram of size $16\times 16$. In particular, we use the synthetic datasets with $54,720$ data points described in Section~\ref{sec:experiments:setup} to train and test our proposed model. To observe how training data distribution affects the test accuracy, we organized the training data into different combinations of $1$ to $7$ distributions in Table~\ref{tab:parameters}. For each combination, we take a split of $75\%$ data points for training process. We test all the trained models with $25\%$ of the synthetic data points. We also test on $2800$ data points that we collected from SE queries on real {\tt OSM-Nodes} and {\tt OSM-Lakes} dataset. Figure~\ref{fig:experiment:accuracy_prediction} shows an interesting observation that the more data distributions we used for training process, the more accurate it is. This is expected since some simple distributions might not be able to capture important insights of test datasets. DeepSampling model is doing very well when we tested on both synthetic data and real data (MAPE is around $3\%$ and $16\%$). This shows the portability of the model. Even though the model was trained only on synthetic data, it still provided good results for the real dataset. In the future, we plan to add more synthetic data to make the model even more accurate with real data. On the other hand, the linear regression baseline, due to its simplicity and the lack of data distribution, did not achieve a good accuracy. For the test on real dataset, its prediction is even more than $100\%$ beyond the actual mean accuracy value. \subsection{Sampling Ratio Estimation} \label{sec:experiments:sampling_ratio_prediction} In this experiment, we build a model based on DeepSampling to predict sampling ratio, given a desired query accuracy, query size and dataset histogram of size $16\times 16$. We use the same set of training and testing split as mentioned in Section~\ref{sec:experiments:accuracy_prediction}. Table~\ref{fig:experiment:sampling_ratio_prediction} shows that DeepSampling is still doing better than the baseline when applied on both synthetic and real data. The errors are relatively higher than the accuracy prediction problem in Section~\ref{sec:experiments:accuracy_prediction}. The reason is that the range of the accuracy in the training set is narrow as compared to the range of sampling ratio. For example, in Figure~\ref{fig:relationship}, the accuracy in some cases stays above 95\% while the sampling ratio ranges from 0.1\% to 20\%. Nonetheless, the DeepSampling approach is consistently more accurate than the linear regression baseline. These results are consistent with existing work that found that the sampling ratio estimation problem is more difficult. For example, in BlinkDB~\cite{agarwal2013blinkdb} this problem is solved by simply choosing from a predefined set of points, sampling ratio and accuracy, and interpolating between them if needed. \subsection{Effect of histogram resolution} \label{sec:experiments:histogram_effect} \begin{figure}[t] \centering \subfigure[Effect on accuracy]{\input{Experiments/histogram-resolution-accuracy} \label{fig:histogram-resolution-accuracy}} \subfigure[Effect on training time]{\input{Experiments/histogram-resolution-training-time} \label{fig:histogram-resolution-training-time}} \caption{Effect of histogram resolution} \label{fig:histogram_effect} \end{figure} To choose a good histogram size, this experiment studies the trade-off between the model accuracy and training time as we vary the histogram size as depicted in Figure~\ref{fig:histogram_effect}. In this experiment, we vary the histogram resolution from $1\times 1$ (effectively no histogram) to $64\times 64$. Figure~\ref{fig:histogram-resolution-accuracy} shows the accuracy of the model when tested on both synthetic and real data as the histogram size increases. It is clear from this experiment that the histograms with higher resolutions carry more information that makes the model more accurate. However, the model stabilizes at $16\times 16$ where the histogram is accurate enough to catch the distributions in the training set. Figure~\ref{fig:histogram-resolution-training-time} shows the total time of the training phase, i.e., the time until the model stabilizes. As expected, the model takes more time to train as the histogram resolution increases due to the large input that goes through the CNN model. From this experiment, we choose to set the histogram size to $16\times 16$ which gives a good accuracy in a reasonable time. \section{Summary and future work} \label{sec:conclusion} In this paper, we introduced DeepSampling, a deep-learning-based system that provides predicted errors for approximate geospatial query processing. The proposed model combines the sampling ratio, the result accuracy, the query parameters, and the input data distribution. We carry some preliminary results when we apply DeepSampling to improve performance of selectivity estimation query. The results show that the proposed model can accurately compute the sampling ratio and accuracy for many synthetic and real distributions. In the future, we will apply the same model on other important approximate spatial problems such as K-means clustering and spatial partitioning. \section{Introduction} \end{document} \endinput
{'timestamp': '2020-08-18T02:14:12', 'yymm': '2008', 'arxiv_id': '2008.06831', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06831'}
arxiv
\section{Introduction} \label{sec:introduction} Image segmentation is a fundamental task in a great variety of applications arising in the fields of computer vision and medical imaging. The segmentation approaches based on the energy minimization theorems, such as the variational methods or the graph-based methods, have demonstrated their strong capacity of coping with various challenging image segmentation issues. Among them, the interactive segmentation algorithms in conjunction with user intervention and priors are able to provide a reliable and efficient way for separating foreground regions of interest from image domain. The interventions from user often provide necessary information to initialize the interactive segmentation approaches, or impose effective constraints to encourage reasonable and accurate segmentations. In many segmentation approaches, user interactions can be constructed by loosely drawing scribbles associated to different regions. These scribbles serve as initial seeds for image segmentation. Models relying on a graph-based optimization scheme frequently utilize such an interactive fashion as introduced in~\cite{boykov2006grapy,grady2006random,couprie2011power,li2004lzay}, for which an image is modeled as a graph collecting a set of nodes and edges. The Voronoi diagram-based segmentation approaches~\cite{arbelaez2004energy,bai2009geodesic,chen2018fast} implement the image domain partitioning through Voronoi regions and the corresponding Voronoi index maps, where the user-provided scribbles serve as the sets of source points for the computation of minimal weighted distances and for the propagation of region labels. In~\cite{gao2012interactive}, these scribbles were treated as subregions of the image domain, from which statistical models fitting to the image intensity distributions in the target regions are created. This is also the case for the selective segmentation models~\cite{spencer2019parameter,nguyen2012robust}, which exploited user-provided scribbles to extract statistical priors of image features. Active contour approaches~\cite{kass1988snakes} have proven their ability in addressing a wide variety of image segmentation problems. In their basic formulation, the segmentation procedure can be carried out by deforming initial curves driven by suitable gradient flows. These initial curves can be placed close to the targets, thus able to identify specific target regions from complicated backgrounds, especially for these models relying on local image features such as image gradients~\cite{kass1988snakes,xu1998snakes,cohen1991active,cohen1993finite,caselles1997geodesic,malladi1995shape} and local region-based homogeneity penalization~\cite{li2008minimization,brox2009local}. Thanks to the energy minimization framework, the geometric priors such as Euclidean curve length and the elastica energy can be naturally taken into account for finding favorable segmentations. The interventions created by clicking several points along the boundary of interest often serve as the user input for paths-based interactive image segmentation models. In general, these models usually exploit closed contours to delineate target boundaries, each of which can be sought via a set of relevant piecewise minimal cost paths. Given suitable cost functions for curve arcs, these minimal cost paths can be efficiently tracked either in a discrete setting~\cite{miranda2012riverbed} or in a continuous PDE framework~\cite{cohen1997global}. Shape priors can be naturally incorporated into segmentation models in a energy minimization framework such as active contours~\cite{cremers2002diffusion,bresson2006variational,leventon2000statistical, chan2005level,klodt2011convex}, allowing to encourage segmented object regions to satisfy the constraints induced from the given shape priors. In addition, recent segmentation approaches impose that the segmented regions are convex~\cite{yan2020convexity,luo2019convex,gorelick2016convexity,royer2016convexity} or star convexity~\cite{veksler2008star,vicente2008graph,yuan2012efficient}, which are capable of generating promising image segmentation results in many challenging scenarios. The list of the literature reviewed above is obviously not exhaustive and other interesting and efficient image segmentation approaches may include the learning-based models such as~\cite{ma2020learning,wang2018deepigeos,zhang2020exploring,zhang2021automatic,zhang2021cross}. In the following, we concentrate on the minimal geodesic path approaches under the framework of Eikonal PDEs. \begin{figure}[t] \centering \includegraphics[width=8.5cm]{images/fig1} \caption{An example for the illustration of the advantages of the proposed geodesic paths-based segmentation model. (\textbf{a}) An original image, where the red line indicates the ground truth. (\textbf{b}) and (\textbf{c}) Segmentation contours from the edge-based circular geodesic model~\cite{appleton2005globally} and the proposed model, respectively} \label{fig_Example} \end{figure} \subsection{Geodesic Paths-based Image Segmentation Models} The original snakes model~\cite{kass1988snakes} invoked a non-intrinsic functional that depends on the parameterization of the evolving curves. The geodesic active contour models~\cite{caselles1997geodesic,yezzi1997geometric,kimmel2003regularized} remove the dependency on curve parameterization. These geometric approaches made use of weighted curve lengths as energy functionals, which are measured via a type of Riemannian metrics. Contrary to the snakes model~\cite{kass1988snakes} using parameterized curves, the curve evolution in these geometric approaches can be implemented in a level set formulation~\cite{osher1988fronts}. However, as an important shortcoming, it is difficult for these geometric active contour models to find the global minimum of the corresponding weighted curve length. As a consequence, the image segmentations are sensitive to the initialization. In order to overcome this issue, Cohen and Kimmel~\cite{cohen1997global} introduced a minimal geodesic model based on the Eikonal PDE framework, where a globally minimizing curve is a geodesic path associated to a Riemannian metric. The minimal geodesic models~\cite{peyre2010geodesic} are quite efficient for image segmentation applications, due to the well-studied numerical schemes such as the Fast marching method, and the global optimality. Along this research line, most of the relevant approaches~\cite{benmansour2009fast,mille2009geodesically,mille2015combination} attempted to construct simple and closed contours leveraging geodesic paths. Cohen and Kimmel introduced a saddle points detection approach for image segmentation~\cite{cohen1997global}. The initialization is a single point located in the boundary of interest, from which a closed contour can be generated to describe the target boundary. This saddle point detection method was then adopted by~\cite{appia2011active,mille2015combination} for interactive image segmentation in conjunction with a set of prescribed points at the target boundary. However, the geodesic paths in these models rely only on the edge-based features by essence, despite the use of region-based homogeneity terms for finding the final segmentations. This issue is addressed in~\cite{chen2016finsler,chen2019active}, where a Randers minimal path model was exploited as a solution to the region-based active contour problems. Unfortunately, this model does not take into account curvature regularization when computing minimal paths. Instead of placing source points at the target boundary, the circular geodesic model~\cite{appleton2005globally} exploits a fixed point inside the target region as initialization to set up the segmentation algorithm. However, neither the region-based terms nor the curvature regularization were exploited for segmentation. A simple closed geodesic path is extracted in conjunction of a particular cut placed in the image domain. In this paper, we propose a new geodesic paths-based image segmentation model relying on a dual-cut scheme. The proposed model differs to the original circular geodesic model~\cite{appleton2005globally} mainly at the construction of the local geodesic metrics and at the generation of simple closed contours. Specifically, the geodesic metrics considered are able to encode the region-based homogeneity features and priors for image segmentation. As mentioned above, the original circular geodesic model~\cite{appleton2005globally} still falls into the \emph{edge-only} limitation, such that the resulting segmentation curves may fail to capture the whole target region, as illustrated in Fig.~\ref{fig_Example}b. In contrast, one can see that the integration of those beneficial features in the proposed model can overcome such an issue, as depicted in Fig.~\ref{fig_Example}c. In this experiment, Fig.~\ref{fig_Example}a illustrates the original image where the red line indicates the ground truth contour. \subsection{Contributions and Paper Structure} The main contributions of this paper are three folder. \begin{itemize} \item \emph{Geodesic metrics implicitly encoding region-based homogeneity features}. We introduce a new geodesic metric construction method for minimal path computation with application to interactive image segmentation. The geodesic metrics considered can be decomposed into a scalar-valued function which encodes region-based homogeneity features, and a type of Finsler metrics which involve either the asymmetric image gradient features or the curvature regularization. \item \emph{Dual-cut Scheme for closed contour construction}. Inspired by the circular geodesic model~\cite{appleton2005globally}, we propose a new geodesic paths-based interactive image segmentation model relying on a point that is located inside the target region. The final segmentation contours are generated by the concatenation of two disjoint paths derived from a new dual-cut scheme. \item \emph{Flexible implementation of user intervention}. We show that the scribbles provided by the user can be easily incorporated into the proposed segmentation method. These scribbles are regarded as barriers to prevent the geodesic paths from crossing over unexpected positions, allowing a flexible implementation of the proposed model for efficient interactive image segmentation. \end{itemize} The remaining of this paper is organized as follows. In Section~\ref{sec_BG}, we introduce the background on a generic minimal geodesic model and on the computation of image features. The main contributions are presented in Sections~\ref{sec_principle} and~\ref{sec_DualCut}. Specifically, Section~\ref{sec_principle} introduces a new metric construction method which integrates with image edge-based features, implicit region-based homogeneity features and/or the curvature regularization term. Moreover, Section~\ref{sec_DualCut} presents a dual-cut scheme for the extraction of simple closed curves. Experimental results and conclusion are presented in Sections~\ref{sec_Exp} and~\ref{sec_Conclusion}, respectively. \section{BackGround} \label{sec_BG} \subsection{Minimal Paths} \label{subsec_MP} Tracking continuous curves to depict interesting image features is a fundamental problem posed in the field of image analysis. Cohen and Kimmel introduced\cite{cohen1997global} an elegant minimal path solution to that problem based on the Eikonal PDE framework, yielding a broad variety of successful applications. Let $\mathbb M\subset\mathbb R^n$ be an open and bounded domain of dimension $n=2,3$. Basically, a core ingredient for minimal path models is the energy for a curve $\gamma$, defined as the weighed curve length of $\gamma$ associated to a geodesic metric $\mathcal F:\mathbb M\times\mathbb R^n\to\mathbb R_0^+$. At each fixed point $\mathbf x\in\mathbb M$, the metric can be denoted by $\mathcal F(\mathbf x,\mathbf u)=F_{\mathbf x}(\mathbf u)$, where $F_{\mathbf x}(\mathbf u)$ is a 1-homogeneous and convex function. In the original minimal path model~\cite{cohen1997global}, the weighted length of a curve is measured by isotropic Riemannian metrics, which are independent to the curve tangents $\gamma^\prime$ (i.e. the first-order derivative of $\gamma$). In general, a Finsler metric $\mathcal F(\mathbf x,\mathbf u)$ is allowed to be asymmetric and anisotropic with respect to its second argument at some point $\mathbf x\in\mathbb M$~\cite{melonakos2008finsler}. Typical examples of Finsler metric may involve the Randers metrics~\cite{randers1941asymmetrical,chen2016finsler,chen2017global} and the asymmetric quadratic metrics~\cite{chen2018asymmetric,duits2018optimal,mirebeau2018fast}. The weighted curve length of a Lipschitz continuous curve $\gamma:[0,1]\to\mathbb M$, measured using a general Finsler metric $\mathcal F$, can be formulated by \begin{equation} \label{eq:CL} \mathcal L_{\mathcal F}(\gamma):=\int_0^1\mathcal F(\gamma(u),\gamma^\prime(u))du. \end{equation} Given a fixed source point $\mathbf s\in\mathbb M$, globally minimizing the weighted curve length~\eqref{eq:CL} between $\mathbf s$ and an arbitrary target point $\mathbf x\in\mathbb M$ yields a geodesic distance map $\mathcal U_\mathbf s:\mathbb M\to\mathbb R_0^+$ \begin{equation} \label{eq_MinimalLength} \mathcal U_{\mathbf s}(\mathbf x)=\inf_{\gamma\in\Lip([0,1],\mathbb M)}~\big\{\mathcal L_\mathcal F(\gamma);\gamma(0)=\mathbf s,\gamma(1)=\mathbf x\big\}, \end{equation} where $\Lip([0,1],\mathbb M)$ is the set of all Lipschitz curves $\gamma:[0,1]\to\mathbb M$. A geodesic path linking from the source point $\mathbf s$ to a target point $\mathbf x$ is a globally minimizing curve $\mathcal G_{\mathbf s,\mathbf x}\in\Lip([0,1],\mathbb M)$ such that its weighted curve length is equivalent to the geodesic distance $\mathcal U_\mathbf s(\mathbf x)$, i.e. \begin{equation} \label{eq_GeoCurve} \mathcal G_{\mathbf s,\mathbf x}=\underset{\gamma\in\Lip([0,1],\mathbb M)}{\arg\min}\big\{\mathcal L_\mathcal F(\gamma);\gamma(0)=\mathbf s,\gamma(1)=\mathbf x\big\}. \end{equation} The geodesic distance map $\mathcal U_\mathbf s$ associated to a Finsler metric $\mathcal F$ admits the unique viscosity solution to a generalized Eikonal PDE, or a static Hamilton-Jacobi PDE~\cite{mirebeau2014efficient}, which reads \begin{equation} \label{eq_FinslerEikonal} \begin{cases} \displaystyle\sup_{\mathbf v\neq\mathbf{0}}\frac{\langle\nabla \mathcal U_\mathbf s(\mathbf x),\mathbf v\rangle}{\mathcal F(\mathbf x,\mathbf v)}=1,~\forall \mathbf x\in\Omega\backslash\{\mathbf s\},\\ \mathcal U_\mathbf s(\mathbf s)=0, \end{cases} \end{equation} where $\langle\mathbf u_1,\mathbf u_2\rangle=\mathbf u_1^T\mathbf u_2$ denotes the standard Euclidean scalar product of two vectors $\mathbf u_1,\,\mathbf u_2\in\mathbb R^n$. Tracing a geodesic path $\mathcal G_{\mathbf s,\mathbf x}$, as defined in Eq.~\eqref{eq_GeoCurve}, can be implemented by re-parameterizing the solution $\mathcal G$ to a gradient descent ordinary differential equation (ODE) such that $\mathcal G(0)=\mathbf x$, and for $u>0$ \begin{equation} \label{eq_ODE} \mathcal G^\prime(u)=-\,\underset{\|\mathbf v\|=1}{\arg\max}\frac{\langle\nabla \mathcal U_\mathbf s(\mathcal G(u)),\mathbf v\rangle}{\mathcal F(\mathcal G(u),\mathbf v)}. \end{equation} The back-tracking procedure~\eqref{eq_ODE} will be terminated once the source point $\mathbf s$ is reached. Numerically, the gradient descent ODE can be solved by the efficient scheme proposed in~\cite{mirebeau2019riemannian}. In the remaining of this paper, we explore two types of Finsler geodesic metrics to deal with the 2D image segmentation problem, as introduced in Sections~\ref{subsec_SpatialMetric} and~\ref{subsec_Curvature}. The first type of considered metrics is constructed using image features only. In this case, one has $\mathbb M:=\Omega$, where $\Omega\subset\mathbb R^2$ stands for an open and bounded \emph{image domain}. The second type of metrics invokes a tool of orientation lifting to to track curvature-regularized geodesic paths. Accordingly, these geodesics paths are established over an orientation-lifted space $\mathbb M:=\Omega\times \mathbb S^1$, where $\mathbb S^1:=\mathbb R\backslash(2\pi\mathbb Z)$ denotes the orientation space with a periodic boundary condition. \subsection{Region-based Active Contour Models} \label{subsec_RAC} The region-based active contour models\cite{chan2001active,cremers2007review,zhu1996region,dubrovina2015multi} implement the image segmentation by minimizing an energy functional $\Psi$ with respect to \emph{closed} curves $\mathcal C:[0,1]\to\Omega$ \begin{equation} \label{eq_ACEnergy} \Psi(\mathcal C)=\mathcal E(\mathcal C)+\eta\mathcal L(\mathcal C), \end{equation} where $\eta\in\mathbb R^+$ is a parameter that controls the relative importance between the region-based term $\mathcal E$ and the regularization term $\mathcal L$. Specifically, the term $\mathcal L(\mathcal C)$ can be set as either the Euclidean curve length of $\mathcal C$ or as the weighted curve length~\eqref{eq:CL}. The region-based homogeneity penalization is encoded in the term $\mathcal E(\mathcal C)$, where typical examples may include the region competition models~\cite{zhu1996region,chan2001active}, the pairwise similarity models~\cite{jung2012nonlocal,sumengen2006graph} and the Bhattacharyya coefficient-based model~\cite{michailovich2007image}. In the context of two-phase segmentation, the curve $\mathcal C$ partitions the image domain $\Omega$ into two regions $R$ and $\Omega\backslash R$, where we assume $R$ is enclosed by $\mathcal C$. In the following, $R$ is also referred to as a shape. We take the piecewise constants model~\cite{chan2001active,chan2000active} as an instance, for which the corresponding regional term $\mathcal E$ reads as \begin{equation} \label{eq_PConst} \mathcal E(\mathcal C)=\int_{R}\|I(\mathbf x)-\mathbf{c}_1\|^2d\mathbf x+\int_{\Omega\backslash R}\|I(\mathbf x)-\mathbf{c}_2\|^2d\mathbf x, \end{equation} where $I:\Omega\to\mathbb R^m$ is an image, with $m=1$ and $m=3$ corresponding to gray level images and color images, respectively. The scalar value $\mathbf{c}_1=(c_{1,1},\cdots,c_{m,1})$ (resp. $\mathbf{c}_2=(c_{1,2},\cdots,c_{m,2})$) stands for the mean intensities of the corresponding channel of $I$ within the subregion $R$ (resp. the subregion $\Omega\backslash R$), i.e., \begin{equation} \label{eq_Means} c_{k,1}:=\frac{\int_{R}I_k(\mathbf x)d\mathbf x}{\int_{R}d\mathbf x}, \quad c_{k,2}:=\frac{\int_{\Omega\backslash R}I_k(\mathbf x)d\mathbf x}{\int_{\Omega\backslash R}d\mathbf x}, \end{equation} for $k=1,\cdots,m$. \subsection{Edge-based Features from Image Gradients} \label{subsec_EdgeFeatures} The extraction of image edge appearance and anisotropy features very often relies on the image gradients. We adopt the model introduced in~\cite{sochen1998vision} for the computation of the gradients of a color image $I=(I_1,I_2,I_3)$. This is implemented by invoking the Jacobian matrices of the smoothed image $G_\sigma\ast I$, where $G_\sigma$ is a Gaussian kernel of standard derivation $\sigma$ and where `$\ast$' stands for the convolution operator. As in~\cite{sochen1998vision}, we first build a Jacobian matrix $\mathcal J(\mathbf x)=(\nabla G_\sigma \ast I)(\mathbf x)$ of size $2\times 3$, which is comprised of the smoothed $x$-derivatives $\partial_x G_\sigma \ast I_i$ and $y$-derivatives $\partial_y G_\sigma\ast I_i$ for $i=1,2,3$. \subsubsection{Edge Appearance Features} Based on the Jacobian matrices $\mathcal J$, the image edge appearance features can be carried out by the Frobenius norms of $\mathcal J$, which reads \begin{equation} \label{eq_FrobNorms} \tilde{g}(\mathbf x)=\left(\sum_i^3\,\|(\nabla G_\sigma\ast I_i)(\mathbf x)\|^2\right)^{1/2}. \end{equation} In practice, we normalize the values of the scalar-valued function $\tilde{g}$ to the range $[0,1]$ by defining \begin{equation} \label{eq_Magnitude} g(\mathbf x)=\frac{\tilde{g}(\mathbf x)}{\displaystyle\sup_{\mathbf y\in\Omega}\|\tilde{g}(\mathbf y)\|},\quad \forall \mathbf x\in\Omega. \end{equation} \subsubsection{Edge Anisotropic Features} Let $\mathbb S_2^+$ stand for the set collecting all positive definite symmetric tensors of size $2\times2$. In order to compute the edge anisotropy features, we take into account a tensor field $\mathcal W\in\mathbb S_2^+$ which can be expressed as~\cite{sochen1998vision} \begin{equation} \label{eq_W} \mathcal W(\mathbf x)=\mathcal J(\mathbf x)\mathcal J(\mathbf x)^T+\Id, \end{equation} where $\Id$ is the identity of size $2\times2$. The edge anisotropic features are encoded in the matrices $\mathcal W(\mathbf x)$. Notice that for a gray level image $I:\Omega\to\mathbb R$, one has $\mathcal J(\mathbf x)=(\partial_x G_\sigma\ast I,\partial_y G_\sigma\ast I)^T$, and the corresponding tensor $\mathcal W(\mathbf x)$ can be still computed using Eq.~\eqref{eq_W}. \section{Geodesic Paths with Implicit Region-based Homogeneity Enhancement} \label{sec_principle} The core contributions of this paper lie at the introduction of a new minimal geodesic model for efficient interactive image segmentation. Basically, the proposed model is mainly comprised of two ingredients: (i) the computation of local geodesic metrics encoding image features and/or curvature regularization, and (ii) the construction of simple closed curves made up of geodesic paths. Both of them require a point $\mathbf z\in\Omega$ to provide reliable user intervention such that the point $\mathbf z$, referred to as a landmark point, is supposed to be placed inside the target region. In this section, we focus on the computation of local geodesic metrics which implicitly encode the region-based homogeneity features. In the context of image segmentation, image gradients involving both edge appearance and anisotropy features are very often implemented to define object boundaries. However, exploiting only image gradients for building metrics is usually insufficient to find favorable segmentation results in many complex scenarios, as illustrated in Fig.~\ref{fig_Example}. In order to address this issue, we consider a geodesic metric $\mathscr Q_z$ associated to the landmark point $\mathbf z$, which can be expressed as \begin{equation} \label{eq_targetMetric} \mathscr Q_\mathbf z(\mathbf x,\mathbf u):=\psi_\mathbf z(\mathbf x)\mathcal F(\mathbf x,\mathbf u), \end{equation} where $\psi_\mathbf z:\Omega\to\mathbb R^+$ is a scalar-valued weighted function that encodes the region-based homogeneity information. The second term $\mathcal F$ in the right side of Eq.~\eqref{eq_targetMetric} is a Finsler metric. Moreover, the metric $\mathcal F$ allows to incorporate the curvature-dependent length terms as regularization. The construction for $\mathcal F$ will be detailed in Sections~\ref{subsec_SpatialMetric} and~\ref{subsec_Curvature}. \subsection{Extracting Implicit Region-based Homogeneity Features} \label{subsec_ImplicitFeatures} In a great variety of region-based active contour models, the motion of planar closed curves $\mathcal C:[0,1]\to\Omega$ satisfies the following evolution equation \begin{equation} \label{eq_GradientFlow} \frac{\partial\mathcal C(u)}{\partial t}=\xi(\mathcal C(u))\mathcal N(u), \end{equation} where $\mathcal N$ is the \emph{inward} unit normal to $\mathcal C$ and $\xi:\Omega\to\mathbb R$ is a velocity function. As discussed in the literature~\cite{zhu1996region,tsai2001curve}, the flow~\eqref{eq_GradientFlow} can be exploited to minimize a region-based energy functional of a form \begin{equation} \label{eq_GeneralFunctional} E(\mathcal C)=\int_R\xi(\mathbf x)d\mathbf x=\int_\Omega\xi(\mathbf x)\chi_R(\mathbf x)d\mathbf x, \end{equation} where $R\subset\Omega$ is the interior region of $\mathcal C$ and $\chi_R:\Omega\to\{0,1\}$ stands for the characteristic function of $R$. The velocity $\xi$ can be chosen as the $L^1$ shape gradient of a region-based functional at $\chi_{R_0}$, where $R_0\subset\Omega$ is referred to as the initial shape. We refer to~\cite{chen2019eikonal} for more details on the $L^1$ shape gradient. Notice that $R_0$ is supposed to contain the point $\mathbf z$, which can be built by running a front propagation expanding from $\mathbf z$, as described in Section~\ref{subsec_Initializations}. With these definitions, we propose a new method to \emph{implicitly} represent the region-based homogeneity features carried by the velocity $\xi$. The basic idea is to define a set $\Theta_\mathbf z\subset\Omega$ which contains the point $\mathbf z$ and the initial shape $R_0$ \begin{equation} \label{eq_Bound} \Theta_\mathbf z:=\{\mathbf x\in\Theta\cup R_0;\mathbf x\text{~is connected to~}\mathbf z\}, \end{equation} where $\Theta$ consists of all the points $\mathbf x$ such that $\xi(\mathbf x)\leq 0$, i.e. \begin{equation*} \Theta:=\{\mathbf x\in\Omega;~\xi(\mathbf x)\leq 0\}. \end{equation*} From the definition~\eqref{eq_Bound}, one can see that the points involved in the set $\Theta_\mathbf z$ are connected to the point $\mathbf z$. As a result, this constraint is able to yield more selective user invention. In the following, we denote by $\partial\Theta_\mathbf z$ the boundary of the set $\Theta_\mathbf z$, which excludes the boundaries of holes inside $\Theta_\mathbf z$. In other words, when traveling forward along the boundary $\partial\Theta_\mathbf z$ with a counter-clockwise direction, the interior of $\Theta_\mathbf z$ is on the left. \begin{figure*}[t] \centering \includegraphics[width=17.5cm]{images/fig2} \caption{Examples for image edge-based features. (\textbf{a}) The original image. (\textbf{b}) Visualization for the appearance features $g$. (\textbf{c}) Visualization for the vector field $\omega$ using the tool of color coding. (\textbf{d}) The geodesic distances superimposed on the original image. The red and blue dots respectively denote the source and end points. The white line indicates the corresponding geodesic path } \label{fig_ColorCoding} \end{figure*} A local minimizer for the functional $E$ in Eq.~\eqref{eq_GeneralFunctional} should satisfy the respective Euler-Lagrange equation $\partial E/\partial\mathcal C=-\xi\mathcal N=0$. This means that a minimizing curve should pass through the zero-level curve of the velocity $\xi$. Based on this observation, we exploit the boundary $\partial\Theta_\mathbf z$ for the computation of the weighted function $\psi_\mathbf z$ used in Eq.~\eqref{eq_targetMetric}. In our model, we expect that the geodesic paths associated to the metric $\mathscr Q_\mathbf z$ formulated in Eq.~\eqref{eq_targetMetric} pass through the regions close to $\partial\Theta_\mathbf z$. This can be done by choosing $\psi_\mathbf z$ such that it takes low values around the boundary $\partial\Theta_\mathbf z$ and high values, otherwise. Toward this purpose, we define a Euclidean distance map $\mathcal D:\Omega\to\mathbb R^+_0$ with respect to the boundaries $\partial\Theta_\mathbf z$ \begin{equation} \label{eq_EucDist} \mathcal D(\mathbf x)=\min_{\mathbf y\in\partial\Theta_\mathbf z}\|\mathbf x-\mathbf y\|. \end{equation} Basically, the values of $\psi_\mathbf z(\mathbf x)$ should be positively correlated to the Euclidean distance value $\mathcal D(\mathbf x)$. In practice, one can set $\psi_\mathbf z(\mathbf z)=\infty$ and for any point $\mathbf x\in\Omega\backslash\{\mathbf z\}$ \begin{equation} \label{eq_DefPsi} \psi_\mathbf z(\mathbf x)=f(\|\mathbf x-\mathbf z\|)\exp(\mu\,\mathcal D(\mathbf x)), \end{equation} where $\mu\in\mathbb R^+$ is a constant, and $f(a)$ is a decreasing function for $a\in\mathbb R^+$ so as to prevent the geodesic curves from shrinking to $\mathbf z$. As in~\cite{appleton2005globally}, we make use of $f(a)=a^{-1}$ in the experiments. Note that the set $\Theta_\mathbf z$ was also considered in~\cite{spencer2019parameter} to incorporate user intervention into the computation of the velocity $\xi$, where the image segmentation was implemented by a convex relaxation framework. However, neither the asymmetric edge-based features nor the curvature regularization term were considered in~\cite{spencer2019parameter}. In contrast, these effective features can be naturally involved in the geodesic metrics considered, as introduced in the following sections. \subsection{Computation for the Shape Gradients} \label{Subsec_ShapeGradient} The computation for the velocity $\xi$ relies on the $L^1$ shape gradient of a differentiable functional $\tilde\mathcal E:L^1(\Omega,\mathbb R)\to\mathbb R$. For any admissible perturbation $\delta \varrho\in L^1(\Omega,\mathbb R)$, we can express $\tilde\mathcal E(\varrho)$ as follows \begin{equation} \label{eq_LinearAppro} \tilde\mathcal E(\varrho+\delta \varrho)=\tilde\mathcal E(\varrho)+\int_\Omega \delta \varrho(\mathbf x)\xi(\mathbf x)d\mathbf x+o(\|\delta \varrho\|_{L^1}), \end{equation} where $\xi\in L^\infty(\Omega,\mathbb R)$ is the shape gradient of $\tilde\mathcal E$ at $\varrho$. It can be generated through the G\^ateaux derivative of $\tilde\mathcal E$ \begin{equation} \label{eq_ShapeGradient} \int_\Omega\xi(\mathbf x)f(\mathbf x)\, d\mathbf x=\lim_{a\to 0}\frac{\tilde\mathcal E(\varrho+af)-\tilde\mathcal E(\varrho)}{a}. \end{equation} As in~\cite{chen2019eikonal}, for a given shape $R_0$ and an arbitrary shape $R$ that is close to $R_0$, one can choose $\varrho=\chi_{R_0}$ and $\delta\varrho=\chi_R-\chi_{R_0}$ such that the second term in the right-hand side of Eq.~\eqref{eq_LinearAppro} can be expressed as \begin{equation} \label{eq_LinearApprox2} \int_\Omega\delta\varrho\,\xi d\mathbf x=\int_\Omega\xi\,\chi_R d\mathbf x-\int_\Omega\xi\,\chi_{R_0} d\mathbf x. \end{equation} The first term $\int_\Omega\xi\,\chi_R d\mathbf x$ of Eq.~\eqref{eq_LinearApprox2} is identical to the right-hand side of Eq.~\eqref{eq_GeneralFunctional}, where the velocity $\xi$ is associated to the given shape $R_0$. We take the piecewise constants-based functional~\eqref{eq_PConst} as an example for the computation of the velocity $\xi$. In this case, one can set $\tilde\mathcal E(\chi_{R})=\mathcal E(\mathcal C)$ such that \begin{equation*} \tilde\mathcal E(\chi_{R})=\int_{\Omega}\Big(\chi_{R} \,\|I-\mathbf{c}_1\|^2+(1-\chi_R)\,\|I-\mathbf{c}_2\|^2\Big)d\mathbf x, \end{equation*} For a given shape $R_0$, the velocity $\xi(\mathbf x)$ at $\chi_{R_0}$ can be computed by Eq.~\eqref{eq_ShapeGradient} as follows \begin{equation*} \xi(\mathbf x)= \|I(\mathbf x)-\mathbf{c}_1\|^2-\|I(\mathbf x)-\mathbf{c}_2\|^2, \end{equation*} where $\mathbf{c}_1$ and $\mathbf{c}_2$ are estimated using Eq.~\eqref{eq_Means} associated to $R_0$. \subsection{Metrics for Anisotropic and Asymmetric Geodesic Curves} \label{subsec_SpatialMetric} In geodesic paths-based image segmentation, most of existing approaches usually utilize a type of Riemannian metrics based on the edge-based features~\cite{appleton2005globally,mille2009geodesically,mille2015combination}. In order to take image edge asymmetry features into consideration, we make use of a Finsler metric with an asymmetric quadratic form~\cite{chen2018asymmetric,duits2018optimal}. Let $\mathbb S_2^+$ be a set collecting all the positive definite symmetric matrices of size $2\times2$. Basically, the asymmetric quadratic metric $\mathcal F:=\mathcal F^{\rm AQ}$ can be formulated by a tensor field $\mathcal M:\Omega\to\mathbb S_2^+$ and a vector field $\omega:\Omega\to\mathbb R^2$ \begin{equation} \label{eq_AsyQuad} \mathcal F^{\rm AQ}(\mathbf x,\mathbf u)=\sqrt{\langle\mathbf u,\mathcal M(\mathbf x)\mathbf u \rangle+\langle\omega(\mathbf x),\mathbf u\rangle_+^2}\,, \end{equation} where $\langle\mathbf u_1,\mathbf u_2\rangle_+=\max\{0,\langle\mathbf u_1,\mathbf u_2\rangle\}$ is the positive part of $\langle\mathbf u_1,\mathbf u_2\rangle$ over $\mathbb R^2$, and $\langle\mathbf u_1,\mathbf u_2\rangle_+^2=(\langle\mathbf u_1,\mathbf u_2\rangle_+)^2$. The computation of the tensor field $\mathcal M$ and the vector field $\omega$ relies on the the matrices $\mathcal W(\mathbf x)$ (see Eq.~\eqref{eq_W}), which consists of both the image edge appearance and anisotropy features. For an edge point $\mathbf x$, the eigenvector $\vartheta(\mathbf x)\in\mathbb R^2$ of the matrix $\mathcal W(\mathbf x)$ corresponding to the smaller eigenvalue is perpendicular to the edge direction at $\mathbf x$. Thus, we can utilize $\vartheta(\mathbf x)^\perp$, the perpendicular vector of $\vartheta(\mathbf x)$, to characterize the edge anisotropy feature at $\mathbf x$. With these definitions, the tensor field $\mathcal M$ can be expressed as follows: \begin{align} \label{eq_EdgeM} \mathcal M(\mathbf x)=\exp&(\alpha g(\mathbf x))\,\vartheta(\mathbf x)^\perp\otimes\vartheta(\mathbf x)^\perp\nonumber\\ &+\exp(\tilde\alpha g(\mathbf x))\vartheta(\mathbf x)\otimes\vartheta(\mathbf x), \end{align} where $\mathbf u_1\otimes \mathbf u_2=\mathbf u_1\mathbf u_2^T,\forall \mathbf u_1,\mathbf u_2\in\mathbb R^2$. The parameters $\alpha,\,\tilde\alpha\in\mathbb R$ (s.t. $\tilde\alpha\geq\alpha$) controls the anisotropy ratio of $\mathcal M(\mathbf x)$. For the sake of simplicity, we set $\tilde\alpha=0$ and $\alpha<0$ to generate anisotropic tensors $\mathcal M(\mathbf x)$. In order to compute the vector field $\omega$, we first consider the gradients of the Gaussian-smoothed images, denoted by $\varpi:\Omega\to\mathbb R^2$, expressed as \begin{equation} \label{eq_asyGradient} \varpi(\mathbf x)=\frac{1}{3}\sum_{k=1}^3 (\nabla G_\sigma\ast I_k)(\mathbf x). \end{equation} Obviously, the edge asymmetry features are carried out by the vector field $\varpi$. At an edge point $\mathbf x$, the vector $\varpi(\mathbf x)$ is perpendicular to the edge tangent at this point. Thus the vector field $\omega$ can be generated using $\varpi$ as follows \begin{equation} \omega(\mathbf x)= \begin{cases} \lambda\mathbf{M}\varpi(\mathbf x)/\|\varpi(\mathbf x)\|,&\text{if~}\|\varpi(\mathbf x)\|\neq 0\\ \mathbf{0},&\text{otherwise}, \end{cases} \end{equation} where $\mathbf M$ is a \emph{counter-clockwise} rotation matrix with rotation angle $\pi/2$ and where $\lambda\in\mathbb R$ is a scalar parameter. Let $\tilde\mathcal C$ be a closed curve defined over $[0,1]$ that parameterizes the target boundary in a \emph{counter-clockwise} order\footnote{In the remaining of this paper, we assume that all the closed curves are parameterized in a counter-clockwise order.}. The sign of the parameter $\lambda$ is chosen being such that the scalar products $\langle \tilde\mathcal C^\prime(u),\omega(\tilde\mathcal C(u))\rangle<0,~\forall u\in[0,1]$, are satisfied as much as possible. As a consequence, the metric $\mathcal F^{\rm AQ}$ is suitable for handling images satisfying a coherence prior on image gradients, which can be formulated as: the scalar products $\langle\varpi(\tilde\mathcal C(u)),\mathcal N(u)\rangle$ along most parts of $\tilde\mathcal C$ have the identical sign~\cite{chen2019active,kimmel2003regularized,zach2009globally}, where $\mathcal N(u)$ is the unit normal to $\tilde\mathcal C(u)$. In Fig.~\ref{fig_ColorCoding}c, we illustrate an example for the visualization of the vector field $\varpi$ using the tool of color coding. The edge appearance feature map carried out by the function $g$ defined in Eq.~\eqref{eq_Magnitude} is shown in Fig.~\ref{fig_ColorCoding}b. In Fig.~\ref{fig_ColorCoding}d, we illustrate the geodesic distances associated to the metric $\mathcal F^{\rm AQ}$, which exhibits strongly asymmetric property. \noindent\emph{Remark}. In many scenarios, the image segmentations can benefit from the prior on the image gradients as stated above. However, in case the prior is not satisfied, one can make use of an anisotropic Riemannian metric as a reduction of $\mathcal F^{\rm AQ}$ \begin{equation} \label{eq_RiemannReduction} \mathcal F^{\rm R}(\mathbf x,\mathbf u)=\sqrt{\langle\mathbf u,\mathcal M(\mathbf x)\mathbf u\rangle}, \end{equation} by setting the vector field $\omega\equiv\mathbf{0}$. \subsection{Metrics for Curvature-penalized Geodesic Curves} \label{subsec_Curvature} The curvature-regularized minimal path approaches~\cite{chen2017global,duits2018optimal,mirebeau2018fast} search for globally minimizing paths in an orientation-lifting domain $\mathbb M=\Omega\times\mathbb S^1$. Any point $\tilde\mathbf x=(\mathbf x,\theta)\in \Omega\times\mathbb S^1$ is made up of a physical position $\mathbf x\in\Omega$ and an angular coordinate $\theta\in\mathbb S^1$. In the proposed model, the component $\mathcal F$ of the metric $\mathscr Q_\mathbf z$ in Eq.~\eqref{eq_targetMetric} can be a metric with curvature regularization. Examples for curvature-penalized geodesic approaches may involve the Euler-Mumford elastica geodesic model~\cite{chen2017global} and the Reeds–Shepp forward model~\cite{duits2018optimal}. The key idea for both models is to represent the tangent directions of a smooth planar curve $\gamma:[0,1]\to\Omega$ via an orientation lifting $\varphi:[0,1]\to\mathbb S^1$ such that for any $u\in[0,1]$ \begin{equation} \label{eq_OnWay} \gamma^\prime(u)=\|\gamma^\prime(u)\|\mathbf n(\varphi(u)), \end{equation} where $\mathbf n(\theta)=(\cos\theta,\sin\theta)^T$. Simple calculation yields that the curvature $\kappa:[0,1]\to\mathbb R$ of a curve $\gamma$ can be denoted by the ratio of $\varphi^\prime$ and $\|\gamma^\prime\|$, i.e. $\kappa=\varphi^\prime/\|\gamma^\prime\|$. The weighted curve length involving the curvature $\kappa$ along a curve $\tilde\gamma=(\gamma,\varphi):[0,1]\to\Omega\times\mathbb S^1$ satisfying~\eqref{eq_OnWay} can be formulated as \begin{align} \label{eq_MetricInterpretation2} \mathcal L(\tilde\gamma)&=\int_0^1 \mathcal P(\tilde\gamma(u))\,\big(1+\beta\kappa(u)^2\big)^\varsigma \|\gamma^\prime(u)\|\,du\\ &=\int_0^1 \mathcal P(\tilde\gamma(u))\,\left(1+\frac{\beta\varphi^\prime(u)^2}{\|\gamma^\prime(u)\|^2}\right)^\varsigma \|\gamma^\prime(u)\|\,du\nonumber\\ &=\int_0^1\mathcal F(\tilde\gamma(u),\tilde\gamma^\prime(u))\,du, \label{eq_MetricInterpretation} \end{align} where $\mathcal P:\Omega\times\mathbb S^1\to\mathbb R^+$ is an orientation-dependent function and $\beta\in\mathbb R^+$ is a parameter that weights the importance of the curvature. The metric $\mathcal F$ can be expressed for any point $\tilde\mathbf x=(\mathbf x,\theta)\in\Omega\times\mathbb S^1$ and any vector $\tilde\mathbf u=(\mathbf u,\nu)\in\mathbb R^3$ \begin{equation*} \mathcal F(\tilde\mathbf x,\tilde\mathbf u)= \begin{cases} \mathcal P(\tilde\mathbf x)\left(1+\frac{\beta\nu^2}{\|\mathbf u\|^2}\right)^\varsigma\|\mathbf u\|,&\text{if~} \mathbf u=\mathbf n(\theta)\|\mathbf u\|,\\ \infty,&\text{otherwise}. \end{cases} \end{equation*} The metric $\mathcal F$ used in Eq.~\eqref{eq_MetricInterpretation} with $\varsigma=1$ and $\varsigma=1/2$ respectively corresponds to the Euler-Mumford elastica metric~\cite{chen2017global} and the Reeds-Shepp forward metric~\cite{duits2018optimal}. Finally, the data-driven function $\mathcal P$ can be defined as~\cite{chen2017global} \begin{equation} \label{eq_OrienPotential} \mathcal P(\mathbf x,\theta)=\exp\left(\alpha\,\langle\mathbf n(\theta)^\perp,\mathcal W(\mathbf x)\mathbf n(\theta)^\perp\rangle\right), \end{equation} where $\alpha<0$ is a scalar-valued parameter. In this definition, the term $\langle\mathbf n(\theta)^\perp,\mathcal W(\mathbf x)\mathbf n(\theta)^\perp$ stands for the orientation score. One can point out that if the vector $\mathbf n(\theta)^\perp$ is proportional to the edge tangents for edge points $\mathbf x$, the values of $\mathcal P(\mathbf x,\theta)$ are low, satisfying the requirement in image segmentation applications. \begin{figure*}[t] \centering \includegraphics[width=17.5cm]{images/fig3} \caption{Illustration for the proposed dual-cut scheme. (\textbf{a}) A synthetic image with a red dot denoting the landmark point $\mathbf z$. (\textbf{b}) The blue solid line indicates $\ell_\mathbf z^+$, the red line is the geodesic path $\mathcal G_{\mathbf q}$ obtained in the first step and the yellow dot indicates the sampled point $\mathbf q$. (\textbf{c}) The green and yellow dots are the points $\mathbf a$ and $\mathbf b$. The red line is the $\Gamma_{\mathbf a,\mathbf b}$ which is a portion of $\mathcal G_{\mathbf q}$ and the blue line denotes $\ell^-_\mathbf z$. (\textbf{d}) The geodesic path $\mathcal G_{\mathbf b,\mathbf a}$ denoted by red line. (\textbf{e}) The target closed curve $\mathcal C$, see text. (\textbf{f}) and (\textbf{h}) The geodesic distance maps superimposed on the original image, which correspond to figures (b) and (d). (\textbf{g}) The region $\Theta$ tagged as white color } \label{fig_Dualcut} \end{figure*} \section{Dual-cut Scheme for Closed Curve Detection} \label{sec_DualCut} Finding image segmentation under a geodesic framework usually amounts to building simple and closed curves made up of geodesic paths. In this section, we introduce a dual-cut scheme, which is an adaption of the circular geodesic model~\cite{appleton2005globally}, to efficiently solve the interactive image segmentation problems. In the circular geodesic model, the basic idea is to impose a constraint to the image domain $\Omega$ by means of a cut, where the origin of the domain $\Omega$ is instantiated in the given landmark point $\mathbf z$, and the cut is placed infinitesimally beneath the non-negative $x$-axis. Hereinafter we denote by $\ell^+_\mathbf z$ the non-negative $x$-axis. The use of the cut adds disconnection constraint between the two sides of the cut, which favours to detect \emph{cut-convexity} curves~\cite{appleton2005globally}. For convenience, we denote by $\Xi_\mathbf z$ the set collecting all the cut-convexity curves with respect to the given landmark point $\mathbf z$ such that \begin{align} \Xi_\mathbf z:=\Big\{\gamma\in\Lip([0,1],\Omega);~&\mathbf z\in R_\gamma,\,\gamma(0)=\gamma(1)\in\ell^+_\mathbf z,\nonumber\\ &\gamma(u)\notin\ell^+_\mathbf z,\forall u\in(0,1)\Big\}, \end{align} where $R_\gamma$ represents the interior region of closed curve $\gamma$. We emphasize that the point $\mathbf z$ is not passed by $\gamma$. \subsection{Initialization} \label{subsec_Initializations} The generation of an initial shape $R_{0}\subset\Omega$ such that $\mathbf z\in R_0$ is the first stage of the proposed method. Basically, this shape $R_0$ is expected to be covered by the target region as much as possible. Towards this purpose, we choose to construct $R_0$ by means of a front propagation procedure expanding from $\mathbf z$. Specifically, this can be done by thresholding a geodesic distance map which admits the solution to the following isotropic Eikonal PDE \begin{equation} \label{eq_InitializationPDE} \|\nabla\mathcal U_{\mathbf z}(\mathbf x)\|=\phi(\mathbf x),\quad\forall\mathbf x\in\Omega\backslash\{\mathbf z\}, \end{equation} with boundary condition $\mathcal U_{\mathbf z}(\mathbf z)=0$. The function $\phi:\Omega\to\mathbb R^+$ is an edge indicator defined by \begin{equation} \phi(\mathbf x)=\exp(\tau\,g(\mathbf x))-\tau_\epsilon, \end{equation} where $\tau\in\mathbb R^+$ and $\tau_\epsilon\in(0,1)$ are two constants, and $g$ is the magnitude of image gradients as defined in Eq.~\eqref{eq_Magnitude}. In our experiments, we fix $\tau=5$ and $\tau_\epsilon=0.99$ for all the numerical experiments. Then, the shape $R_{0}$ can be generated by \begin{equation} \label{eq_InitialShape} R_0=\{\mathbf x\in\Omega;\,\mathcal U_{\mathbf z}(\mathbf x)\leq T\}, \end{equation} where $T\in \mathbb R^+$ is a thresholding value. Once the construction of $R_0$ is done, we can estimate the shape gradient $\xi$ with respect to $R_{0}$ using Eq.~\eqref{eq_ShapeGradient}. \subsection{Dual-cut Scheme for Closed Contour Detection} \label{subsec_Principle} Suppose that the set $\Theta_\mathbf z$ has been built by means of Eq.~\eqref{eq_Bound}. Basically, the proposed dual-cut scheme can be divided into two steps, where the target is to seek a simple closed curve as the concatenation of two disjoint geodesic paths. \subsubsection{Step I} In the first step, among all the intersection points between the non-negative $x$-axis $\ell_\mathbf z^+$ and the boundary $\partial\Theta_\mathbf z$, we choose a point $\mathbf q\in\ell_\mathbf z^+$ that is closest to $\mathbf z$ in the sense of Euclidean distance. The goal in this step is to extract a geodesic curve from the set $\Xi_\mathbf z$. Such a geodesic path can be generated by solving the following minimizing problem \begin{equation} \label{eq_CutGeo} \mathcal G_{\mathbf q}=\underset{\gamma\in\Xi_\mathbf z}{\arg\min}\left\{\int_0^1 \mathscr Q_\mathbf z(\gamma,\gamma^\prime)du;\gamma(0)=\gamma(1)=\mathbf q\right\}. \end{equation} We give an example in Fig.~\ref{fig_Dualcut}b for this step using a synthetic image. In this figure, the red and yellow dots respectively indicate the points $\mathbf z$ and $\mathbf q$, and the cyan line represents $\ell^+_\mathbf z$. By the definition~\eqref{eq_CutGeo}, the closed geodesic curve $\mathcal G_{\mathbf q}$ is allowed to pass through the non-negative $x-$axis only once. As a result, $\mathcal G_{\mathbf q}$ may fail to delineate the boundary segments which pass through $\ell^+_\mathbf z$ multiple times. This can be seen from Fig.~\ref{fig_Dualcut}b, where the boundary segment at the top right corner is missed. In order to overcome this issue, we consider to use the non-positive $x$-axis, referred to as $\ell_\mathbf z^-$, to tack another geodesic path in order to delineate the boundary segments missed by $\mathcal G_\mathbf q$. \subsubsection{Step II} \label{subsubsec_StepII} From the first step, we have obtained a simple closed geodesic curve $\mathcal G_{\mathbf q}$, which intersects with non-positive axis $\ell_\mathbf z^-$ at least once. Among these intersection points, we choose the first and the last points, respectively denoted by $\mathcal G_\mathbf q(u_1)=\mathbf a\in\ell^-_\mathbf z$ and $\mathcal G_\mathbf q(u_2)=\mathbf b\in\ell^-_\mathbf z$ such that $0<u_1\leq u_2<1$, in order to track a new geodesic curve. \noindent\emph{In case $\mathbf a\neq\mathbf b$}. We denote by $\mathcal G_\mathbf q|_{u_1\to u_2}$ the portion of the geodesic path $\mathcal G_{\mathbf q}$ traveling from $\mathbf a$ to $\mathbf b$, and denote by $\Gamma_{\mathbf a,\mathbf b}$ the re-parameterization of $\mathcal G_\mathbf q|_{u_1\to u_2}$ over the range $[0,1]$, i.e. \begin{equation} \Gamma_{\mathbf a,\mathbf b}(0)=\mathbf a,\quad\Gamma_{\mathbf a,\mathbf b}(1)=\mathbf b. \end{equation} An example for the path $\Gamma_{\mathbf a,\mathbf b}$ can be seen from Fig.~\ref{fig_Dualcut}c, indicated by a red line. Let $A\subset\Omega$ be a set which is regarded as the union of closed regions enclosed by the non-positive $x$-axis $\ell_\mathbf z^-$ and $\Gamma_{\mathbf a,\mathbf b}$, see Fig.~\ref{fig_Dualcut}g for an example. We expect to seek an open geodesic path $\mathcal G_{\mathbf b,\mathbf a}$, which links $\mathbf b$ to $\mathbf a$ and is forbidden to pass through $A$. For this purpose, we consider a set of curves \begin{align*} \Upsilon_{\mathbf z}=\Big\{\gamma\in\Lip([0,1],\Omega);~&\gamma(0)\in\ell_\mathbf z^-,~\gamma(1)\in\ell_\mathbf z^-,\\ &\gamma(u)\notin\ell^-_\mathbf z\cup A,\forall u\in(0,1)\Big\} \end{align*} yielding that \begin{equation} \label{eq_CutGeo2} \mathcal G_{\mathbf b,\mathbf a}=\underset{\gamma\in\Upsilon_\mathbf z}{\arg\min}\left\{\int_0^1 \mathscr Q_\mathbf z(\gamma,\gamma^\prime)du\right\}s.t.\, \begin{cases} \gamma(0)=\mathbf b,\\ \gamma(1)=\mathbf a. \end{cases} \end{equation} We illustrate an example for such a geodesic path $\mathcal G_{\mathbf b,\mathbf a}$ in Fig.~\ref{fig_Dualcut}d. Similar to the classical geodesic tracking procedure as introduced in Section~\ref{subsec_MP}, the minimization of the problems~\eqref{eq_CutGeo} and~\eqref{eq_CutGeo2} can be addressed by estimating geodesic distance maps associated to the respective metrics $\mathscr Q_\mathbf z$, implemented via a variant of the fast marching methods~\cite{mirebeau2018fast,mirebeau2019riemannian} in conjunction with $\ell^+_\mathbf z$ and $\ell^-_\mathbf z$, see Section~\ref{subsec_NI}. Now we can build the target closed curve $\mathcal C\in\Lip([0,1],\Omega)$ as the concatenation of two paths $\Gamma_{\mathbf a,\mathbf b}$ and $\mathcal G_{\mathbf b,\mathbf a}$, i.e. \begin{equation} \label{eq_TargetCurve} \mathcal C(u)=\left(\Gamma_{\mathbf a,\mathbf b}\doublecup\mathcal G_{\mathbf b,\mathbf a}\right)(u),\quad \forall u\in[0,1] \end{equation} where $\doublecup$ is a concatenation operator of two curves $\gamma_1$ and $\gamma_2:[0,1]\to\Omega$ \begin{equation} \label{eq_Concatenation} (\gamma_1\doublecup\gamma_2)(u)= \begin{cases} \gamma_1(u),&\text{if~} u\in[0,1/2],\\ \gamma_2(u),&\text{if~} u\in[1/2,1]. \end{cases} \end{equation} \begin{figure*}[t] \centering \includegraphics[width=17.5cm]{images/fig4} \caption{Image segmentation derived from the proposed model using scribbles. (\textbf{a}) User-provided scribbles indicated by a green line. \textbf{b} Image segmentation contour indicated by a blue line. (\textbf{c}) Close-up view of the segmentation contour in Figure~(b). (\textbf{d}) An additional scribble (white line) used as a barricade. (\textbf{e}) Image segmentation contour constrained by all the scribbles. (\textbf{f}) Close-up view of the segmentation contour in Figure (e)} \label{fig_Scribble} \end{figure*} \noindent\emph{In case $\mathbf a=\mathbf b$}. In particular, if the path $\mathcal G_{\mathbf q}$ crosses over the non-positive $x$-axis $\ell^-_\mathbf z$ just once, then we have $\mathbf a=\mathbf b$. In this case, the closed set $A=\emptyset$ and the geodesic paths $\mathcal G_{\mathbf b,\mathbf a}$ can be still defined by~\eqref{eq_CutGeo2}. In this case, the concatenation operator is no longer needed such that the target curve $\mathcal C=\mathcal G_{\mathbf b,\mathbf a}$. \noindent\emph{Using curvature-penalized geodesic paths}. In this section, the geodesic paths are assumed to be defined over the image domain $\mathbb M=\Omega$, which are suitable for the case of asymmetric quadratic metrics $\mathcal F^{\rm AQ}$. With respect to the curvature-penalized geodesic metrics over the domain $\mathbb M:=\Omega\times\mathbb S^1$, the minimization problems~\eqref{eq_CutGeo} and~\eqref{eq_CutGeo2} respectively get to be \begin{equation} \label{eq_CutGeo2} \tilde\mathcal G_{\mathbf q}=\mathop{\arg\min}_{\scriptstyle\tilde\gamma=(\gamma,\varphi)\in\Lip([0,1],\mathbb M) \atop \scriptstyle\tilde\gamma(0)=\tilde\gamma(1)=\tilde\mathbf q } \left\{\int_0^1 \mathscr Q_\mathbf z(\tilde\gamma,\tilde\gamma^\prime)du;\gamma\in\Xi_\mathbf z\right\} \end{equation} and \begin{equation} \label{eq_CutGeo3} \tilde\mathcal G_{\mathbf b,\mathbf a}=\mathop{\arg\min}_{\scriptstyle\tilde\gamma=(\gamma,\varphi)\in \Lip([0,1],\mathbb M) \atop \scriptstyle\tilde\gamma(0)=\tilde\mathbf b,\tilde\gamma(1)=\tilde\mathbf a }\left\{\int_0^1 \mathscr Q_\mathbf z(\tilde\gamma,\tilde\gamma^\prime)du;\gamma\in\Upsilon_{\mathbf z}\right\}. \end{equation} When applying the curvature-penalized geodesic paths for the proposed dual-cut scheme, the sampled point $\mathbf q$, used in the first step, is lifted to $\tilde\mathbf q=(\mathbf q,\theta_\mathbf q)$ such that \begin{equation*} \theta_\mathbf q=\underset{\theta\in(0,\pi)}{\arg\min}\,\mathcal P(\mathbf q,\theta). \end{equation*} In the second step, the intersection points $\mathbf a$ and $\mathbf b$ are detected using the physical projection $\mathcal G_\mathbf q$ of the orientation-lifted geodesic path $\tilde\mathcal G_\mathbf q=(\mathcal G_\mathbf q,\varphi_\mathbf q)$, see Eq.~\eqref{eq_CutGeo2}. Again, in order to generate the orientation-lifted geodesic path $\tilde\mathcal G_{\mathbf b,\mathbf a}$, one should respectively lift $\mathbf a$ and $\mathbf b$ to $\tilde\mathbf a=(\mathbf a,\theta_\mathbf a)$ and $\tilde\mathbf b=(\mathbf b,\theta_\mathbf b)$ \begin{equation*} \theta_\mathbf a=\underset{\theta\in(-\pi,0)}{\arg\min}\,\mathcal P(\mathbf a,\theta),\quad \theta_\mathbf b=\underset{\theta\in(-\pi,0)}{\arg\min}\,\mathcal P(\mathbf b,\theta). \end{equation*} Note that the detection of the orientations $\theta_\mathbf q,\,\theta_\mathbf a$ and $\theta_\mathbf b$ coincides with the assumption that the curves $\mathcal G_\mathbf q$ and $\mathcal C$ are parameterized in a counter-clockwise order. \begin{figure*}[t] \centering \includegraphics[width=17.5cm]{images/fig5} \caption{Influence of the implicit region-based homogeneity features on the final segmentation contours. (\textbf{b}) and (\textbf{c}) Segmentations from the CombPaths and VCGeo models, respectively. (\textbf{d}) and (\textbf{e}) Segmentation results derived from the proposed DualCut-Asy and DualCut-RSF models, respectively} \label{fig_syn} \end{figure*} \begin{figure*}[t] \centering \includegraphics[width=17cm]{images/fig6} \caption{Qualitative comparison results with the CVF model, the VCGeo model and the CombPaths model. The segmentation contours are indicated by red lines. The while in column $1$ are initial contours for the CVF model. The cyan dots in columns $2$ and $4$ indicate the user-provided points for the VCGeo and DualCut-Asy models. The yellow dots are the input points for the CombPaths model} \label{fig_examples_natural} \end{figure*} \subsection{Extending User Intervention from a Point to Scribbles} \label{subsec:Scribbles} In the dual-cut closed curve detection scheme as introduced in Section~\ref{subsec_Principle}, the user input is supposed to be a single point used to locate the target region. As in many interactive image segmentation approaches~\cite{boykov2006grapy,grady2006random,chen2018asymmetric}, scribbles often serve as seeds to provide constraint for image segmentation. In this section, we present a method to add user-provided scribbles to the proposed dual-cut model. In the basic setting of the proposed model, a scribble $\mathcal S$ can be modeled as a continuous curve line placed in the image domain $\Omega$. The scribbles considered can be classified into two categories. The first one serves as foreground seeds to locate the regions we attempt to search for (see Fig.~\ref{fig_Scribble}a for an example), from which one can sample the landmark point $\mathbf z\in\mathcal S$. In addition, the target curves $\mathcal G$ defined in Eq.~\eqref{eq_TargetCurve} are supposed to surround the scribbles $\mathcal S$. In practice, the scribbles $\mathcal S$ are used to stop the fast marching fronts to pass through it. The initial shape $R_0$ can be constructed by Eq.~\eqref{eq_InitialShape}, where the associated geodesic distance map $\mathcal U_\mathcal S$ satisfies the isotropic Eikonal PDE with respect to $\phi$, as used in Eq.~\eqref{eq_InitializationPDE}. In some complicated scenarios, favorable segmentations may require more user intervention, in addition to the scribbles tagged as foreground. In Fig.~\ref{fig_Scribble}b, one can see that the segmentation contour can accurately delineate most of the target boundaries except for a high concave part, where the close-up view for this part is depicted in Fig.~\ref{fig_Scribble}c. In order to overcome this problem, we consider the second type of scribbles which serves as barricades to prevent the geodesic paths from crossing them. Furthermore, no label is assigned to the second type of scribbles. We illustrate the segmentation result using the second type of scribbles in Figs.~\ref{fig_Scribble}e and~\ref{fig_Scribble}f. \begin{algorithm}[!t] \caption{\textsc{Fast Marching Method}} \label{algo_FM} \begin{algorithmic} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \Require A source point $\mathbf s$ and a set $\Im_{\rm end}$; \Ensure Geodesic distance map $\mathcal U_\mathbf s$; \renewcommand{\algorithmicrequire}{\textbf{Initialization}:} \Require \State $\bullet$ Set $\mathcal U_\mathbf s(\mathbf s)\gets0$ and set $\mathcal U_\mathbf s(\mathbf x)\gets\infty$, $\forall \mathbf x\in\mathbb Z^n\backslash\{\mathbf s\}$. \State $\bullet$ Set $\mathcal V(\mathbf x)\gets\Trial$, $\forall \mathbf x\in\mathbb Z^n$. \State $\bullet$ Set $\mathbf x_{\rm min}\gets\mathbf s$ and $\StoppingFlag$ $\gets$ FALSE. \end{algorithmic} \begin{algorithmic}[1] \renewcommand{\algorithmicrequire}{\textbf{Main Loops}:} \Require \While{$\StoppingFlag$ $\neq$ TRUE} \State Find $\mathbf x_{\rm min}$ minimizing $\mathcal U_\mathbf s$ among all $\Trial$ points; \State $\mathcal V(\mathbf x_{\rm min})\gets\Accepted$; \If{$\mathbf x_{\rm min}\in\Im_{\rm end}$} \State Set $\StoppingFlag$ $\gets$ TRUE. \EndIf \For{all $\mathbf x_{\rm n}$ s.t. $\mathcal V(\mathbf x_{\rm n})= \Trial$ and $\mathbf x_{\rm min}\in\Lambda(\mathbf x_{\rm n})$} \If{$\Satisfactory(\mathbf x_{\rm min},\mathbf x_{\rm n})=$TRUE} \label{algLine_Satisf} \State Update the value $\mathcal U_\mathbf s\mathbf x_{\rm n})$ by solving the upwind discretization of the Eikonal PDE~\eqref{eq_HamiltionHJB}. \label{algLine_Update} \Else \State $\mathcal U_\mathbf s(\mathbf x_{\rm n})\gets+\infty$; \EndIf \EndFor \EndWhile \end{algorithmic} \end{algorithm} \subsection{Numerical Implementation} \label{subsec_NI} In Section~\ref{subsec_Principle}, we have introduced the dual-cut scheme for extracting closed curves. A crucial ingredient is to track two geodesic paths using the sets $\Xi_\mathbf z$ and $\Upsilon_{\mathbf z}$. In this section, we show that these geodesic paths can be efficiently generated by an adaption of state-of-the-art Hamiltonian Fast Marching method (HFM). We first consider the numerical implementation in the 2D domain, which can be simply extended to the orientation-lifted case. The HFM method is based on the reformulation of the Eikonal equation~\eqref{eq_FinslerEikonal} \begin{equation} \label{eq_HamiltionHJB} \mathcal H(\mathbf x,\nabla\mathcal U_\mathbf s(\mathbf x))=\frac{1}{2},~\forall \mathbf x\in\Omega\backslash\{\mathbf s\},\\ \end{equation} with $\mathcal U_\mathbf s(\mathbf s)=0$ as the boundary condition, where $\mathcal H$ is the Hamiltonian with respect to the metric $\mathcal F$, defined as \begin{equation*} \mathcal H(\mathbf x,\mathbf v) = \sup_{\mathbf u\in \mathbb R^2}\left\{\langle\mathbf u,\mathbf v\rangle - \frac{1}{2} \mathcal F(\mathbf x,\mathbf u)^2\right\}. \end{equation*} The first stage for tracking the geodesic paths $\mathcal G_\mathbf q$ and $\mathcal G_{\mathbf b,\mathbf a}$ respectively defined in Eqs.~\eqref{eq_CutGeo} and~\eqref{eq_CutGeo2} is implemented by estimating geodesic distance maps. In the HFM method, the estimation of these distance maps is performed in a regular grid $\mathbb M_h$ with $h$ being the discretization scale. The update of distance values is implemented by solving a finite differences discretization of the Eikonal equation~\eqref{eq_HamiltionHJB}, based on the adaptive stencils $\Lambda$. For each grid point $\mathbf x\in\mathbb M_h$, the stencil $\Lambda(\mathbf x)$ is made up of a finite number of offsets $\mathbf e_j\in\mathbb Z^2$ with integer coordinates, which are constructed using a discrete geometry tool of Voronoi’s first reduction of quadratic forms~\cite{mirebeau2018fast,mirebeau2019riemannian}. The constraints used to define the sets $\Xi_\mathbf z$ and $\Upsilon_{\mathbf z}$ are respectively introduced by the axes $\ell_\mathbf z^+$ and $\ell_\mathbf z^-$, which can be incorporated into the HFM by removing unsatisfactory offsets from some stencils $\Lambda(\mathbf x)$. Denote by $\mathbf y_j=\mathbf x+h\mathbf e_j\in\mathbb M_h,\,\forall\mathbf e_j\in\Lambda(\mathbf x)$ the neighbourhood points of a grid point $\mathbf x\in\mathbb M_h$. When computing the geodesic curve $\mathcal G_\mathbf q$ in the first step (resp. the geodesic curve $\mathcal G_{\mathbf b,\mathbf a}$ in the second step), we consider the following two conditions: \begin{itemize} \item[(i)] If $\mathbf x\notin \ell^+_\mathbf z\cap\mathbb M_h$ (resp. $\mathbf x\notin \ell^-_\mathbf z$) and the segment $[\mathbf x,\mathbf y_i]$ intersects with $\ell^+_\mathbf z$ (resp. with $\ell^-_\mathbf z$). \item[(ii)] If $\mathbf x\in \ell^+_\mathbf z\cap\mathbb M_h$ (resp. $\mathbf x\in \ell^-_\mathbf z$) and the scalar product $\langle\mathbf y_j-\mathbf x,(0,1)^T\rangle<0$ (resp. $\langle\mathbf y_j-\mathbf x,(0,-1)^T\rangle<0$). \end{itemize} The offsets $\mathbf e_j$ will be removed from the stencil $\Lambda(\mathbf x)$ if they satisfy either condition. Specifically, in the first step of the dual-cut scheme, we estimate a geodesic distance map $\mathcal U_\mathbf q$, which satisfies the Eikonal PDE~\eqref{eq_HamiltionHJB}. This is done by the HFM using the constrains related to $\ell^+_\mathbf z$, as formulated in Points (i) and (ii). While in the second step, likewise the distance map $\mathcal U_\mathbf q$, we estimate a geodesic distance map $\mathcal U_\mathbf b$ by the HFM with stencils following the constraints as stated in Points (i) and (ii) with respect to $\ell^-_\mathbf z$. In this step, we further take into account the set $A$ in addition to the conditions above, such that an offset $\mathbf e_j$ should be eliminated from the stencil $\Lambda(\mathbf x)$ if the grid point $\mathbf x+h\mathbf e_j\in A$. Based on the geodesic distance maps $\mathcal U_\mathbf q$ and $\mathcal U_\mathbf b$, one can respectively obtain the geodesic paths $\mathcal G_\mathbf q$ and $\mathcal G_{\mathbf b,\mathbf a}$, by solving the gradient descent ODEs~\eqref{eq_ODE}. We illustrate the geodesic distance maps superimposed on the original image in Figs.~\ref{fig_Dualcut}f and~\ref{fig_Dualcut}h, which are respectively generated in the first and second step of the proposed dual-cut scheme. In order to reduce the computation time, the HFM will be terminated once an end point $\mathbf x\in\Im_{\rm end}$ is reached by the fast marching fronts. In the first step of the proposed dual-cut model, the set $\Im_{\rm end}:=\{\mathbf y\in\mathbb M_h;\|\mathbf y-\mathbf q\|\leq\sqrt{2}h,\langle \mathbf y-\mathbf q,(0,-1)^T\rangle>0\}$. While in the second step, we use $\Im_{\rm end}:=\{\mathbf y\in\mathbb M_h;\|\mathbf y-\mathbf a\|\leq\sqrt{2}h,\langle \mathbf y-\mathbf a,(0,1)^T\rangle>0\}$. The main algorithm for estimating geodesic distance maps can be seen in Algorithm~\ref{algo_FM}. In this algorithm, the value of $\Satisfactory(\mathbf x,\mathbf y_j)$ is false if the offset $\mathbf e_j$ should be removed from the stencil $\Lambda(\mathbf x)$. Finally, with respect to the curvature-penalized metrics, each offset $\tilde\mathbf e_j=(\mathbf e_j,e_j^\theta)\in \mathbb Z^3$ yields a neighbourhood point $\tilde\mathbf y_j=(\mathbf y_j,\theta_j)=\tilde\mathbf x+h\tilde\mathbf e_j$. In this case, Points~(i) and (ii) are checked using $\mathbf e_j$ and the test associated to the set $A$ is examined using the physical position $\mathbf y_j$. \begin{figure}[t] \centering \subfigure[]{\includegraphics[width=4cm]{images/cmp_SampledPoints_Ceramic}}\,\subfigure[]{\includegraphics[width=4cm]{images/cmp_obstacle_Ceramic}}\\ \vspace{2mm} \subfigure[]{\includegraphics[width=8cm]{images/boxplot_Ceramic}} \caption{(\textbf{a}) The blue dots indicate a set of sampled points, each of which serves as the landmark point $\mathbf z$. (\textbf{b}) The scribbles of the second type which serve as obstacles. (\textbf{c}) Box plots of the Jaccard score values associated to the points shown in figure (a) for different models} \label{fig_examples_obstacle} \end{figure} \section{Experimental Results} \label{sec_Exp} In this section, we conduct the qualitative and quantitive comparison experiments with the vector field convolution (VFC) active contour model~\cite{li2007active}, a variant of the circular geodesic model (VCGeo), and the combination of paths (CombPaths) model~\cite{mille2015combination}. The brief introduction for the VCGeo model is presented in Appendix~\ref{appendix_VCGeo}. Finally, we use the abbreviation of DualCut-Asy (resp. DualCut-RSF) to represent the proposed dual-cut model with a spatial asymmetric quadratic metric (resp. Reeds-Shepp Forward metric). In this section, the quantitative evaluation is carried out by the Jaccard score, which measures the overlap between a segmented region $\mathbb{S}$ and the ground truth region $GT$ \begin{equation*} J(\mathbb{S},GT)=\frac{\#|\mathbb{S}\cap GT|}{\#|\mathbb{S}\cup GT|} \end{equation*} where $\#|\mathbb{S}|$ denotes the number of grid points involved in $\mathbb{S}$. \subsection{Parameter setting} In the proposed dual-cut model, the considered metrics $\mathscr Q_\mathbf z$, as defined in Eqs.~\eqref{eq_targetMetric}, are comprised of two components: the scalar-valued function $\psi_\mathbf z$ that implicitly encodes the region-based homogeneity features and the Finsler metrics $\mathcal F$. The parameter $\mu$ for $\psi_\mathbf z$ controls the importance of the regional information. If the region-based homogeneity terms used are suitable for the image data, one can assign large values to $\mu$ and small values, otherwise. Typically, we found that $\mu=0.1$ or $\mu=0.2$ can generate favorable segmentation results. For an asymmetric quadratic metric $\mathcal F^{\rm AQ}$ defined in Eq.~\eqref{eq_AsyQuad}, we should build the tensor field $\mathcal M$ and the vector field $\omega$ relying on the parameters $\alpha$ and $\lambda$, respectively. The values of $\alpha$ dominate the importance of the edge-based features and we found that satisfactory segmentations can be obtained for $\alpha\in[5,8]$. We invoke $\alpha=7$ and $|\lambda|=2$ unless otherwise specified. Note that the values $\sign(\lambda)$ are set in terms of the image gradients coherence prior and depend on the image data. In the following experiments, we take the Reeds-Sheep forward metric as the instance of the curvature-penalized metrics. In this case, the value of $\alpha=5$ is used for computing the orientation-dependent function $\mathcal P$, see Eq.~\eqref{eq_OrienPotential}. The parameter $\beta$ is a weighting parameter for the curvature term, see Eq.~\eqref{eq_MetricInterpretation2}. In principle, $\beta$ should be tuned for each individual image. Finally, when applying the curvature-penalized metrics for the proposed model, we set the discretization resolution of the orientation dimension to be $60$. \begin{figure*}[t] \centering \includegraphics[width=17.5cm]{images/fig8} \caption{Qualitative comparison results with the CVF model, the VCGeo model and the CombPaths model, evaluated on images interrupted by different noises. The red lines indicate the final segmentation contours. The blue sold lines in column $1$ are the initial curves for the CVF model. The blue dots in columns $2$ and $4$ represent the landmark point $\mathbf z$ for the VCGeo model and the proposed DualCut-RSF model, and the yellow dots in column $3$ are the input points for the CombPaths model} \label{fig_NoisedImages} \end{figure*} \noindent\emph{Initialization for the considered models}. The input of the proposed dual-cut model can be a landmark point $\mathbf z$ or a scribble $\mathcal S$ inside the target region. In the following experiments, we exploit the point-based user input for the proposed model, unless otherwise noted. We make use of the point $\mathbf z$ to initialize the VCGeo model for all the experiments. In addition, the initial contour for the VFC model is set as a circle centred at $\mathbf z$ with a given radius. Finally, for the CombPaths model, we extract four control points clockwisely distributed along the ground truth boundary of interest. These points are sampled by taking $\mathbf z$ as the origin of the image domain as before. Then the first control point is the intersection point between the positive $x$-axis and the ground truth boundary. Likewise to the first one, the second to the fourth points are detected respectively using the negative $y$-axis, the negative $x$-axis and the positive $y$-axis. \subsection{Comparison Results} One of the crucial contributions of the proposed dual-cut segmentation model lies at the introduction of the implicit region-based homogeneity information to guide the computation of geodesic paths. In contrast, the geodesic paths in both of the CombPaths and VCGeo models are dependent only on the edge-based features, which may yield bias toward the boundary segments of strong visibility, regardless of their Euclidean length. In Fig.~\ref{fig_syn}, we illustrate the effect from the region-based homogeneity terms in paths-based segmentation applications. In this test, the synthetic image used consists of two disjoint regions over the background. The region of interest lying at the bottom half of the image domain has highest gray levels. In Figs.~\ref{fig_syn}b and~\ref{fig_syn}c, the segmentation contours, as indicated by red lines, are generated from the CombPaths and VCGeo models, respectively. One can point out that each of these segmentation contours combines a boundary segment not belonging to the target. In Figs.~\ref{fig_syn}d and~\ref{fig_syn}e, the contours are generated using the proposed DualCut-Asy and DualCut-RSF models. One can see that integrating the region-based homogeneity features with the image gradients coherence prior and the curvature regularization indeed can accurately capture the desired target region, as depicted in Figs.~\ref{fig_syn}d and~\ref{fig_syn}e. \begin{table*}[t] \centering \caption{Quantitative comparisons between the VCF model, the VCGeo model, the CombPaths model and the proposed DualCut-RSF model in terms of the statistics of Jaccard scores over $20$ runs per image. Images $1$ to $3$ are respectively shown from rows $1$ to $3$ of Fig.~\ref{fig_NoisedImages}} \label{table_ResultNoise} \setlength{\tabcolsep}{5pt} \renewcommand{\arraystretch}{1.5} \begin{tabular}[t]{c c c c c c c c c c c c c c c c c c} \shline \multicolumn{1}{c}{\multirow{1}{*}{Images}}&\multicolumn{4}{l}{CVF}&\multicolumn{4}{l}{VCGeo}&\multicolumn{4}{l}{CombPaths}&\multicolumn{4}{l}{DualCut-RSF} \\ \cmidrule(lr){2-5} \cmidrule(lr){6-9}\cmidrule(lr){10-13}\cmidrule(lr){14-17} \multicolumn{1}{c}{}&\multicolumn{1}{c}{Mean}&\multicolumn{1}{c}{Max}&\multicolumn{1}{c}{Min}&\multicolumn{1}{l}{Std}&\multicolumn{1}{c}{Mean}&\multicolumn{1}{c}{Max}&\multicolumn{1}{c}{Min}&\multicolumn{1}{l}{Std}&\multicolumn{1}{c}{Mean}&\multicolumn{1}{c}{Max}&\multicolumn{1}{c}{Min}&\multicolumn{1}{l}{Std}&\multicolumn{1}{c}{Mean}&\multicolumn{1}{c}{Max}&\multicolumn{1}{c}{Min}&\multicolumn{1}{l}{Std}\\ \hline \multicolumn{1}{c}{Image 1}&\multicolumn{1}{c}{$0.13$}&\multicolumn{1}{c}{$0.22$}&\multicolumn{1}{c}{$0.09$}&\multicolumn{1}{l}{$0.04$} &\multicolumn{1}{c}{$0.59$}&\multicolumn{1}{c}{$0.83$}&\multicolumn{1}{c}{$0.10$}&\multicolumn{1}{l}{$0.29$} &\multicolumn{1}{c}{$0.80$}&\multicolumn{1}{c}{$0.96$}&\multicolumn{1}{c}{$0.66$}&\multicolumn{1}{l}{$0.09$} &\multicolumn{1}{c}{$0.96$}&\multicolumn{1}{c}{$0.96$}&\multicolumn{1}{c}{$0.93$}&\multicolumn{1}{l}{$\approx0$}\\ \multicolumn{1}{c}{Image 2}&\multicolumn{1}{c}{$0.17$}&\multicolumn{1}{c}{$0.25$}&\multicolumn{1}{c}{$0.10$}&\multicolumn{1}{l}{$0.05$} &\multicolumn{1}{c}{$0.48$}&\multicolumn{1}{c}{$0.82$}&\multicolumn{1}{c}{$0.10$}&\multicolumn{1}{l}{$0.25$} &\multicolumn{1}{c}{$0.55$}&\multicolumn{1}{c}{$0.97$}&\multicolumn{1}{c}{$0.01$}&\multicolumn{1}{l}{$0.42$} &\multicolumn{1}{c}{$0.98$}&\multicolumn{1}{c}{$0.98$}&\multicolumn{1}{c}{$0.96$}&\multicolumn{1}{l}{$\approx 0$}\\ \multicolumn{1}{c}{Image 3}&\multicolumn{1}{c}{$0.16$}&\multicolumn{1}{c}{$0.23$}&\multicolumn{1}{c}{$0.10$}&\multicolumn{1}{l}{$0.04$} &\multicolumn{1}{c}{$0.54$}&\multicolumn{1}{c}{$0.98$}&\multicolumn{1}{c}{$0.23$}&\multicolumn{1}{l}{$0.30$} &\multicolumn{1}{c}{$0.83$}&\multicolumn{1}{c}{$0.98$}&\multicolumn{1}{c}{$0.32$}&\multicolumn{1}{l}{$0.24$} &\multicolumn{1}{c}{$0.98$}&\multicolumn{1}{c}{$0.99$}&\multicolumn{1}{c}{$0.96$}&\multicolumn{1}{l}{$\approx0$}\\ \shline \end{tabular} \end{table*} \begin{figure*}[t] \centering \includegraphics[width=17.5cm]{images/fig9} \caption{Qualitative comparison results on CT images with the CVF model, the VCGeo model and the CombPaths model. In column 1, we illustrate the ground truth regions. The red lines in columns $2$ to $4$ denote the segmentation contours derived from each model} \label{fig_CT} \end{figure*} \begin{figure}[t] \centering \includegraphics[width=8cm]{images/boxplot_CT} \caption{Box plots of the average Jaccard scores of $20$ runs per image over a set of $86$ CT images. Note that each test image is artificially interrupted by \emph{additive Gaussian noises}} \label{fig_boxplot_CT} \end{figure} In Fig.~\ref{fig_examples_natural}, we demonstrate the qualitative results for the CVF model, the VCGeo model, the CombPaths model and the DualCut-Asy model on real images sampled from the Grabcut dataset~\cite{rother2004grabcut} and the Weizmann dataset~\cite{alpert2012image}. In this experiment, the segmentation contours of each evaluated model are denoted by red lines. The white lines in row $2$ represent the initial curves for CVF model. The blue (resp. yellow) dots in rows $2$ and $4$ (resp. row $3$) are the input points for the VCGeo model and the proposed DualCut-Asy model (resp. the CombPaths model), respectively. From Fig.~\ref{fig_examples_natural}, we can see that most of the segmentation contours derived from the CVF, VCGeo and CombPaths models suffer from the shortcut problems, as depicted in rows $1$ to $3$. In other words, most of these segmentation contours pass through the interior of the target regions. The DualCut-Asy model in conjunction with the implicit region-based homogeneity features is able to reduce the risk for the segmentation curves being trapped into unexpected local minima, as shown in row $4$. Note that for the proposed DualCut-Asy model, we exploit the piecewise constants-based homogeneity term to derive $\psi_\mathbf z$ for the test images in the first two rows and the Bhattacharyya coefficients for the images in rows $3$ to $5$. In Fig.~\ref{fig_examples_obstacle}, we demonstrate the advantages of using the performance of the proposed DualCut-Asy model on an image with complicated foreground, when exploiting scribbles as input. For this purpose, we first sample $20$ seed points from the interior of the ground truth region, as indicated by the cyan dots in Fig.~\ref{fig_examples_obstacle}a. From each seed point, we perform the front propagation associated to a potential with constant value $1$ inside the eroded ground truth region and $\infty$, otherwise. A farthest point is a point which has the highest distance value among all the boundary points of the eroded ground truth region. From this farthest point, one can track a shortest path linking to the corresponding seed. The scribbles of the second type are provided manually, as depicted by the white lines in Fig.~\ref{fig_examples_obstacle}c. With these setting, we perform $20$ runs for all the evaluated models such that each seed point is taken as the landmark point to set up the respective models. Note that in each test, we use the scribble of both types for the VCGeo model and the DualCut-Asy model. The statistics for the corresponding segmentation results are illustrated in Fig.~\ref{fig_examples_obstacle}c. From the box plots, we can see that the DualCut-Asy model achieves the best performance in the sense of Jaccard scores, due to the benefits from both of the region-based homogeneity enhancement and image gradients coherence property. Even through with the same scribbles during geodesic paths estimation, the segmentation results from the VCGeo model show lower accuracy than the proposed one. The segmentation results from the CombPaths model seem to be insensitive to the input. However, we still observe lower Jaccard scores comparing to the proposed DualCut-Asy model. The Jaccard scores for the CVF model illustrate that the segmentations from this model in most tests might be stuck in unexpected local minima. In this experiment, we use the Bhattacharyya coefficients for computing $\psi_\mathbf z$. The average computation time of the DualCut-Asy model is around $1$ second involving the computation of the velocity $\xi$, the construction of the metrics and the computation of geodesic distances, where the test image involves $480\times 640$ grid points. The curvature regularization may lead to smooth geodesic paths. This property is very effective in scenarios of segmenting images with strong noise levels. We show the comparison results on three images interrupted by different noises, as depicted in Fig.~\ref{fig_NoisedImages}. Moreover, in Table~\ref{table_ResultNoise}, we illustrate the statistics of the Jaccard scores with respect to different image segmentation approaches over $20$ runs per image, using a set of sampled points distributed inside the regions of interest. In this experiment, the piecewise constants-based homogeneity term is used for building $\psi_\mathbf z$. The results illustrated in this table indeed show that the proposed DualCut-RSF model are able to capture favorable segmentations in the presence of strong noises. For the images in the rows $2$ and $3$, the computation time of the proposed DualCut-RSF model is around $8$ seconds where the resolution of the grid $\mathbb M_h$ is $450\times 600\times 60$. In Fig.~\ref{fig_CT}, we perform the qualitative comparison on three CT images, for which the image gradients coherence property is satisfied along most parts of the objective boundaries. In this experiment, one can observe that the CVF model fails to segment the whole object regions. Moreover, the CombPaths model is capable of roughly capturing the boundaries of interest as depicted in rows $1$ to $3$. In rows $2$ and $3$, we observe leakage problems for the VCGeo model, where a portion of these segmentation contour pass through the background region. In contrast, the proposed DualCut-Asy model is able to find favorable segmentations in all CT images, due to the benefits from the regional homogeneity features derived using piecewise constants-based term in this experiment, and from the use of the image gradients coherence prior. Finally, we present the quantitative comparison results over $86$ CT images~\cite{spencer2019parameter} in terms of Jaccard scores. Each test CT image is artificially interrupted by Gaussian white noise with mean $0$ and normalized variance $0.05$. We sample $20$ points for each image from the corresponding eroded ground truth region. Each sampled point is taken as the landmark point $\mathbf z$ to initialize the evaluated models. The box plots of the mean Jaccard scores over $20$ runs are illustrated in Fig.~\ref{fig_boxplot_CT}. In each test, two and four points lying at the ground truth boundary are exploit to set up the VCGeo model and the CombPaths model. One can see that the proposed DualCut-Asy model indeed outperforms the compared models, even through the VCGeo model and the CombPaths model make use of more reliable user intervention. \noindent \emph{Discussion on future work}. In summary, the proposed geodesic paths-based model requires a point $\mathbf z$ to set up the initialization. In this work, we assume that the point $\mathbf z$ is provided by user, yielding an efficient and accurate interactive segmentation algorithm. In the future, the research work can be devoted to the integration with learning-based approaches. A possible way is to exploit the saliency objection detection models~\cite{han2018advanced,zhang2019synthesizing,wei2012geodesic,wei2020f3net} to predict the position of $\mathbf z$ and also to take the saliency maps as auxiliary image features. In addition, we plan to take into account the shape priors of convexity and star-convexity for the computation of geodesic paths. \section{Conclusion} \label{sec_Conclusion} In this paper, an efficient geodesic paths-based model is introduced for interactive image segmentation under the Eikonal PDE framework. We show the possibility of implicitly incorporating a great variety of region-based homogeneity information into the construction of local geodesic metrics. The implicit representation of the region-based features is carried out by a scalar-valued function, which is used the weight for a Finsler geodesic metric. As a consequence, either the image gradients coherence prior or the curvature regularization can be taken into account for tracking geodesic paths. In addition, we also introduce a new dual-cut geodesic computation scheme for image segmentation using a landmark point inside the target region. Both of the qualitative and quantitive comparison results prove the advantages of the proposed model in interactive image segmentation. \section*{Acknowledgment} The authors thank all the anonymous reviewers for their invaluable suggestions to improve this manuscript. This work is in part supported by the National Natural Science Foundation of China (No. 61902224), the Shandong Provincial Natural Science Foundation (No. ZR2020LZL001), and the French government under management of Agence Nationale de la Recherche as part of the ``Investissements d'avenir'' program, reference ANR-19-P3IA-0001 (PRAIRIE 3IA Institute). This research is also partially supported by the Distinguished Taishan Scholars in Climbing Plan (No. tspd20181211) and Young Taishan Scholars (Nos. tsqn201909137, tsqn201909140).
{'timestamp': '2021-05-07T02:20:20', 'yymm': '2008', 'arxiv_id': '2008.06909', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06909'}
arxiv
\section{Introduction} A robot is a programmable machine capable of executing complex tasks automatically. Traditionally, robots are designed to perform mechanical actions with no regard to how they look. With the evolution of the robotic industry, as well as the higher psychological requirement of human beings, more and more robots are designed and conducted to appear and behave like human beings \cite{paper.1}. Such similarity can be for functional purposes, for example, interacting with human instruments and facilities, or for other experimental purposes \cite{paper.2,paper.3}. In general, these humanoid robots are endowed with similar body structures of human beings, i.e., a head, a torso, two arms, and two legs \cite{paper.4}. Some of them also have their head parts designed to replicate emotional expressions of the human face, such as eye-blinking and lip-sipping \cite{paper.5}. An automatic perception for facial expressions of humanoid robots proposed by Zhang $et \ al.$ demonstrated the potential in developing personalized robots with social intelligence \cite{paper.6}. Trovato $et \ al.$ created a facial expression generator applied to a KOBIAN-R robot to establish an adaptive system based on human communication and facial anatomy \cite{paper.7}. Such a system is effective for the implementation of complex interactions between humans and robots. For a XIN-REN robot, a facial expression learning method based on energy conservation principle proposed by Ren $et \ al.$ successfully ensured smoother trajectories for multi-frame imitation of humanoid robots \cite{paper.8}. In addition to the head, the arms are also crucial and indispensable for a humanoid robot. Recently, various novel humanoid robots equipped with arms have been studied and further applied in home service, personal entertainment, inspection, health care, manufacturing, and so on \cite{article.2,article.3,article.4,article.5}. The dual arms of humanoid robots can not only conduct tasks \cite{article.6}, but also convey emotions with body language \cite{article.7, article.8}. To perform daily tasks with dual-arms of humanoid robots, the motion planning problem should be considered. Aly $et \ al.$ proposed a system to generate the dynamic characteristics of gestures and postures of the NAO robot during nonverbal communications \cite{paper.9,paper.10}. Tondu $et \ al.$ designed an anthropomorphic robot arm and its ancillary motion control method \cite{paper.11}. One of the basic problems of dual-arm motion planning is the inverse kinematic problem \cite{article.9}, i.e., given the trajectories of end-effector, computing joint variables at each time instant \cite{book.8}. Most dual arms of humanoid robots have more than three degrees of freedom (termed as DOF). This redundancy improves the flexibility of dual arms when the humanoid robots implement end-effector tasks \cite{article.11}. However, the redundant DOF also inevitably increases the difficulties of computation \cite{article.12}. The traditional redundancy resolution method is pseudo-inverse method \cite{article.13}. Wang $et \ al.$ proposed a closed-loop method for solving the inverse kinematics in Ref. \cite{article.14}, which was based on pseudo-inverse method, to control the dual arms on a mobile platform. In addition, the inverse of matrices has to be considered when utilizing the pseudo-inverse method to solving inverse kinematics, which can be challenging \cite{article.15}. Quadratic programming (termed as QP) methods are preferred recently, and a QP-based task priority framework is proposed in Ref. \cite{article.16} to resolve the kinematic redundancy problem. Inspired by the aforementioned optimization method, a QP-based online generation scheme for generating expected gestures of dual arms is proposed by Zhang $et \ al.$ \cite{article.1}, and a gesture-determined-dynamic function (termed as GDDF) is designed and introduced to the kinematics of humanoid robots. This GDDF scheme can not only handle the redundancy resolution problem within the joint limits, but also dynamically adjust gestures to the desired position. Different from the exiting pseudo-inverse method \cite{article.17,article.18,article.19} or very few QP-based methods focusing on single arm \cite{article.20,article.21,article.22}, together with the numerical QP solver, the GDDF scheme can generate dual-arm behaviors for humanoid robots \cite{article.23,article.24,article.26,article.28} in 3-D space online. However, there is still a deficiency in the GDDF scheme. On the basis of a series of experiments, we find that at some parameter groups during execution, the joint might slightly exceed its limit. That is to say, if the parameter is falsely selected, dead-lock of robot arms or even damages could occur, which is perilous for the practical applications. To remedy this disadvantage, a modified GDDF method named MGDDF is proposed in this paper. With consideration of three kinds of margins (i.e., MGDDF-1, MGDDF-2 and MGDDF-3, which will be carefully discussed in the following sections) are introduced to the MGDDF method to constrain the movement of the joints. The remainder of this paper is listed as follows. The overviews of related works are presented in Section II. Section III gives the preliminary and problem formulation of dual arms. The traditional GDDF method and the proposed MGDDF method are discussed in Section IV. Simulations and experiments are made in Section V to verify the effectiveness of the proposed method. Section VI offers a concluding remarks. The main contributions of this paper can be summarized as follows: \begin{itemize} \item With consideration of three margins, a modified scheme named MGDDF is proposed for solving kinematic problems of dual arms of humanoid robot. \item The gesture of dual arms can be smoothly achieved by using MGDDF method, and the joints would not exceed their limits during the whole execution of tasks. \end{itemize} \section{Related Works} The motion planning of humanoid robots have been studied for a few decades. Gouda $et \ al.$ proposed a whole-body motion planning approach of NAO robot using onboard sensing and achieved reliable motion sequences when operating in complex environment \cite{related.1}. A path planning method which computes dynamics and collision avoidance for full-body gestures of humanoid robots was proposed by Kagami $et \ al.$ \cite{related.2}. This method contains a filtering function that constrains the zero moment point of each trajectory to obtain statically stabilization for the entire body. Without lost of generality, Dalibard $et \ al.$ presented a collision-free method for whole-body working control of humanoid robots \cite{related.3}. In Ref. \cite{related.4}, Ohashi $et \ al.$ introduced a linear inverted pendulum mode and designed a collision avoidance method for a robot with an upper body to discriminate the start/stop of force of robot arms. On the basis of Lyapunov stability theory, an adaptive control method was proposed by Liu $et \ al.$ to satisfy the coordination of dual arms of humanoid robots \cite{related.5}. Simulation results prove that when applying this method, the internal force of the arms can be held and the position errors are arbitrarily small. As for the motion optimization, Ayusawa $et \ al.$ proposed a novel re-targeting method with geometric parameter identification, motion planning and inverse kinematics to handle control problems of humanoid robots \cite{related.6}. A practical experiment performed on HRP-4 robot further verified the excellent performance of this method. In Ref. \cite{related.7}, an optimization-based approach was proposed by Schulman $et \ al.$ to find collision-free trajectories of a 18 degrees-of-freedom robot with dual arms. Hong $et \ al.$ who focused on real-time pattern generation utilized the linear pendulum model to solve the walking control problem of MAHRU-R robot with feed-forward and feed-back controller \cite{related.8}. The desired task hierarchy which is based on quadratic programming was solve by Liu $et \ al.$ to reduce the risk of instability when humanoid robots conducting operations \cite{related.9}. According to HRP-2 robot, a novel plan for foot placements was proposed by Kanoun $et \ al.$ to formulate the deformation problem as the inverse kinematic problem and to further be described as a locomotion phase of the desired tasks. \cite{related.10}. For the posture control problem, Choi $et \ al.$ proposed a kinematic resolution method based on the center of mass Jacobian with embedded motion of humanoid robots \cite{related.11}. A motion planning using swept volume approximation was researched by Perrin $et \ al.$ to achieve the 3-D obstacle avoidance \cite{related.12}. In the field of gesture generation, Yanik $et \ al.$ proposed a gesture recognition scheme for path shaping of simulated robot \cite{new.0}. They first extracted gesture data from sequential skeletal depth and then clustered them by a growing neural gas algorithm. Cheng $et \ al.$ presented a hand-gesture-recognition method which can track gestures of a dance robot in real-time \cite{new.1}. The hand gestures were recorded as signals detected by a 3-axis sensor and represented as discrete cosine transform coefficients. Furthermore, a artificial communicator for gesture recognition, proposed by Zhang $et \ al.$, was utilized for human-robot cooperative assembly \cite{new.2}. In Ref. \cite{new.3}, the tracking control of manipulators was solved by nonlinear observers which provided joint coordinate rates. Arteaga $et \ al.$ utilized this method by associating Euler-Lagrange equations to describe gesture motions and achieved high control accuracy. \section{Preliminary and Problem Formulation}\label{sec.model} The forward kinematics of dual arms of humanoid robots can be described as \begin{equation} \textit{\textbf{p}}_L=\Im_L(\mathbf{\theta}_L), \ \textit{\textbf{p}}_R=\Im_R(\mathbf{\theta}_R)\label{equ.timeinv} \end{equation} where $\textit{\textbf{p}}_L$ and $\textit{\textbf{p}}_R$ denote the position vectors of the end effector. $\theta_L$ and $\theta_R$ stand for the vectors of left and right joints. $\Im_L(\cdot)$ and $\Im_R(\cdot)$ are continuous nonlinear functions. These two equations can be obtained when the manipulator is given. For redundant manipulator, the inverse kinematic problem is basic and the motion states of each joint should be solved according to the trajectories of the end effector. Inspired by previous work in Ref. \cite{article.1}, an online optimization algorithm to solve the redundancy problem is presented. The following equations at velocity level are obtained \begin{eqnarray} \frac{\dot{\theta}_L^\text{T}\textit{\textbf{A}}\dot{\theta}_L}{2}+\frac{\dot{\theta}_R^\text{T}\textit{\textbf{B}}\dot{\theta}_R}{2} +\textit{\textbf{c}}_L^\text{T}\theta_L+\textit{\textbf{c}}_R^\text{T}\theta_R\label{eq4}\\ \textit{\textbf{J}}_L(\theta_L)\dot{\theta}_L=\dot{\textit{\textbf{p}}}_L+\wp_L\big(\textit{\textbf{p}}_L-\Im_L(\theta_L)\big)\label{eq5}\\ \textit{\textbf{J}}_R(\theta_R)\dot{\theta}_R=\dot{\textit{\textbf{p}}}_R+\wp_R\big(\textit{\textbf{p}}_R-\Im_R(\theta_R)\big)\label{eq6}\\ \theta_L^-\leqslant\theta_L\leqslant\theta_L^+\label{eq7}\\ \theta_R^-\leqslant\theta_R\leqslant\theta_R^+\label{eq8}\\ \dot{\theta}_L^-\leqslant\dot{\theta}_L\leqslant\dot{\theta}_L^+\label{eq9}\\ \dot{\theta}_R^-\leqslant\dot{\theta}_R\leqslant\dot{\theta}_R^+\label{eq10} \end{eqnarray} where superscript $^\text{T}$ denotes the transpose of a vector or a matrix. $\dot{\theta}_{L}$ and $\dot{\theta}_{R}\in \mathbb{R}^n$ denote joint-velocity vectors of left and right arms. $\textit{\textbf{A}}\in \mathbb{R}^{n\times n}$ and $\textit{\textbf{B}}\in \mathbb{R}^{n\times n}$ are coefficient matrices of quadratic terms. $\textit{\textbf{c}}_L$ and $\textit{\textbf{c}}_R$ are coefficient vectors related to linear terms. $\textit{\textbf{J}}_L(\cdot)$ and $\textit{\textbf{J}}_R(\cdot)\in \mathbb{R}^{n\times m}$ are the Jacobian matrices of the left and right arms, respectively. $\dot{\textit{\textbf{p}}}_{L}$ and $\dot{\textit{\textbf{p}}}_{R}\in \mathbb{R}^n$ denote velocity vectors of the end effector. The position-error feedbacks $\wp_L\big(\textit{\textbf{p}}_L-\Im_L(\theta_L)\big)$ and $\wp_R\big(\textit{\textbf{p}}_R-\Im_R(\theta_R)\big)$ are considered with non-negative parameters $\wp_L$ and $\wp_R$. The series of inequalities (\ref{eq7})-(\ref{eq10}) are the constraints of joints and joint-velocities. $\theta_L^\pm$ and $\theta_R^\pm$ denote physical joint limits, while $\dot{\theta}_L^\pm$ and $\dot{\theta}_R^\pm$ denote joint-velocity limits, respectively. The aforementioned dual formulas (\ref{eq5})-(\ref{eq10}) can be combined as matrix forms to offer a much more clear expression, i.e., $\bullet$ position-error feedback equalities (\ref{eq5})-(\ref{eq6}) are combined as \begin{equation} \begin{bmatrix} \textit{\textbf{J}}_\text{L} &\textbf{\text{0}}_{m\times n}\\ \textbf{\text{0}}_{m\times n} &\textit{\textbf{J}}_\text{R} \end{bmatrix} \cdot \begin{bmatrix} \dot{\theta}_L\\ \dot{\theta}_R \end{bmatrix} = \begin{bmatrix} \dot{\textit{\textbf{p}}}_L\\ \dot{\textit{\textbf{p}}}_R \end{bmatrix} + \begin{bmatrix} \wp_L\big(\textit{\textbf{p}}_L-\Im_L(\theta_L)\big)\\ \wp_R\big(\textit{\textbf{p}}_R-\Im_R(\theta_R)\big) \end{bmatrix}; \label{eqn.c1} \end{equation} $\bullet$ joint limit inequalities (\ref{eq7})-(\ref{eq8}) are combined as \begin{eqnarray} \begin{bmatrix} \theta_L^-\\ \theta_R^- \end{bmatrix} \leqslant \begin{bmatrix} \theta_L\\ \theta_R \end{bmatrix} \leqslant \begin{bmatrix} \theta_L^+\\ \theta_R^+ \end{bmatrix} \in \mathbb{R}^{2n}; \label{eqn.c2} \end{eqnarray} $\bullet$ joint-velocity limit inequalities (\ref{eq9})-(\ref{eq10}) are combined as \begin{eqnarray} \begin{bmatrix} \dot{\theta}_L^-\\ \dot{\theta}_R^- \end{bmatrix} \leqslant \begin{bmatrix} \dot{\theta}_L\\ \dot{\theta}_R \end{bmatrix} \leqslant \begin{bmatrix} \dot{\theta}_L^+\\ \dot{\theta}_R^+ \end{bmatrix} \in \mathbb{R}^{2n}. \label{eqn.c3} \end{eqnarray} With the consideration of objective function (\ref{eq4}) and modified constrains (\ref{eqn.c1})-(\ref{eqn.c3}), the following standard QP can be formulated as follows \begin{eqnarray} \text{min.} \ ~ \frac{\dot{\Theta}^\text{T}\textit{\textbf{M}}\dot{\Theta}}{2}+\textit{\textbf{c}}^\text{T}\Theta\label{eq14}~~~~~~~~~~~~~~~~~~ \\ \text{s. t.} \ ~ \textit{\textbf{J}}(\Theta)\dot{\Theta}=\dot{\Upsilon}+\wp(\Upsilon-\Im(\Theta))\\ \Theta^-\leqslant\Theta\leqslant\Theta^+\label{eq16}\\ \dot{\Theta}^-\leqslant\dot{\Theta}\leqslant\dot{\Theta}^+\label{eq17} \end{eqnarray} where $\Theta=[\theta_L^\text{T}, \theta_R^\text{T}]$, $\textit{\textbf{c}}=[\textit{\textbf{c}}_L^\text{T}, \textit{\textbf{c}}_R^\text{T}]$, $\Theta^-=[\theta_L^{-\text{T}}, \theta_R^{-\text{T}}]^\text{T}$, $\Theta^+=[\theta_L^{+\text{T}}, \theta_R^{+\text{T}}]^\text{T}$, $\dot{\Theta}=\text{d}\Theta/\text{d}t=[\dot{\theta}_L^\text{T}, \dot{\theta}_R^\text{T}]$, $\dot{\Theta}^-=[\dot{\theta}_L^{-\text{T}}, \dot{\theta}_R^{-\text{T}}]^\text{T}$, $\dot{\Theta}^+=[\dot{\theta}_L^{+\text{T}}, \dot{\theta}_R^{+\text{T}}]^\text{T}$, $\dot{\Upsilon}=[\dot{\textit{\textbf{p}}}_L^\text{T}, \dot{\textit{\textbf{p}}}_R^\text{T}]^\text{T}$, \begin{equation} \textit{\textbf{M}}= \begin{bmatrix} \textit{\textbf{A}} &\textbf{\text{0}}_{n\times n}\\ \textbf{\text{0}}_{n\times n} &\textit{\textbf{B}} \end{bmatrix} \in \mathbb{R}^{2n\times 2n}, \end{equation} \begin{equation} \textit{\textbf{J}}= \begin{bmatrix} \textit{\textbf{J}}_L &\textbf{\text{0}}_{n\times n}\\ \textbf{\text{0}}_{n\times n} &\textit{\textbf{J}}_R \end{bmatrix} \in \mathbb{R}^{2m\times 2n}, \end{equation} \begin{equation} \wp= \begin{bmatrix} \wp_L &\textbf{\text{0}}_{m\times m}\\ \textbf{\text{0}}_{m\times m} &\wp_R \end{bmatrix} \in \mathbb{R}^{2m\times 2m}. \end{equation} It is worth pointing out that vector $\textit{\textbf{c}}$ and matrix $\textit{\textbf{M}}$ are determined by a definite redundancy-resolution scheme. Matrix $\wp$ stands for the feedback gain and is determined by practical effect. Different goals can be obtained by choosing different criteria of vector $\textit{\textbf{c}}$ and matrix $\textit{\textbf{M}}$. The following three schemes are introduced, i.e., $\bullet$ MKE scheme: If vector $\textit{\textbf{c}}=[\textbf{\text{0}}; \textbf{\text{0}}]$, and matrix $\textit{\textbf{M}}=[\mathcal{I}_L, 0; 0, \mathcal{I}_R]$ (where $\mathcal{I}$ denotes inertia matrix), then the QP problem (\ref{eq14})-(\ref{eq17}) forms a minimum-kinetic-energy (MKE) scheme. $\bullet$ RMP scheme: If vector $\textit{\textbf{c}}=[\lambda(\theta_L-\theta_L(0)); \lambda(\theta_R-\theta_R(0))]$ (where $\lambda$ is a non-negative parameter), and matrix $\textit{\textbf{M}}=\textit{\textbf{I}}$ is an identity matrix, then the QP problem (\ref{eq14})-(\ref{eq17}) forms a repetitive motion planning (RMP) scheme. $\bullet$ MVN scheme: If vector $\textit{\textbf{c}}=[\textbf{\text{0}}$, and matrix $\textit{\textbf{M}}=\textit{\textbf{I}}$ is an identity matrix, then the QP problem (\ref{eq14})-(\ref{eq17}) forms a minimum-velocity-norm (MVN) scheme. \section{Proposed Methods} Humanoid robots are not only asked to finish the end-effector tasks, but also are demanded to ``behave'' naturally as a human \cite{paper.8,article.23,article.24}. Being the most straight way of expressing feelings and emotions, gestures of humanoid robots have been widely designed and exerted to accomplish natural human-robot interactions \cite{article.26,article.23,article.28}. A gesture-determined-dynamic function (GDDF) is presented in Ref. \cite{article.1}. Associating with a QP framework (\ref{eq14})-(\ref{eq17}) and the GDDF method, the researchers expect to cause expected gestures of humanoid robots. \subsection{GDDF Scheme} To generate the expected movement and to execute the end-effector tasks, some joints of the dual arms should be dynamically adjustable \cite{article.1,article.8,article.9,myarticle.11,myarticle.21,myarticle.31,myarticle.41}. The joint limits and joint-velocity limits have already been formulated into QP problem (\ref{eq14})-(\ref{eq17}). A dynamic function which can change the upper and the lower bounds of the limits should be found, and the bounds should be related to the expectation values. Besides, the generated curves should be smooth during the executing process. The following function is then designed to satisfy the demand and the joints can adjust to the expected gesture, i.e., \begin{equation} \tilde{\Theta}^\pm(t)=\Theta^\pm+\frac{\Delta\Theta^\pm}{1+e^{-(t-\tau)/\varrho}}\label{fun18} \end{equation} where $\Delta\Theta^\pm=\Theta_{g}^\pm-\Theta^\pm$, and $\Theta_{g}=[\Theta_{gL}^\text{T}; \Theta_{gR}^\text{T}]$ sets the goal configuration of joint. $\varrho$ is a parameter affecting the variation trend. Parameter $\tau=T_d/N$, with $T_d$ denoting the task execution time and $N\geqslant 1$ denoting the parameter affecting the proximity between the adjusted value and the actual value (set point). $\Delta\Theta$ determines whether $\tilde{\Theta}$ increases or decreases. Normally speaking $\tilde{\Theta}^+$ decreases while $\tilde{\Theta}^-$ increases. Fraction $1/[1+e^{-(t-\tau)/\varrho}]$ is a gradual and smooth function and it influences the curve shape of the joint limit. When time $t$ approaches infinite, $e^{-(t-\tau)/\varrho}$ will approach $0$, thus the fraction will approach $1$, and $\tilde{\Theta}^\pm$ will approach $\Theta^\pm+\Delta\Theta^\pm=\Theta_{g}^\pm$. Function (\ref{fun18}) can lead to the expected movement smoothly and slowly. On the basis of smooth function (\ref{fun18}) and QP-based framework (\ref{eq14})-(\ref{eq17}), the GDDF scheme can be successfully established. The upper and lower bounds of the inequalities will constrain the movement of the joints, and make the joints move just as expected. For dual arms of humanoid robots, all the joints can be adjusted to the tasks at the same time. As for each \emph{i}-th joint, we can set $\Theta_{g\emph{i}}^+=\Theta^+$ and $\Theta_{g\emph{i}}^-=\Theta^-$, and the corresponding joints would reach the target values equally. To achieve the joints' expected gestures, a series of values of parameters $\varrho$, $\tau$ and $N$ which influence the proximity between the adjusted value and the actual value can be easily set. \subsection{MGDDF Scheme with Consideration of Margins} The gestures can be smoothly achieved by using GDDF method. However, there is still a deficiency in this scheme. Through the experiment we find that the joint might exceed its limit slightly at some parameter groups. To remedy this problem, three kinds of margins are introduced to constrain the movement of the joints. This modified GDDF method is termed as MGDDF method. $\bullet$ MGDDF-1: \begin{figure*} \centering \includegraphics[width=.99\textwidth]{FIG-1.eps}\\ \caption{Graphical representation of the margins of MGDDF-1. Both upper bound and lower bound of joint limits are greater than zero.}\label{fig.MGDDF-1} \end{figure*} Firstly, joint limit (\ref{eq16}) is rewritten as \begin{equation} \tilde{\Theta}^-\leqslant\Theta\leqslant\tilde{\Theta}^+ \label{eqn.MGDDF-1} \end{equation} Secondly, a margin set at velocity level is considered, and the joint limit constraint (\ref{eqn.MGDDF-1}) is modified as follows \begin{equation} \nu\big((2-\kappa)\tilde{\Theta}^-(t)-\Theta\big)\leqslant\dot{\Theta}\leqslant\nu\big(\kappa\tilde{\Theta}^+(t)-\Theta\big) \label{eqn.cons} \end{equation} where $\dot{\Theta}$ denote the joint velocity and $\nu>0$ is a parameter which is applied to scale the feasible region of $\dot{\Theta}$. For simplicity, $\nu$ is set as $\nu=2$ in the following experiments. The critical coefficient $\kappa\in(0,1)$ is selected to define a critical region $(\Theta_i^-, (2-\kappa)\Theta_i^-]$ and $[\kappa\Theta_i^+, \Theta_i^+)$, which is shown in Fig. \ref{fig.MGDDF-1}. It is worth noting that, MGDDF-1 is suitable for the case that the upper bound and lower bound of joint limits are greater than zero. Moreover, for the \emph{i}-th joint, the joint-velocity constraint of MGDDF-1 are be formulated as follows \begin{eqnarray} \begin{split} \text{max}\big\{\dot{\Theta}^-,\nu\big((2-\kappa)\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}&\leq\dot{\Theta}_{\emph{i}}\\ \text{min}\big\{\dot{\Theta}^+,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}&\geq\dot{\Theta}_{\emph{i}}. \end{split} \label{eqn.v-MGDDF-1} \end{eqnarray} To simplify the expression of joint-velocity constraint (\ref{eqn.v-MGDDF-1}), the following equations are introduced, i.e., \begin{eqnarray} \tilde{\zeta}_{\emph{i}}^-(t)=\text{max}\big\{\dot{\Theta}^-,\nu\big((2-\kappa)\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}\\ \tilde{\zeta}_{\emph{i}}^+(t)=\text{min}\big\{\dot{\Theta}^+,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}. \end{eqnarray} $\bullet$ MGDDF-2: \begin{figure*} \centering \includegraphics[width=.99\textwidth]{FIG-2.eps}\\ \caption{Graphical representation of the margins of MGDDF-2. The upper bound of joint limits is greater than zero, while the lower bound of joint limits is less than zero.}\label{fig.MGDDF-2} \end{figure*} Considering the case that upper limit $>0$ and lower limit $<0$. On the basis of constraint (\ref{eqn.cons}), the critical region of MGDDF-2 is $(\Theta_i^-, \kappa\Theta_i^-]$ and $[\kappa\Theta_i^+, \Theta_i^+)$. The graphical representation of the margins of MGDDF-2 is depicted in Fig. \ref{fig.MGDDF-1}. Similar to MGDDF-1, the joint-velocity constraint of MGDDF-2 is simplified as the following relationships, i.e., \begin{eqnarray} \tilde{\zeta}_{\emph{i}}^-(t)=\text{max}\big\{\dot{\Theta}^-,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}\\ \tilde{\zeta}_{\emph{i}}^+(t)=\text{min}\big\{\dot{\Theta}^+,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}. \end{eqnarray} $\bullet$ MGDDF-3: When both the upper bound and lower bound of limits are less than zero, the critical region of MGDDF-3 are $(\Theta_i^-, \kappa\Theta_i^-]$ and $[(2-\kappa)\Theta_i^+, \Theta_i^+)$. Sharing the same process, the following result is obtained, i.e., \begin{eqnarray} \tilde{\zeta}_{\emph{i}}^-(t)=\text{max}\big\{\dot{\Theta}^-,\nu\big(\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}\\ \tilde{\zeta}_{\emph{i}}^+(t)=\text{min}\big\{\dot{\Theta}^+,\nu\big((2-\kappa)\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}. \end{eqnarray} Combining the aforementioned MGDDF-1, MGDDF-2 and MGDDF-3, the MGDDF scheme with consideration of margins is obtained, i.e., \begin{eqnarray} \text{min.} \ ~ \frac{\dot{\Theta}^\text{T}\textit{\textbf{M}}\dot{\Theta}}{2}+\textit{\textbf{c}}^\text{T}\Theta\label{eq32}~~~~~~~~~~~~~~~~~~ \\ \text{s. t.} \ ~ \textit{\textbf{J}}(\Theta)\dot{\Theta}=\dot{\Upsilon}+\wp(\Upsilon-\Im(\Theta))\label{eq33}\\ \tilde{\zeta}_{\emph{i}}^-(t)\leqslant\dot{\Theta}\leqslant\tilde{\zeta}_{\emph{i}}^+(t)\label{eq34} \end{eqnarray} \begin{figure*} \centering \includegraphics[width=.99\textwidth]{FIG-3.eps}\\ \caption{Graphical representation of the margins of MGDDF-3. Both upper bound and lower bound of joint limits are less than zero.}\label{fig.MGDDF-3} \end{figure*} In summary, the kinematic task of the dual arms of the humanoid robot can be successfully finished by using the proposed MGDDF scheme (\ref{eq32})-(\ref{eq34}). The end-effector velocities $\dot{\textit{\textbf{p}}}_L$ and $\dot{\textit{\textbf{p}}}_R$ are integrated into equation (\ref{eq33}). The key function (\ref{fun18}) determines the upper and lower bounds of inequality (\ref{eq34}). It is worth mentioning that the proposed MGDDF scheme can be solved by a discrete QP solver, which will be discussed in the following sub-section. \subsection{MGDDF Solvers} According to Refs. \cite{article.12, article.15}, a linear-variational-inequality (LVI) is introduced to solve MGDDF scheme (\ref{eq32})-(\ref{eq34}). Equivalently, a linear projection equation is led to replace these equations, i.e., \begin{equation} \Phi_{\Omega}\big(\textit{\textbf{d}}-(\Gamma \textit{\textbf{d}}+\textit{\textbf{q}})\big)-\textit{\textbf{d}}=0 \end{equation} where $\Phi_{\Omega}(\cdot)$ ($\mathbb{R}^{2n+2m}\rightarrow\Omega$) is a projection operator with set $\Omega=\{\textit{\textbf{d}} ~|~\textit{\textbf{d}}^-\leqslant\textit{\textbf{d}}\leqslant\textit{\textbf{d}}^+\}\subset \mathbb{R}^{2n+2m}$. $\textit{\textbf{d}}=[\Theta; \iota]$, $\textit{\textbf{d}}^+=[\tilde{\zeta}^+(t); \omega \textit{\textbf{l}}_{\iota}]\in \mathbb{R}^{2n+2m}$, $\textit{\textbf{d}}^-=[\tilde{\zeta}^-(t); -\omega \textit{\textbf{l}}_{\iota}]\in \mathbb{R}^{2n+2m}$, $\Gamma=[\textit{\textbf{M}}, -\textit{\textbf{J}}^\text{T}(\Theta); \textit{\textbf{J}}(\Theta), \textbf{\text{0}}]\in \mathbb{R}^{(2n+2m)\times (2n+2m)}$, $\textit{\textbf{q}}=[\textbf{\text{0}}; -\dot{\Upsilon}]\in \mathbb{R}^{n+m}$, and $\textit{\textbf{l}}_{\iota}=[\textbf{1}, \cdots, \textbf{1}]^\text{T}$. Besides, $\textit{\textbf{d}}\in \mathbb{R}^m$ denotes the primal-dual decision vector, $\textit{\textbf{d}}^+\in \mathbb{R}^m$ and $\textit{\textbf{d}}^-\in \mathbb{R}^m$ are the upper and lower bounds, severally. $\omega$ is valued enormous ($\varpi:=10^{10}$) in the experiments. We define $\varepsilon(\textit{\textbf{d}}):= \textit{\textbf{d}}-\Phi_{\Omega}\big(\textit{\textbf{d}}-(\Gamma \textit{\textbf{d}}+\textit{\textbf{q}})\big)$, and the iterative algorithm causes $\varepsilon(\textit{\textbf{d}})\rightarrow 0$. $\textit{\textbf{d}}^0\in \mathbb{R}^{2n+2m}$ is the original primal-dual decision variable vector, $k=0,1,2,3,\cdots$, if $\textit{\textbf{d}}^k\notin \Omega^*$, then \begin{equation} \textit{\textbf{d}}^{k+1}=\textit{\textbf{d}}^k-\frac{||\varepsilon(\textit{\textbf{d}}^k)||_2^2\sigma(\textit{\textbf{d}}^k)} {||\sigma(\textit{\textbf{d}}^k)||_2^2}\label{eq36} \end{equation} where $\varepsilon(\textit{\textbf{d}}^k)=\textit{\textbf{d}}^k-\Phi_{\Omega}(\textit{\textbf{d}}^k-(\Gamma \textit{\textbf{d}}^k+\textit{\textbf{q}}))$ and $\sigma(\textit{\textbf{d}}^k)=(\Gamma+I)\varepsilon(\textit{\textbf{d}}^k)$. In numerical calculation, $\varepsilon(\textit{\textbf{d}}^k)=10^{-5}$. \begin{lemma} \cite{article.9} The sequence $\{\textit{\textbf{d}}^k\}, k=1, 2, \cdots$, which is generated by QP-solution (\ref{eq36}), satisfies \begin{equation} ||\textit{\textbf{d}}^{k+1}-\textit{\textbf{d}}^{\star}||_2^2\leqslant||\textit{\textbf{d}}^k-\textit{\textbf{d}}^{\star}||_2^2- \frac{||\varepsilon(\textit{\textbf{d}}^k)_2^4}{||\sigma(\textit{\textbf{d}}^k)||_2^2}. \end{equation} \end{lemma} This lemma is applied to all $\textit{\textbf{d}}^{\star}\in\Omega^{\star}$. The solution vector $\textit{\textbf{d}}^{\star}$ comes from $\{\textit{\textbf{d}}^k\}$, and its first $2n$ elements consist of the optimal solution to MGDDF (\ref{eq32})-(\ref{eq34}), $\Theta^{\star}\in \mathbb{R}^n$. Definitely, the first $n$ elements constitute the optimal solutions of the left-arm joints, while the second $n$ elements constitute right-arm joints' optimal solution. \begin{corollary} For any positive constant $\Xi>0$, error vector $\epsilon\in\mathbb{R}^n$ of a dynamic system $\dot{\epsilon}=-\Xi\epsilon$, starting from any initial state $\epsilon(0)$, converges to zero with exponential convergence speed, where $\dot{\epsilon}$ is the first-order derivative of $\epsilon$ with respect to time $t$. \end{corollary} \begin{corollary} For any positive constant $\Xi>0$ and disturbance $\Delta\Xi>-\Xi$, a dynamic system with disturbance parameter $\dot{\epsilon}=-(\Xi+\Delta\Xi)\epsilon$ is robust for the uncertain-parameter situation, where $\dot{\epsilon}$ is the first-order derivative of $\epsilon$ with respect to time $t$. \end{corollary} According to dual theory and Lagrange theory \cite{NN29,NN30}, the proposed MGDDF (\ref{eq32})-(\ref{eq34}) can also be solved by a neural network solver. To find a primal dual equilibrium vector $\mathcal{K}\in\mathbb{R}^{2m}$, MGDDF (\ref{eq32})-(\ref{eq34}) should be converted into the following linear variational inequalities, i.e., \begin{equation} \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix}\in\Omega :=\bigg\{ \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix} ~\bigg|~ \begin{bmatrix} \tilde{\zeta}_{\emph{i}}^-(t)\\ -z\textit{\textbf{l}}_{\mathcal{K}} \end{bmatrix} \leq \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix} \leq \begin{bmatrix} \tilde{\zeta}_{\emph{i}}^+(t)\\ +z\textit{\textbf{l}}_{\mathcal{K}} \end{bmatrix}\bigg\}\subset\mathbb{R}^{2n+2m} \end{equation} where $\textit{\textbf{l}}_{\mathcal{K}}=[\textbf{1}, \cdots, \textbf{1}]^\text{T}$ and $z$ is set to approximate $m$-dimensional $+\infty$. Such that \begin{equation} \bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix} \bigg)^{\text{T}} \bigg(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix} \bigg)\geq0, \forall \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}\in\Omega \end{equation} where $\mathcal{I}\in\mathbb{R}^{2n\times2n}$. According to Ref. \cite{myarticle.21}, the above relationship is equivalent to a piecewise-linear-equation system satisfy \begin{equation} \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg)- \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}=0 \label{equ.nn-1} \end{equation} where $\mathcal{P}_{\Omega}(\cdot):\mathbb{R}^{2n+2m}\rightarrow\Omega$ is the projection operator. With projective theory, system (\ref{equ.nn-1}) can be computed by the recurrent neural network below \begin{equation} \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} =\mathcal{H}\bigg(\mathcal{E}+ \begin{bmatrix} \mathcal{I} &\textit{\textbf{J}}\\ -\textit{\textbf{J}}^{\text{T}} &\textbf{0} \end{bmatrix}\bigg) \cdot \bigg\{ \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg)- \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix} \bigg\} \label{equ.nn-2} \end{equation} where $\mathcal{H}>0$ is designed to scale convergent rate and $\mathcal{E}\in\mathbb{R}^{(2n+2m)\times(2n+2m)}$ denotes identity matrix. \begin{theorem} State vector $[\dot{\Theta}, \mathcal{K}]^{\text{T}}$ of (\ref{equ.nn-2}), starting from any initial state, can globally convergent to an equilibrium point $[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}$, of which the first $2n$ elements constitute optimal solution $\dot{\Theta}^*$ to MGDDF (\ref{eq32})-(\ref{eq34}). Moreover, with constant $\mathcal{N}>0$ such that \begin{equation} \bigg\|~ \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg) ~\bigg\|_2^2 \geq \mathcal{N}~\bigg\|~\begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix}~ \bigg\|_2^2, \end{equation} the exponential stability for computing MGDDF (\ref{eq32})-(\ref{eq34}) can be guaranteed. \end{theorem} \begin{proof} Firstly, define the following Lyapunov function candidate, i.e., \begin{equation} \mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg)= \bigg\|~\begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} ~\bigg\|_2^2 \geq0. \end{equation} Secondly, the time derivative of $\mathcal{V}(\cdot)$ along (\ref{equ.nn-2}) is \begin{equation} \frac{\text{d}\mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg)}{\text{d}t} \end{equation} \begin{equation} = \mathcal{H} \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg)^{\text{T}} \bigg(\mathcal{E}+ \begin{bmatrix} \mathcal{I} &\textit{\textbf{J}}\\ -\textit{\textbf{J}}^{\text{T}} &\textbf{0} \end{bmatrix}\bigg) \times \bigg\{ \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg)- \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix} \bigg\} \end{equation} \begin{equation} \leq-\mathcal{H}\bigg\|~ \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix} - \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg) ~\bigg\|^2_2 - \mathcal{H}\bigg\|~ \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg) ~\bigg\|_2^2 \leq0. \end{equation} On the basis of Lyapunov theory, with positive-defined $\mathcal{V}$ and negative-dfined $\dot{\mathcal{V}}$, state vector $[\dot{\Theta}, \mathcal{K}]^{\text{T}}$ of (\ref{equ.nn-2}) is stable and converges to equilibrium point $[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}$ globally, in view that $\dot{\mathcal{V}}=0$ when $[\dot{\Theta}, \mathcal{K}]^{\text{T}}=[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}=0$. It follows that the first $2n$ elements of $[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}$ constitute the optimal solution to MGDDF (\ref{eq32})-(\ref{eq34}). Also note that \begin{equation} \frac{\text{d}\mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg)}{\text{d}t} \leq - \mathcal{H} \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg)^{\text{T}} \bigg( \mathcal{N}\mathcal{E}+ \begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \bigg)\cdot \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg) \leq-\mathcal{S}\mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg) \end{equation} where convergence rate $\mathcal{S}=\mathcal{N}\mathcal{H}>0$. Therefore, with $\forall t\geq t_0$, we have $\mathcal{V}([\dot{\Theta}, \mathcal{K}]^{\text{T}})=O(e^{-\mathcal{S}(t-t_0)})$ such that \begin{equation} \bigg\|~ \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} ~\bigg\|_2^2 = O(e^{-\mathcal{S}(t-t_0)/2}). \label{eqn.nn-3} \end{equation} In reference to (\ref{eqn.nn-3}), we can draw the conclusion that the exponential computation speed of MGDDF (\ref{eq32})-(\ref{eq34}) can be achieved. The proof is thus completed. \end{proof} \section{Simulations and Experiments} \begin{figure*} \centering \includegraphics[width=.75\textwidth]{FIG-4.eps}\\ \caption{The skeleton structure of dual arms of the humanoid robot used in simulations.}\label{fig.structure} \end{figure*} In this section, the practicability of the proposed MGDDF scheme is verified by simulative experiments. The comparison between MGDDF and the traditional GDDF scheme is also provided. Specifically, the experiments are based on the dual arms of a humanoid robot, which contain 14 DOF (7 of each arm), and the skeleton structure is shown in Fig. \ref{fig.structure}. The execution task lasts for $18s$. In addition, the upper and lower bounds of the joint limit $6$, $7$, $13$ and $14$ are set as the same value, respectively. \subsection{Adjustments of the GDDF Scheme} Set the parameters of the QP problem (\ref{eq32})-(\ref{eq34}) as follows: $N=1$, $\varrho=2$, $\kappa=0.85$, $\Theta_{gL}^-=[0, -54\pi/180,$ $-10.5\pi/180, 0, -131\pi/180, \pi/3, 55\pi/180]^\text{T}$ (rad), $\Theta_{gL}^+=[9\pi/180, 18\pi/180, 22.5\pi/180, \pi/2, 0, \pi/3,$ $55\pi/180]^\text{T}$ (rad), $\Theta_{gR}^-=[-9\pi/180, -18\pi/180, -22.5\pi$ $/180, \pi/2, -131\pi/180, \pi/3, -25\pi/36]^\text{T}$ (rad), and $\Theta_{gR}^+=$ $[0, 54\pi/180,$ $10.5\pi/180, \pi, 0, \pi/3, -25\pi/36]^\text{T}$ (rad). At first, to show the adjustment to the traditional GDDF scheme, the inequality (\ref{eq34}) of the QP problem (\ref{eq32})-(\ref{eq34}) is not applied directly. For the GDDF scheme, when the margin is not considered, the upper limit and lower limits would overlap and the result is shown in Fig. \ref{fig.compare adjustment}. Specifically, the black line stands for the joint limit and the green line stands for the limit with margins. From the figure we can see that the movement of the joint is constrained by the limit with margins. Because of the margins, $\Theta_{g}^-$ and $\Theta_{g}^+$ of joint $7$ is not the same, so we propose that when the limit with margins reaches the goal value, they would hold that value. After adjustment, the joint would not exceed the margins. Fig. \ref{fig.compare adjustment} (b) gives the result of this modification. \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.49\columnwidth]{FIG-5-a.eps}} \subfigure[]{\includegraphics[width=0.49\columnwidth]{FIG-5-b.eps}} \caption{Comparisons between GDDF scheme with non-adjustment-margin and adjustment-margin. (a) Without adjustment. (b) With adjustment. }\label{fig.compare adjustment} \end{figure} We use the following equations to simplify, i.e., \begin{eqnarray} \Theta_{set}^+(t)=\Theta^++\frac{\Delta\Theta^+}{1+e^{-(t-\tau)/\varrho}}\\ \Theta_{set}^-(t)=\Theta^-+\frac{\Delta\Theta^-}{1+e^{-(t-\tau)/\varrho}}. \end{eqnarray} For joint $6$, $7$ and $13$, the upper limit and lower limit both $>0$, the following equations are introduced, i.e., $$ \kappa\tilde{\Theta}^+ =\left\{ \begin{aligned} &\kappa\Theta_{set}^+(t), && \kappa\tilde{\Theta}^+> \Theta_{g}^+\\ &\Theta_{g}^+, && \kappa\tilde{\Theta}^+ \leqslant \Theta_{g}^+ \end{aligned} \right. $$ $$ \kappa\tilde{\Theta}^- =\left\{ \begin{aligned} &(2-\kappa)\Theta_{set}^-(t), && \kappa\tilde{\Theta}^+< \Theta_{g}^-\\ &\Theta_{g}^-, && \kappa\tilde{\Theta}^-\geqslant \Theta_{g}^- \end{aligned} \right. $$ and function (\ref{fun18}) should be rewritten as $$ \tilde{\Theta}^+ =\left\{ \begin{aligned} &\Theta_{set}^+(t), && \tilde{\Theta}^+> \Theta_{g}^+/\kappa\\ &\Theta_{g}^+/\kappa, && \tilde{\Theta}^+ \leqslant \Theta_{g}^+/\kappa \end{aligned} \right. $$ $$ \tilde{\Theta}^- =\left\{ \begin{aligned} &\Theta_{set}^-(t), && \tilde{\Theta}^-< \Theta_{g}^-/(2-\kappa)\\ &\Theta_{g}^-/(2-\kappa), && \tilde{\Theta}^- \geqslant \Theta_{g}^-/(2-\kappa). \end{aligned} \right. $$ \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-6-a.eps}} \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-6-b.eps}} \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-6-c.eps}} \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-6-d.eps}} \caption{Comparisons between GDDF and MGDDF when $\varrho=2$, $N=2$. (a) Limit of joint $6$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin.}\label{fig.c2n2} \end{figure} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-7-a.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-7-b.eps}} \subfigure[]{\includegraphics[width=0.34\columnwidth]{FIG-7-c.eps}} \subfigure[]{\includegraphics[width=0.34\columnwidth]{FIG-7-d.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-7-e.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-7-f.eps}} \caption{Comparisons between GDDF and MGDDF when $\varrho=2$, $N=3$. (a) Limit of joint $7$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin. (e) Limit of Joint $14$ with margin. (d) Limit of joint $14$ without margin.} \label{fig.c2n3} \end{figure} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-8-a.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-8-b.eps}} \subfigure[]{\includegraphics[width=0.34\columnwidth]{FIG-8-c.eps}} \subfigure[]{\includegraphics[width=0.33\columnwidth]{FIG-8-d.eps}} \subfigure[]{\includegraphics[width=0.33\columnwidth]{FIG-8-e.eps}} \subfigure[]{\includegraphics[width=0.33\columnwidth]{FIG-8-f.eps}} \caption{Comparisons between GDDF and MGDDF when $\varrho=2$, $N=4$. (a) Limit of joint $6$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin. } \label{fig.c2n4} \end{figure} For joint $14$, the upper limit and lower limit both $<0$, hence $$ \tilde{\Theta}^+ =\left\{ \begin{aligned} &\Theta_{set}^+(t), && \tilde{\Theta}^+> \Theta_{g}^+/(2-\kappa)\\ &\Theta_{g}^+/(2-\kappa), && \tilde{\Theta}^+ \leqslant \Theta_{g}^+/(2-\kappa) \end{aligned} \right. $$ $$ \tilde{\Theta}^- =\left\{ \begin{aligned} &\Theta_{set}^-(t), && \tilde{\Theta}^-< \Theta_{g}^-/\kappa\\ &\Theta_{g}^-/\kappa, && \tilde{\Theta}^- \geqslant \Theta_{g}^-/\kappa. \end{aligned} \right. $$ \subsection{Comparisons between GDDF and MGDDF} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-9-a.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-9-b.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-9-c.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-9-d.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-9-e.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-9-f.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-9-g.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-9-h.eps}} \caption{Comparisons between GDDF and MGDDF when $\varrho=3$, $N=1$. (a) Limit of joint $6$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin. (e) Limit of joint $13$ with margin. (f) Limit of joint $13$ without margin. (g) Limit of joint $14$ with margin. (h) Limit of joint $14$ without margin.}\label{fig.c3n1} \end{figure} In this part, experiments are made to compare the proposed MGDDF scheme with the traditional GDDF scheme. Joints $6$, $7$, $13$ and $14$ are the main research objets. Similar to before, $\Theta_{g}^+$ and $\Theta_{g}^-$ of joints $6$, $7$, $13$ and $14$ are set as the same values. The parameter $\varrho$ is set as $\varrho=2$ and $N$ is set as $N=2$. From Fig. \ref{fig.c2n2} we could see that when applying GDDF scheme, joint $6$ exceed the limit of margins, and it cannot exceed its real limit. The similar situation happens in the experiment of joint $7$. Now parameter $N$ changes from $2$ to $3$. Joints $6$, $7$ and $14$ exceed their limits again. From Fig. \ref{fig.c2n3} (a) (c) and (e) we could see that by containing the margins, the proposed MGDDF can successfully complete the task. Similar conclusion can be drew when parameters $\varrho=2$ and $N=4$ for joints $6$ and $7$ in Fig. \ref{fig.c2n4}, parameters $\varrho=3$ and $N=1$ for joints $6$, $7$, $13$ and $14$ in Fig. \ref {fig.c3n1}, and parameters $\varrho=4$ and $N=1$ for joints $7$ and $14$ in Fig. \ref {fig.c4n1}. \subsection{The ``Ball-catch'' Experiment} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-10-a.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-10-b.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-10-c.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-10-d.eps}} \caption{Comparisons between GDDF and MGDDF when $\varrho=4$, $N=1$. (a) Limit of joint $7$ with margin. (b) Limit of joint $7$ without margin. (c) Limit of joint $14$ with margin. (d) Limit of joint $14$ without margin.} \label{fig.c4n1} \end{figure} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.49\columnwidth]{FIG-11-a.eps}} \subfigure[]{\includegraphics[width=0.48\columnwidth]{FIG-11-b.eps}} \caption{Motion trajectories of humanoid robot when applying to a ``ball-catch'' experiment. (a) Tracking trajectories of each joint. (b) Joint state of the dual arms.} \label{fig.ball} \end{figure} To validate the feasibility of the proposed method, a ``ball-catch'' experiment which was based on the 14 DOF humanoid is designed. For this experiment, the end-effector task is to move the ball up, left, down, and then back. Fig. \ref{fig.ball} demonstrates the motion trajectories and joint state of the dual arms of the humanoid robot in this experiment. The task can be completed and all the 14 joints maintain their joint limits successfully. All the simulative experiment results illustrated above verify the effectiveness of the proposed MGDDF method. \section{Conclusions} In this paper, the gesture-determined-dynamic function (GDDF) scheme is promoted and its deficiency is fixed. With consideration of three margins, a modified scheme named MGDDF is proposed for solving kinematic problems of dual arms of humanoid robots. Embed into a quadratic programming framework, the gesture of dual arms can be smoothly achieved by using MGDDF method, and the joints would not exceed their limits during the execution of tasks. Computer simulations verify the feasibility, accuracy and superiority of the proposed MGDDF method for solving motion planning and gesture determination of humanoid robots. \section*{Nomenclature} The full name of abbreviations proposed in this paper are listed as follows: \begin{eqnarray*} \begin{split} \textsc{GDDF} ~~~~~~~~~ &\textmd{Gesture-determined-dynamic function}.\\ \textsc{MGDDF} ~~~~~ &\textmd{Modified gesture-determined-dynamic function}.\\ \textsc{QP} ~~~~~~~~~~~~~~ \ &\textmd{Quadratic programming}.\\ \textsc{DOF} ~~~~~~~~~~~ \ &\textmd{Degrees-of-freedom}.\\ \textsc{MKE} ~~~~~~~~~~ \ &\textmd{Minimum-kinetic-energy}.\\ \textsc{RMP} ~~~~~~~~~~ \ &\textmd{Repetitive motion planning}.\\ \textsc{MVN} ~~~~~~~~~ \ &\textmd{Minimum-velocity-norm}.\\ \textsc{LVI} ~~~~~~~~~~~~~ \ &\textmd{Linear-variational-inequality}. \end{split} \end{eqnarray*} \section{Introduction} A robot is a programmable machine capable of executing complex tasks automatically. Traditionally, robots are designed to perform mechanical actions with no regard to how they look. With the thrive of the robotic industry, as well as the higher psychological requirement of human beings, more and more robots are designed and conducted to take on human form \cite{paper.1}. Such similarity can be for functional purposes, for example, interacting with human instruments and facilities, or for other experimental purposes \cite{paper.2,paper.3}. In general, these humanoid robots are endowed with similar body structure of human beings, i.e., a head, a torso, two arms, and two legs \cite{paper.4}. Some of them also have their head designed to replicate emotional expressions of the human face, such as eye-blinking and lip-sipping \cite{paper.5}. An automatic perception for facial expressions of humanoid robots proposed by Zhang $et \ al.$ demonstrated the potential in developing personalized robots with social intelligence \cite{paper.6}. Trovato $et \ al.$ created a facial expression generator applied to a KOBIAN-R robot to establish an adaptive system based on human communication and facial anatomy \cite{paper.7}. Such a system is effective for the implementation of complex interactions between humans and robots. For a XIN-REN robot, a facial expression learning method based on energy conservation principle proposed by Ren $et \ al.$ successfully ensured smoother trajectories for multi-frame imitation of humanoid robots \cite{paper.8}. In addition to the head, the arms are also crucial and indispensable for the humanoid robot. Recently, various novel humanoid robots equipped with arms have been studied and further applied to home service, personal entertainment, inspection, health care, manufacturing, and so on \cite{article.2,article.3,article.4,article.5}. The dual arms of humanoid robots can not only fulfill task manipulation \cite{article.6}, but also convey emotions with body language \cite{article.7, article.8}. To perform daily tasks with dual-arms of humanoid robots, the motion planning problem should be considered. Aly $et \ al.$ proposed a system to generate the dynamic characteristics of gestures and postures of the NAO robot during nonverbal communications \cite{paper.9,paper.10}. Tondu $et \ al.$ designed an anthropomorphic robot arm and its ancillary motion control method \cite{paper.11}. One of the basic problems of dual-arm motion planning is the inverse kinematic problem \cite{article.9}, i.e., given the trajectories of end-effector, computing joint variables at each time instant \cite{book.8}. Most dual arms of humanoid robots have more than three degrees of freedom (termed as DOF). This redundancy improves the flexibility of dual arms when the humanoid robots implement end-effector tasks \cite{article.11}. However, the redundant DOF also inevitably increases the difficulties of computation \cite{article.12}. The traditional redundancy resolution method is pseudo-inverse method \cite{article.13}. Wang $et \ al.$ proposed a closed-loop inverse kinematics in Ref. \cite{article.14}, which was based on pseudo-inverse method, to control the dual arms on a mobile platform. Noting that the inverse of matrices has to be considered when utilizing the pseudo-inverse methods, which is difficult \cite{article.15}. Quadratic programming (termed as QP) methods are preferred recently, and a QP-based task priority framework is proposed in Ref. \cite{article.16} to resolve the kinematic redundancy problem. Inspired by the aforementioned optimization method, a QP-based online generation scheme for generating expected gestures of dual arms is proposed by Zhang $et \ al.$ \cite{article.1}, and a gesture-determined-dynamic function (termed as GDDF) is designed and introduced to the kinematics of humanoid robots. This GDDF scheme can not only handle the redundancy resolution problem within the joint limits, but also dynamically adjust gestures to the desired position. Different from the exiting pseudo-inverse method \cite{article.17,article.18,article.19} or very few QP-based methods focusing on single arm \cite{article.20,article.21,article.22}, together with the numerical QP solver, the GDDF scheme can generate the behaviors of the dual arms of humanoid robots \cite{article.23,article.24,article.26,article.28} in 3-D space online. However, there is still a deficiency in the GDDF scheme. On the basis of a series of experiments, we find that at some parameter groups during execution, the joint might slightly exceed its limit. That is to say, if the parameter is falsely selected, dead-lock of robot arms or even damages could occur, which is perilous for the practical applications. To remedy this disadvantage, a modified GDDF method named MGDDF is proposed in this paper. With consideration of three kinds of margins (i.e., MGDDF-1, MGDDF-2 and MGDDF-3, which will be carefully discussed in the following sections) are introduced to the MGDDF method to constrain the movement of the joints. The remainder of this paper is listed as follows. The overviews of related works are presented in Section II. Section III gives the preliminary and problem formulation of dual arms. The traditional GDDF method and the proposed MGDDF method are discussed in Section IV. Simulative experiments are made in Section V to verify the effectiveness of the proposed method. Section VI offers a concluding remark. The main contributions of this paper can be summarized as follows: \begin{itemize} \item With consideration of three margins, a modified scheme named MGDDF is proposed for solving kinematic problems of dual arms of humanoid robot. \item The gesture of dual arms can be smoothly achieved by using MGDDF method, and the joints would not exceed their limits during the whole execution of tasks. \end{itemize} \section{Related Works} The motion planning of humanoid robots have been studied for a few decades. Gouda $et \ al.$ proposed a whole-body motion planning approach of NAO robot using onboard sensing and achieved reliable motion sequences when operating in complex environment \cite{related.1}. A path planning method which computes dynamics and collision avoidance for full-body gestures of humanoid robots was proposed by Kagami $et \ al.$ \cite{related.2}. This method contains a filtering function that constrains the zero moment point of each trajectory to obtain statically stabilization for the entire body. Without lost of generality, Dalibard $et \ al.$ presented a collision-free method for whole-body working control of humanoid robots \cite{related.3}. In Ref. \cite{related.4}, Ohashi $et \ al.$ introduced a linear inverted pendulum mode and designed a collision avoidance method for a robot with an upper body to discriminate the start/stop of force of robot arms. On the basis of Lyapunov stability theory, an adaptive control method was proposed by Liu $et \ al.$ to satisfy the coordination of dual arms of humanoid robots \cite{related.5}. Simulation results prove that when applying this method, the internal force of the arms can be held and the position errors are arbitrarily small. As for the motion optimization, Ayusawa $et \ al.$ proposed a novel re-targeting method with geometric parameter identification, motion planning and inverse kinematics to handle control problems of humanoid robots \cite{related.6}. A practical experiment performed on HRP-4 robot further verified the excellent performance of this method. In Ref. \cite{related.7}, an optimization-based approach was proposed by Schulman $et \ al.$ to find collision-free trajectories of a 18 degrees-of-freedom robot with dual arms. Hong $et \ al.$ who focused on real-time pattern generation utilized the linear pendulum model to solve the walking control problem of MAHRU-R robot with feed-forward and feed-back controller \cite{related.8}. The desired task hierarchy which is based on quadratic programming was solve by Liu $et \ al.$ to reduce the risk of instability when humanoid robots conducting operations \cite{related.9}. According to HRP-2 robot, a novel plan for foot placements was proposed by Kanoun $et \ al.$ to formulate the deformation problem as the inverse kinematic problem and to further be described as a locomotion phase of the desired tasks. \cite{related.10}. For the posture control problem, Choi $et \ al.$ proposed a kinematic resolution method based on the center of mass Jacobian with embedded motion of humanoid robots \cite{related.11}. A motion planning using swept volume approximation was researched by Perrin $et \ al.$ to achieve the 3-D obstacle avoidance \cite{related.12}. In the field of gesture generation, Yanik $et \ al.$ proposed a gesture recognition scheme for path shaping of simulated robot \cite{new.0}. They first extracted gesture data from sequential skeletal depth and then clustered them by a growing neural gas algorithm. Cheng $et \ al.$ presented a hand-gesture-recognition method which can track gestures of a dance robot in real-time \cite{new.1}. The hand gestures were recorded as signals detected by a 3-axis sensor and represented as discrete cosine transform coefficients. Furthermore, a artificial communicator for gesture recognition, proposed by Zhang $et \ al.$, was utilized for human-robot cooperative assembly \cite{new.2}. In Ref. \cite{new.3}, the tracking control of manipulators was solved by nonlinear observers which provided joint coordinate rates. Arteaga $et \ al.$ utilized this method by associating Euler-Lagrange equations to describe gesture motions and achieved high control accuracy. \section{Preliminary and Problem Formulation}\label{sec.model} The forward kinematics of dual arms of humanoid robots can be described as \begin{equation} \textit{\textbf{p}}_L=\Im_L(\mathbf{\theta}_L), \ \textit{\textbf{p}}_R=\Im_R(\mathbf{\theta}_R)\label{equ.timeinv} \end{equation} where $\textit{\textbf{p}}_L$ and $\textit{\textbf{p}}_R$ denote the position vectors of the end effector. $\theta_L$ and $\theta_R$ stand for the vectors of left and right joints. $\Im_L(\cdot)$ and $\Im_R(\cdot)$ are continuous nonlinear functions. These two equations can be obtained when the manipulator is given. For redundant manipulator, the inverse kinematic problem is basic and the motion states of each joint should be solved according to the trajectories of the end effector. Inspired by previous work in Ref. \cite{article.1}, an online optimization algorithm to solve the redundancy problem is presented. The following equations at velocity level are obtained \begin{eqnarray} \frac{\dot{\theta}_L^\text{T}\textit{\textbf{A}}\dot{\theta}_L}{2}+\frac{\dot{\theta}_R^\text{T}\textit{\textbf{B}}\dot{\theta}_R}{2} +\textit{\textbf{c}}_L^\text{T}\theta_L+\textit{\textbf{c}}_R^\text{T}\theta_R\label{eq4}\\ \textit{\textbf{J}}_L(\theta_L)\dot{\theta}_L=\dot{\textit{\textbf{p}}}_L+\wp_L\big(\textit{\textbf{p}}_L-\Im_L(\theta_L)\big)\label{eq5}\\ \textit{\textbf{J}}_R(\theta_R)\dot{\theta}_R=\dot{\textit{\textbf{p}}}_R+\wp_R\big(\textit{\textbf{p}}_R-\Im_R(\theta_R)\big)\label{eq6}\\ \theta_L^-\leqslant\theta_L\leqslant\theta_L^+\label{eq7}\\ \theta_R^-\leqslant\theta_R\leqslant\theta_R^+\label{eq8}\\ \dot{\theta}_L^-\leqslant\dot{\theta}_L\leqslant\dot{\theta}_L^+\label{eq9}\\ \dot{\theta}_R^-\leqslant\dot{\theta}_R\leqslant\dot{\theta}_R^+\label{eq10} \end{eqnarray} where superscript $^\text{T}$ denotes the transpose of a vector or a matrix. $\dot{\theta}_{L}$ and $\dot{\theta}_{R}\in \mathbb{R}^n$ denote joint-velocity vectors of left and right arms. $\textit{\textbf{A}}\in \mathbb{R}^{n\times n}$ and $\textit{\textbf{B}}\in \mathbb{R}^{n\times n}$ are coefficient matrices of quadratic terms. $\textit{\textbf{c}}_L$ and $\textit{\textbf{c}}_R$ are coefficient vectors related to linear terms. $\textit{\textbf{J}}_L(\cdot)$ and $\textit{\textbf{J}}_R(\cdot)\in \mathbb{R}^{n\times m}$ are the Jacobian matrices of the left and right arms, respectively. $\dot{\textit{\textbf{p}}}_{L}$ and $\dot{\textit{\textbf{p}}}_{R}\in \mathbb{R}^n$ denote velocity vectors of the end effector. The position-error feedbacks $\wp_L\big(\textit{\textbf{p}}_L-\Im_L(\theta_L)\big)$ and $\wp_R\big(\textit{\textbf{p}}_R-\Im_R(\theta_R)\big)$ are considered with non-negative parameters $\wp_L$ and $\wp_R$. The series of inequalities (\ref{eq7})-(\ref{eq10}) are the constraints of joints and joint-velocities. $\theta_L^\pm$ and $\theta_R^\pm$ denote physical joint limits, while $\dot{\theta}_L^\pm$ and $\dot{\theta}_R^\pm$ denote joint-velocity limits, respectively. The aforementioned dual formulas (\ref{eq5})-(\ref{eq10}) can be combined as matrix forms to offer a much more clear expression, i.e., $\bullet$ position-error feedback equalities (\ref{eq5})-(\ref{eq6}) are combined as \begin{equation} \begin{bmatrix} \textit{\textbf{J}}_\text{L} &\textbf{\text{0}}_{m\times n}\\ \textbf{\text{0}}_{m\times n} &\textit{\textbf{J}}_\text{R} \end{bmatrix} \cdot \begin{bmatrix} \dot{\theta}_L\\ \dot{\theta}_R \end{bmatrix} = \begin{bmatrix} \dot{\textit{\textbf{p}}}_L\\ \dot{\textit{\textbf{p}}}_R \end{bmatrix} + \begin{bmatrix} \wp_L\big(\textit{\textbf{p}}_L-\Im_L(\theta_L)\big)\\ \wp_R\big(\textit{\textbf{p}}_R-\Im_R(\theta_R)\big) \end{bmatrix}; \label{eqn.c1} \end{equation} $\bullet$ joint limit inequalities (\ref{eq7})-(\ref{eq8}) are combined as \begin{eqnarray} \begin{bmatrix} \theta_L^-\\ \theta_R^- \end{bmatrix} \leqslant \begin{bmatrix} \theta_L\\ \theta_R \end{bmatrix} \leqslant \begin{bmatrix} \theta_L^+\\ \theta_R^+ \end{bmatrix} \in \mathbb{R}^{2n}; \label{eqn.c2} \end{eqnarray} $\bullet$ joint-velocity limit inequalities (\ref{eq9})-(\ref{eq10}) are combined as \begin{eqnarray} \begin{bmatrix} \dot{\theta}_L^-\\ \dot{\theta}_R^- \end{bmatrix} \leqslant \begin{bmatrix} \dot{\theta}_L\\ \dot{\theta}_R \end{bmatrix} \leqslant \begin{bmatrix} \dot{\theta}_L^+\\ \dot{\theta}_R^+ \end{bmatrix} \in \mathbb{R}^{2n}. \label{eqn.c3} \end{eqnarray} With the consideration of objective function (\ref{eq4}) and modified constrains (\ref{eqn.c1})-(\ref{eqn.c3}), the following standard QP can be formulated as follows \begin{eqnarray} \text{min.} \ ~ \frac{\dot{\Theta}^\text{T}\textit{\textbf{M}}\dot{\Theta}}{2}+\textit{\textbf{c}}^\text{T}\Theta\label{eq14}~~~~~~~~~~~~~~~~~~ \\ \text{s. t.} \ ~ \textit{\textbf{J}}(\Theta)\dot{\Theta}=\dot{\Upsilon}+\wp(\Upsilon-\Im(\Theta))\\ \Theta^-\leqslant\Theta\leqslant\Theta^+\label{eq16}\\ \dot{\Theta}^-\leqslant\dot{\Theta}\leqslant\dot{\Theta}^+\label{eq17} \end{eqnarray} where $\Theta=[\theta_L^\text{T}, \theta_R^\text{T}]$, $\textit{\textbf{c}}=[\textit{\textbf{c}}_L^\text{T}, \textit{\textbf{c}}_R^\text{T}]$, $\Theta^-=[\theta_L^{-\text{T}}, \theta_R^{-\text{T}}]^\text{T}$, $\Theta^+=[\theta_L^{+\text{T}}, \theta_R^{+\text{T}}]^\text{T}$, $\dot{\Theta}=\text{d}\Theta/\text{d}t=[\dot{\theta}_L^\text{T}, \dot{\theta}_R^\text{T}]$, $\dot{\Theta}^-=[\dot{\theta}_L^{-\text{T}}, \dot{\theta}_R^{-\text{T}}]^\text{T}$, $\dot{\Theta}^+=[\dot{\theta}_L^{+\text{T}}, \dot{\theta}_R^{+\text{T}}]^\text{T}$, $\dot{\Upsilon}=[\dot{\textit{\textbf{p}}}_L^\text{T}, \dot{\textit{\textbf{p}}}_R^\text{T}]^\text{T}$, \begin{equation} \textit{\textbf{M}}= \begin{bmatrix} \textit{\textbf{A}} &\textbf{\text{0}}_{n\times n}\\ \textbf{\text{0}}_{n\times n} &\textit{\textbf{B}} \end{bmatrix} \in \mathbb{R}^{2n\times 2n}, \end{equation} \begin{equation} \textit{\textbf{J}}= \begin{bmatrix} \textit{\textbf{J}}_L &\textbf{\text{0}}_{n\times n}\\ \textbf{\text{0}}_{n\times n} &\textit{\textbf{J}}_R \end{bmatrix} \in \mathbb{R}^{2m\times 2n}, \end{equation} \begin{equation} \wp= \begin{bmatrix} \wp_L &\textbf{\text{0}}_{m\times m}\\ \textbf{\text{0}}_{m\times m} &\wp_R \end{bmatrix} \in \mathbb{R}^{2m\times 2m}. \end{equation} It is worth pointing out that vector $\textit{\textbf{c}}$ and matrix $\textit{\textbf{M}}$ are determined by a definite redundancy-resolution scheme. Matrix $\wp$ stands for the feedback gain and is determined by practical effect. Different goals can be obtained by choosing different criterions of vector $\textit{\textbf{c}}$ and matrix $\textit{\textbf{M}}$. The following three schemes are introduced, i.e., $\bullet$ MKE scheme: If vector $\textit{\textbf{c}}=[\textbf{\text{0}}; \textbf{\text{0}}]$, and matrix $\textit{\textbf{M}}=[\mathcal{I}_L, 0; 0, \mathcal{I}_R]$ (where $\mathcal{I}$ denotes inertia matrix), then QP problem (\ref{eq14})-(\ref{eq17}) forms a minimum-kinetic-energy (MKE) scheme. $\bullet$ RMP scheme: If vector $\textit{\textbf{c}}=[\lambda(\theta_L-\theta_L(0)); \lambda(\theta_R-\theta_R(0))]$ (where $\lambda$ is a non-negative parameter), and matrix $\textit{\textbf{M}}=\textit{\textbf{I}}$ is an identity matrix, then QP problem (\ref{eq14})-(\ref{eq17}) forms a repetitive motion planning (RMP) scheme. $\bullet$ MVN scheme: If vector $\textit{\textbf{c}}=[\textbf{\text{0}}$, and matrix $\textit{\textbf{M}}=\textit{\textbf{I}}$ is an identity matrix, then QP problem (\ref{eq14})-(\ref{eq17}) forms a minimum-velocity-norm (MVN) scheme. \section{Proposed Method} Humanoid robots are not only asked to finish the end-effector tasks, but also are demanded to ``behave'' naturally as a human \cite{paper.8,article.23,article.24}. Being the most straight way of expressing feelings and emotions, gestures of humanoid robots have been widely designed and exerted to accomplish natural human-robot interactions \cite{article.26,article.27,article.28}. A gesture-determined-dynamic function (GDDF) is presented in Ref. \cite{article.1}. Associating with a QP framework (\ref{eq14})-(\ref{eq17}) and the GDDF method, the researchers expect to cause expected gestures of humanoid robots. \subsection{GDDF Scheme} To generate the expected movement and to execute the end-effector tasks, some joints of the dual arms should be dynamically adjustable \cite{article.1,article.8,article.9,myarticle.11,myarticle.21,myarticle.31,myarticle.41}. The joint limits and joint-velocity limits have already been formulated into QP problem (\ref{eq14})-(\ref{eq17}). A dynamic function which can change the upper and the lower bounds of the limits should be found, and the bounds should be related to the expectation values. Besides, the generated curves should be smooth during the executing process. The following function is then designed to satisfy the demand and the joints can adjust to the expected gesture, i.e., \begin{equation} \tilde{\Theta}^\pm(t)=\Theta^\pm+\frac{\Delta\Theta^\pm}{1+e^{-(t-\tau)/\varrho}}\label{fun18} \end{equation} where $\Delta\Theta^\pm=\Theta_{g}^\pm-\Theta^\pm$, and $\Theta_{g}=[\Theta_{gL}^\text{T}; \Theta_{gR}^\text{T}]$ sets the goal configuration of joint. $\varrho$ is a parameter affecting the variation trend. Parameter $\tau=T_d/N$, with $T_d$ denoting the task execution time and $N\geqslant 1$ denoting the parameter affecting the proximity between the adjusted value and the actual value (set point). $\Delta\Theta$ determines whether $\tilde{\Theta}$ increases or decreases. Normally speaking $\tilde{\Theta}^+$ decreases while $\tilde{\Theta}^-$ increases. Fraction $1/[1+e^{-(t-\tau)/\varrho}]$ is a gradual and smooth function and it influences the curve shape of the joint limit. When time $t$ approaches infinite, $e^{-(t-\tau)/\varrho}$ will approach $0$, thus the fraction will approach $1$, and $\tilde{\Theta}^\pm$ will approach $\Theta^\pm+\Delta\Theta^\pm=\Theta_{g}^\pm$. Function (\ref{fun18}) can lead to the expected movement smoothly and slowly. On the basis of smooth function (\ref{fun18}) and QP-based framework (\ref{eq14})-(\ref{eq17}), the GDDF scheme can be successfully established. The upper and lower bounds of the inequalities will constrain the movement of the joints, and make the joints move just as expected. For dual arms of humanoid robots, all the joints can be adjusted to the tasks at the same time. As for each \emph{i}-th joint, we can set $\Theta_{g\emph{i}}^+=\Theta^+$ and $\Theta_{g\emph{i}}^-=\Theta^-$, and the corresponding joints would reach the target values equally. To achieve the joints' expected gestures, a series of values of parameters $\varrho$, $\tau$ and $N$ which influence the proximity between the adjusted value and the actual value can be easily set. \subsection{MGDDF Scheme with Consideration of Margins} The gestures can be smoothly achieved by using GDDF method. However, there is still a deficiency in this scheme. Through the experiment we find that the joint might exceed its limit slightly at some parameter groups. To remedy this problem, three kinds of margins are introduced to constrain the movement of the joints. This modified GDDF method is termed as MGDDF method. $\bullet$ MGDDF-1: \begin{figure*} \centering \includegraphics[width=.99\textwidth]{FIG-1.eps}\\ \caption{Graphical representation of the margins of MGDDF-1. Both upper bound and lower bound of joint limits are greater than zero.}\label{fig.MGDDF-1} \end{figure*} Firstly, joint limit (\ref{eq16}) is rewritten as \begin{equation} \tilde{\Theta}^-\leqslant\Theta\leqslant\tilde{\Theta}^+ \label{eqn.MGDDF-1} \end{equation} Secondly, a margin set at velocity level is considered, and the joint limit constraint (\ref{eqn.MGDDF-1}) is modified as follows \begin{equation} \nu\big((2-\kappa)\tilde{\Theta}^-(t)-\Theta\big)\leqslant\dot{\Theta}\leqslant\nu\big(\kappa\tilde{\Theta}^+(t)-\Theta\big) \label{eqn.cons} \end{equation} where $\dot{\Theta}$ denote the joint velocity and $\nu>0$ is a parameter which is applied to scale the feasible region of $\dot{\Theta}$. For simplicity, $\nu$ is set as $\nu=2$ in the following experiments. The critical coefficient $\kappa\in(0,1)$ is selected to define a critical region $(\Theta_i^-, (2-\kappa)\Theta_i^-]$ and $[\kappa\Theta_i^+, \Theta_i^+)$, which is shown in Fig. \ref{fig.MGDDF-1}. It is worth noting that, MGDDF-1 is suitable for the case that the upper bound and lower bound of joint limits are greater than zero. Moreover, for the \emph{i}-th joint, the joint-velocity constraint of MGDDF-1 are be formulated as follows \begin{eqnarray} \begin{split} \text{max}\big\{\dot{\Theta}^-,\nu\big((2-\kappa)\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}&\leq\dot{\Theta}_{\emph{i}}\\ \text{min}\big\{\dot{\Theta}^+,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}&\geq\dot{\Theta}_{\emph{i}}. \end{split} \label{eqn.v-MGDDF-1} \end{eqnarray} To simplify the expression of joint-velocity constraint (\ref{eqn.v-MGDDF-1}), the following equations are introduced, i.e., \begin{eqnarray} \tilde{\zeta}_{\emph{i}}^-(t)=\text{max}\big\{\dot{\Theta}^-,\nu\big((2-\kappa)\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}\\ \tilde{\zeta}_{\emph{i}}^+(t)=\text{min}\big\{\dot{\Theta}^+,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}. \end{eqnarray} $\bullet$ MGDDF-2: \begin{figure*} \centering \includegraphics[width=.99\textwidth]{FIG-2.eps}\\ \caption{Graphical representation of the margins of MGDDF-2. The upper bound of joint limits is greater than zero, while the lower bound of joint limits is less than zero.}\label{fig.MGDDF-2} \end{figure*} Considering the case that upper limit $>0$ and lower limit $<0$. On the basis of constraint (\ref{eqn.cons}), the critical region of MGDDF-2 is $(\Theta_i^-, \kappa\Theta_i^-]$ and $[\kappa\Theta_i^+, \Theta_i^+)$. The graphical representation of the margins of MGDDF-2 is depicted in Fig. \ref{fig.MGDDF-1}. Similar to MGDDF-1, the joint-velocity constraint of MGDDF-2 is simplified as the following relationships, i.e., \begin{eqnarray} \tilde{\zeta}_{\emph{i}}^-(t)=\text{max}\big\{\dot{\Theta}^-,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}\\ \tilde{\zeta}_{\emph{i}}^+(t)=\text{min}\big\{\dot{\Theta}^+,\nu\big(\kappa\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}. \end{eqnarray} $\bullet$ MGDDF-3: When both the upper bound and lower bound of limits are less than zero, the critical region of MGDDF-3 are $(\Theta_i^-, \kappa\Theta_i^-]$ and $[(2-\kappa)\Theta_i^+, \Theta_i^+)$. Sharing the same process, the following result is obtained, i.e., \begin{eqnarray} \tilde{\zeta}_{\emph{i}}^-(t)=\text{max}\big\{\dot{\Theta}^-,\nu\big(\tilde{\Theta}_{\emph{i}}^-(t)-\Theta_{\emph{i}}\big)\big\}\\ \tilde{\zeta}_{\emph{i}}^+(t)=\text{min}\big\{\dot{\Theta}^+,\nu\big((2-\kappa)\tilde{\Theta}_{\emph{i}}^+(t)-\Theta_{\emph{i}}\big)\big\}. \end{eqnarray} Combining the aforementioned MGDDF-1, MGDDF-2 and MGDDF-3, the MGDDF scheme with consideration of margins is obtained, i.e., \begin{eqnarray} \text{min.} \ ~ \frac{\dot{\Theta}^\text{T}\textit{\textbf{M}}\dot{\Theta}}{2}+\textit{\textbf{c}}^\text{T}\Theta\label{eq32}~~~~~~~~~~~~~~~~~~ \\ \text{s. t.} \ ~ \textit{\textbf{J}}(\Theta)\dot{\Theta}=\dot{\Upsilon}+\wp(\Upsilon-\Im(\Theta))\label{eq33}\\ \tilde{\zeta}_{\emph{i}}^-(t)\leqslant\dot{\Theta}\leqslant\tilde{\zeta}_{\emph{i}}^+(t)\label{eq34} \end{eqnarray} \begin{figure*} \centering \includegraphics[width=.99\textwidth]{FIG-3.eps}\\ \caption{Graphical representation of the margins of MGDDF-3. Both upper bound and lower bound of joint limits are less than zero.}\label{fig.MGDDF-3} \end{figure*} In summary, the kinematic task of the dual arms of the humanoid robot can be successfully finished by using the proposed MGDDF scheme (\ref{eq32})-(\ref{eq34}). The end-effector velocities $\dot{\textit{\textbf{p}}}_L$ and $\dot{\textit{\textbf{p}}}_R$ are integrated into equation (\ref{eq33}). The key function (\ref{fun18}) determines the upper and lower bounds of inequality (\ref{eq34}). It is worth mentioning that the proposed MGDDF scheme can be solved by a discrete QP solver, which will be discussed in the following sub-section. \subsection{MGDDF Solvers} According to Refs. \cite{article.12, article.15}, a linear-variational-inequality (LVI) is introduced to solve MGDDF scheme (\ref{eq32})-(\ref{eq34}). Equivalently, a linear projection equation is led to replace these equations, i.e., \begin{equation} \Phi_{\Omega}\big(\textit{\textbf{d}}-(\Gamma \textit{\textbf{d}}+\textit{\textbf{q}})\big)-\textit{\textbf{d}}=0 \end{equation} where $\Phi_{\Omega}(\cdot)$ ($\mathbb{R}^{2n+2m}\rightarrow\Omega$) is a projection operator with set $\Omega=\{\textit{\textbf{d}} ~|~\textit{\textbf{d}}^-\leqslant\textit{\textbf{d}}\leqslant\textit{\textbf{d}}^+\}\subset \mathbb{R}^{2n+2m}$. $\textit{\textbf{d}}=[\Theta; \iota]$, $\textit{\textbf{d}}^+=[\tilde{\zeta}^+(t); \omega \textit{\textbf{l}}_{\iota}]\in \mathbb{R}^{2n+2m}$, $\textit{\textbf{d}}^-=[\tilde{\zeta}^-(t); -\omega \textit{\textbf{l}}_{\iota}]\in \mathbb{R}^{2n+2m}$, $\Gamma=[\textit{\textbf{M}}, -\textit{\textbf{J}}^\text{T}(\Theta); \textit{\textbf{J}}(\Theta), \textbf{\text{0}}]\in \mathbb{R}^{(2n+2m)\times (2n+2m)}$, $\textit{\textbf{q}}=[\textbf{\text{0}}; -\dot{\Upsilon}]\in \mathbb{R}^{n+m}$, and $\textit{\textbf{l}}_{\iota}=[\textbf{1}, \cdots, \textbf{1}]^\text{T}$. Besides, $\textit{\textbf{d}}\in \mathbb{R}^m$ denotes the primal-dual decision vector, $\textit{\textbf{d}}^+\in \mathbb{R}^m$ and $\textit{\textbf{d}}^-\in \mathbb{R}^m$ are the upper and lower bounds, severally. $\omega$ is valued enormous ($\varpi:=10^{10}$) in the experiments. We define $\varepsilon(\textit{\textbf{d}}):= \textit{\textbf{d}}-\Phi_{\Omega}\big(\textit{\textbf{d}}-(\Gamma \textit{\textbf{d}}+\textit{\textbf{q}})\big)$, and the iterative algorithm causes $\varepsilon(\textit{\textbf{d}})\rightarrow 0$. $\textit{\textbf{d}}^0\in \mathbb{R}^{2n+2m}$ is the original primal-dual decision variable vector, $k=0,1,2,3,\cdots$, if $\textit{\textbf{d}}^k\notin \Omega^*$, then \begin{equation} \textit{\textbf{d}}^{k+1}=\textit{\textbf{d}}^k-\frac{||\varepsilon(\textit{\textbf{d}}^k)||_2^2\sigma(\textit{\textbf{d}}^k)} {||\sigma(\textit{\textbf{d}}^k)||_2^2}\label{eq36} \end{equation} where $\varepsilon(\textit{\textbf{d}}^k)=\textit{\textbf{d}}^k-\Phi_{\Omega}(\textit{\textbf{d}}^k-(\Gamma \textit{\textbf{d}}^k+\textit{\textbf{q}}))$ and $\sigma(\textit{\textbf{d}}^k)=(\Gamma+I)\varepsilon(\textit{\textbf{d}}^k)$. In numerical calculation, $\varepsilon(\textit{\textbf{d}}^k)=10^{-5}$. \begin{lemma} \cite{article.9} The sequence $\{\textit{\textbf{d}}^k\}, k=1, 2, \cdots$, which is generated by QP-solution (\ref{eq36}), satisfies \begin{equation} ||\textit{\textbf{d}}^{k+1}-\textit{\textbf{d}}^{\star}||_2^2\leqslant||\textit{\textbf{d}}^k-\textit{\textbf{d}}^{\star}||_2^2- \frac{||\varepsilon(\textit{\textbf{d}}^k)_2^4}{||\sigma(\textit{\textbf{d}}^k)||_2^2}. \end{equation} \end{lemma} This lemma is applied to all $\textit{\textbf{d}}^{\star}\in\Omega^{\star}$. The solution vector $\textit{\textbf{d}}^{\star}$ comes from $\{\textit{\textbf{d}}^k\}$, and its first $2n$ elements consist of the optimal solution to MGDDF (\ref{eq32})-(\ref{eq34}), $\Theta^{\star}\in \mathbb{R}^n$. Definitely, the first $n$ elements constitute the optimal solutions of the left-arm joints, while the second $n$ elements constitute right-arm joints' optimal solution. \begin{corollary} For any positive constant $\Xi>0$, error vector $\epsilon\in\mathbb{R}^n$ of a dynamic system $\dot{\epsilon}=-\Xi\epsilon$, starting from any initial state $\epsilon(0)$, converges to zero with exponential convergence speed, where $\dot{\epsilon}$ is the first-order derivative of $\epsilon$ with respect to time $t$. \end{corollary} \begin{corollary} For any positive constant $\Xi>0$ and disturbance $\Delta\Xi>-\Xi$, a dynamic system with disturbance parameter $\dot{\epsilon}=-(\Xi+\Delta\Xi)\epsilon$ is robust for the uncertain-parameter situation, where $\dot{\epsilon}$ is the first-order derivative of $\epsilon$ with respect to time $t$. \end{corollary} According to dual theory and Lagrange theory \cite{NN29,NN30}, the proposed MGDDF (\ref{eq32})-(\ref{eq34}) can also be solved by a neural network solver. To find a primal dual equilibrium vector $\mathcal{K}\in\mathbb{R}^{2m}$, MGDDF (\ref{eq32})-(\ref{eq34}) should be converted into the following linear variational inequalities, i.e., \begin{equation} \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix}\in\Omega :=\bigg\{ \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix} ~\bigg|~ \begin{bmatrix} \tilde{\zeta}_{\emph{i}}^-(t)\\ -z\textit{\textbf{l}}_{\mathcal{K}} \end{bmatrix} \leq \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix} \leq \begin{bmatrix} \tilde{\zeta}_{\emph{i}}^+(t)\\ +z\textit{\textbf{l}}_{\mathcal{K}} \end{bmatrix}\bigg\}\subset\mathbb{R}^{2n+2m} \end{equation} where $\textit{\textbf{l}}_{\mathcal{K}}=[\textbf{1}, \cdots, \textbf{1}]^\text{T}$ and $z$ is set to approximate $m$-dimensional $+\infty$. Such that \begin{equation} \bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix} \bigg)^{\text{T}} \bigg(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}^*\\ \mathcal{K}^* \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix} \bigg)\geq0, \forall \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}\in\Omega \end{equation} where $\mathcal{I}\in\mathbb{R}^{2n\times2n}$. According to Ref. \cite{NN31}, the above relationship is equivalent to a piecewise-linear-equation system satisfy \begin{equation} \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg)- \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}=0 \label{equ.nn-1} \end{equation} where $\mathcal{P}_{\Omega}(\cdot):\mathbb{R}^{2n+2m}\rightarrow\Omega$ is the projection operator. With projective theory, system (\ref{equ.nn-1}) can be computed by the recurrent neural network below \begin{equation} \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} =\mathcal{H}\bigg(\mathcal{E}+ \begin{bmatrix} \mathcal{I} &\textit{\textbf{J}}\\ -\textit{\textbf{J}}^{\text{T}} &\textbf{0} \end{bmatrix}\bigg) \cdot \bigg\{ \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg)- \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix} \bigg\} \label{equ.nn-2} \end{equation} where $\mathcal{H}>0$ is designed to scale convergent rate and $\mathcal{E}\in\mathbb{R}^{(2n+2m)\times(2n+2m)}$ denotes identity matrix. \begin{theorem} State vector $[\dot{\Theta}, \mathcal{K}]^{\text{T}}$ of (\ref{equ.nn-2}), starting from any initial state, can globally convergent to an equilibrium point $[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}$, of which the first $2n$ elements constitute optimal solution $\dot{\Theta}^*$ to MGDDF (\ref{eq32})-(\ref{eq34}). Moreover, with constant $\mathcal{N}>0$ such that \begin{equation} \bigg\|~ \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg) ~\bigg\|_2^2 \geq \mathcal{N}~\bigg\|~\begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix}~ \bigg\|_2^2, \end{equation} the exponential stability for computing MGDDF (\ref{eq32})-(\ref{eq34}) can be guaranteed. \end{theorem} \begin{proof} Firstly, define the following Lyapunov function candidate, i.e., \begin{equation} \mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg)= \bigg\|~\begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} ~\bigg\|_2^2 \geq0. \end{equation} Secondly, the time derivative of $\mathcal{V}(\cdot)$ along (\ref{equ.nn-2}) is \begin{equation} \frac{\text{d}\mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg)}{\text{d}t} \end{equation} \begin{equation} = \mathcal{H} \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg)^{\text{T}} \bigg(\mathcal{E}+ \begin{bmatrix} \mathcal{I} &\textit{\textbf{J}}\\ -\textit{\textbf{J}}^{\text{T}} &\textbf{0} \end{bmatrix}\bigg) \times \bigg\{ \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg)- \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix} \bigg\} \end{equation} \begin{equation} \leq-\mathcal{H}\bigg\|~ \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix} - \mathcal{P}_{\Omega}\bigg( \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}- \big(\begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \begin{bmatrix} \dot{\Theta}\\ \mathcal{K} \end{bmatrix}+ \begin{bmatrix} \textit{\textbf{c}}^\text{T}\Theta\\ -\dot{\Upsilon}-\wp(\Upsilon-\Im(\Theta)) \end{bmatrix}\big)\bigg) ~\bigg\|^2_2 - \mathcal{H}\bigg\|~ \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg) ~\bigg\|_2^2 \leq0. \end{equation} On the basis of Lyapunov theory, with positive-defined $\mathcal{V}$ and negative-dfined $\dot{\mathcal{V}}$, state vector $[\dot{\Theta}, \mathcal{K}]^{\text{T}}$ of (\ref{equ.nn-2}) is stable and converges to equilibrium point $[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}$ globally, in view that $\dot{\mathcal{V}}=0$ when $[\dot{\Theta}, \mathcal{K}]^{\text{T}}=[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}=0$. It follows that the first $2n$ elements of $[\dot{\Theta}^*, \mathcal{K}^*]^{\text{T}}$ constitute the optimal solution to MGDDF (\ref{eq32})-(\ref{eq34}). Also note that \begin{equation} \frac{\text{d}\mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg)}{\text{d}t} \leq - \mathcal{H} \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg)^{\text{T}} \bigg( \mathcal{N}\mathcal{E}+ \begin{bmatrix} \mathcal{I} &-\textit{\textbf{J}}^{\text{T}}\\ \textit{\textbf{J}} &\textbf{0} \end{bmatrix} \bigg)\cdot \bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} \bigg) \leq-\mathcal{S}\mathcal{V}\bigg( \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} \bigg) \end{equation} where convergence rate $\mathcal{S}=\mathcal{N}\mathcal{H}>0$. Therefore, with $\forall t\geq t_0$, we have $\mathcal{V}([\dot{\Theta}, \mathcal{K}]^{\text{T}})=O(e^{-\mathcal{S}(t-t_0)})$ such that \begin{equation} \bigg\|~ \begin{bmatrix} \ddot{\Theta}\\ \dot{\mathcal{K}} \end{bmatrix} - \begin{bmatrix} \ddot{\Theta}^*\\ \dot{\mathcal{K}}^* \end{bmatrix} ~\bigg\|_2^2 = O(e^{-\mathcal{S}(t-t_0)/2}). \label{eqn.nn-3} \end{equation} In reference to (\ref{eqn.nn-3}), we can draw the conclusion that the exponential computation speed of MGDDF (\ref{eq32})-(\ref{eq34}) can be achieved. The proof is thus completed. \end{proof} \section{Simulative Experiments} \begin{figure*} \centering \includegraphics[width=.75\textwidth]{structure.eps}\\ \caption{The skeleton structure of dual arms of the humanoid robot used in simulations.}\label{fig.structure} \end{figure*} In this section, the practicability of the proposed MGDDF scheme is verified by simulative experiments. The comparison between MGDDF and the traditional GDDF scheme is also provided. Specifically, the experiments are based on the dual arms of a humanoid robot, which contain 14 DOF (7 of each arm), and the skeleton structure is shown in Fig. \ref{fig.structure}. The execution task lasts for $18s$. In addition, the upper and lower bounds of the joint limit $6$, $7$, $13$ and $14$ are set as the same value, respectively. \subsection{Adjustment of GDDF Scheme} Set the parameters of the QP problem (\ref{eq32})-(\ref{eq34}) as follows: $N=1$, $\varrho=2$, $\kappa=0.85$, $\Theta_{gL}^-=[0, -54\pi/180,$ $-10.5\pi/180, 0, -131\pi/180, \pi/3, 55\pi/180]^\text{T}$ (rad), $\Theta_{gL}^+=[9\pi/180, 18\pi/180, 22.5\pi/180, \pi/2, 0, \pi/3,$ $55\pi/180]^\text{T}$ (rad), $\Theta_{gR}^-=[-9\pi/180, -18\pi/180, -22.5\pi$ $/180, \pi/2, -131\pi/180, \pi/3, -25\pi/36]^\text{T}$ (rad), and $\Theta_{gR}^+=$ $[0, 54\pi/180,$ $10.5\pi/180, \pi, 0, \pi/3, -25\pi/36]^\text{T}$ (rad). At first, to show the adjustment to the traditional GDDF scheme, the inequality (\ref{eq34}) of the QP problem (\ref{eq32})-(\ref{eq34}) is not applied directly. For the GDDF scheme, when the margin is not considered, the upper limit and lower limits would overlap and the result is shown in Fig. \ref{fig.compare adjustment}. Specifically, the black line stands for the joint limit and the green line stands for the limit with margins. From the figure we can see that the movement of the joint is constrained by the limit with margins. Because of the margins, $\Theta_{g}^-$ and $\Theta_{g}^+$ of joint $7$ is not the same, so we propose that when the limit with margins reaches the goal value, they would hold that value. After adjustment, the joint would not exceed the margins. Fig. \ref{fig.compare adjustment} (b) gives the result of this modification. \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.49\columnwidth]{FIG-4-a.eps}} \subfigure[]{\includegraphics[width=0.49\columnwidth]{FIG-4-b.eps}} \caption{Comparison between GDDF scheme with non-adjustment-margin and adjustment-margin. (a) Without adjustment. (b) With adjustment. }\label{fig.compare adjustment} \end{figure} We use the following equations to simplify, i.e., \begin{eqnarray} \Theta_{set}^+(t)=\Theta^++\frac{\Delta\Theta^+}{1+e^{-(t-\tau)/\varrho}}\\ \Theta_{set}^-(t)=\Theta^-+\frac{\Delta\Theta^-}{1+e^{-(t-\tau)/\varrho}}. \end{eqnarray} For joint $6$, $7$ and $13$, the upper limit and lower limit both $>0$, the following equations are introduced, i.e., $$ \kappa\tilde{\Theta}^+ =\left\{ \begin{aligned} &\kappa\Theta_{set}^+(t), && \kappa\tilde{\Theta}^+> \Theta_{g}^+\\ &\Theta_{g}^+, && \kappa\tilde{\Theta}^+ \leqslant \Theta_{g}^+ \end{aligned} \right. $$ $$ \kappa\tilde{\Theta}^- =\left\{ \begin{aligned} &(2-\kappa)\Theta_{set}^-(t), && \kappa\tilde{\Theta}^+< \Theta_{g}^-\\ &\Theta_{g}^-, && \kappa\tilde{\Theta}^-\geqslant \Theta_{g}^- \end{aligned} \right. $$ and function (\ref{fun18}) should be rewritten as $$ \tilde{\Theta}^+ =\left\{ \begin{aligned} &\Theta_{set}^+(t), && \tilde{\Theta}^+> \Theta_{g}^+/\kappa\\ &\Theta_{g}^+/\kappa, && \tilde{\Theta}^+ \leqslant \Theta_{g}^+/\kappa \end{aligned} \right. $$ $$ \tilde{\Theta}^- =\left\{ \begin{aligned} &\Theta_{set}^-(t), && \tilde{\Theta}^-< \Theta_{g}^-/(2-\kappa)\\ &\Theta_{g}^-/(2-\kappa), && \tilde{\Theta}^- \geqslant \Theta_{g}^-/(2-\kappa). \end{aligned} \right. $$ \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-5-a.eps}} \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-5-b.eps}} \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-5-c.eps}} \subfigure[]{\includegraphics[width=0.245\columnwidth]{FIG-5-d.eps}} \caption{Comparison between GDDF and MGDDF when $\varrho=2$, $N=2$. (a) Limit of joint $6$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin.}\label{fig.c2n2} \end{figure} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-6-a.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-6-b.eps}} \subfigure[]{\includegraphics[width=0.34\columnwidth]{FIG-6-c.eps}} \subfigure[]{\includegraphics[width=0.34\columnwidth]{FIG-6-d.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-6-e.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-6-f.eps}} \caption{Comparison between GDDF and MGDDF when $\varrho=2$, $N=3$. (a) Limit of joint $7$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin. (e) Limit of Joint $14$ with margin. (d) Limit of joint $14$ without margin.} \label{fig.c2n3} \end{figure} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-7-a.eps}} \subfigure[]{\includegraphics[width=0.325\columnwidth]{FIG-7-b.eps}} \subfigure[]{\includegraphics[width=0.34\columnwidth]{FIG-7-c.eps}} \subfigure[]{\includegraphics[width=0.33\columnwidth]{FIG-7-d.eps}} \subfigure[]{\includegraphics[width=0.33\columnwidth]{FIG-7-e.eps}} \subfigure[]{\includegraphics[width=0.33\columnwidth]{FIG-7-f.eps}} \caption{Comparison between GDDF and MGDDF when $\varrho=2$, $N=4$. (a) Limit of joint $6$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin. } \label{fig.c2n4} \end{figure} For joint $14$, the upper limit and lower limit both $<0$, hence $$ \tilde{\Theta}^+ =\left\{ \begin{aligned} &\Theta_{set}^+(t), && \tilde{\Theta}^+> \Theta_{g}^+/(2-\kappa)\\ &\Theta_{g}^+/(2-\kappa), && \tilde{\Theta}^+ \leqslant \Theta_{g}^+/(2-\kappa) \end{aligned} \right. $$ $$ \tilde{\Theta}^- =\left\{ \begin{aligned} &\Theta_{set}^-(t), && \tilde{\Theta}^-< \Theta_{g}^-/\kappa\\ &\Theta_{g}^-/\kappa, && \tilde{\Theta}^- \geqslant \Theta_{g}^-/\kappa. \end{aligned} \right. $$ \subsection{Comparison between GDDF and MGDDF} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-8-a.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-8-b.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-8-c.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-8-d.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-8-e.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-8-f.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-8-g.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-8-h.eps}} \caption{Comparison between GDDF and MGDDF when $\varrho=3$, $N=1$. (a) Limit of joint $6$ with margin. (b) Limit of joint $6$ without margin. (c) Limit of joint $7$ with margin. (d) Limit of joint $7$ without margin. (e) Limit of joint $13$ with margin. (f) Limit of joint $13$ without margin. (g) Limit of joint $14$ with margin. (h) Limit of joint $14$ without margin.}\label{fig.c3n1} \end{figure} In this part, experiments are made to compare the proposed MGDDF scheme with the traditional GDDF scheme. Joints $6$, $7$, $13$ and $14$ are the main research objets. Similar to before, $\Theta_{g}^+$ and $\Theta_{g}^-$ of joints $6$, $7$, $13$ and $14$ are set as the same values. The parameter $\varrho$ is set as $\varrho=2$ and $N$ is set as $N=2$. From Fig. \ref{fig.c2n2} we could see that when applying GDDF scheme, joint $6$ exceed the limit of margins, and it cannot exceed its real limit. The similar situation happens in the experiment of joint $7$. Now parameter $N$ changes from $2$ to $3$. Joints $6$, $7$ and $14$ exceed their limits again. From Fig. \ref{fig.c2n3} (a) (c) and (e) we could see that by containing the margins, the proposed MGDDF can successfully complete the task. Similar conclusion can be drew when parameters $\varrho=2$ and $N=4$ for joints $6$ and $7$ in Fig. \ref{fig.c2n4}, parameters $\varrho=3$ and $N=1$ for joints $6$, $7$, $13$ and $14$ in Fig. \ref {fig.c3n1}, and parameters $\varrho=4$ and $N=1$ for joints $7$ and $14$ in Fig. \ref {fig.c4n1}. \subsection{``Ball-catch'' Experiment} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-9-a.eps}} \subfigure[]{\includegraphics[width=0.251\columnwidth]{FIG-9-b.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-9-c.eps}} \subfigure[]{\includegraphics[width=0.241\columnwidth]{FIG-9-d.eps}} \caption{Comparison between GDDF and MGDDF when $\varrho=4$, $N=1$. (a) Limit of joint $7$ with margin. (b) Limit of joint $7$ without margin. (c) Limit of joint $14$ with margin. (d) Limit of joint $14$ without margin.} \label{fig.c4n1} \end{figure} \begin{figure}[tbp] \centering \subfigure[]{\includegraphics[width=0.49\columnwidth]{ball.eps}} \subfigure[]{\includegraphics[width=0.48\columnwidth]{ball-2.eps}} \caption{Motion trajectories of humanoid robot when applying to a ``ball-catch'' experiment. (a) Tracking trajectories of each joint. (b) Joint state of the dual arms.} \label{fig.ball} \end{figure} To validate the feasibility of the proposed method, a ``ball-catch'' experiment which was based on the 14 DOF humanoid is designed. For this experiment, the end-effector task is to move the ball up, left, down, and then back. Fig. \ref{fig.ball} demonstrates the motion trajectories and joint state of the dual arms of the humanoid robot in this experiment. The task can be completed and all the 14 joints maintain their joint limits successfully. All the simulative experiment results illustrated above verify the effectiveness of the proposed MGDDF method. \section{Conclusions} In this paper, the gesture-determined-dynamic function (GDDF) scheme is promoted and its deficiency is fixed. With consideration of three margins, a modified scheme named MGDDF is proposed for solving kinematic problems of dual arms of humanoid robots. Embed into a quadratic programming framework, the gesture of dual arms can be smoothly achieved by using MGDDF method, and the joints would not exceed their limits during the execution of tasks. Computer simulations verify the feasibility, accuracy and superiority of the proposed MGDDF method for solving motion planning and gesture determination of humanoid robots. \section*{Nomenclature} The full name of abbreviations proposed in this paper are listed as follows: \begin{eqnarray*} \begin{split} \textsc{GDDF} ~~~~~~~~~ &\textmd{Gesture-determined-dynamic function}.\\ \textsc{MGDDF} ~~~~~ &\textmd{Modified gesture-determined-dynamic function}.\\ \textsc{QP} ~~~~~~~~~~~~~~ \ &\textmd{Quadratic programming}.\\ \textsc{DOF} ~~~~~~~~~~~ \ &\textmd{Degrees-of-freedom}.\\ \textsc{MKE} ~~~~~~~~~~ \ &\textmd{Minimum-kinetic-energy}.\\ \textsc{RMP} ~~~~~~~~~~ \ &\textmd{Repetitive motion planning}.\\ \textsc{MVN} ~~~~~~~~~ \ &\textmd{Minimum-velocity-norm}.\\ \textsc{LVI} ~~~~~~~~~~~~~ \ &\textmd{Linear-variational-inequality}. \end{split} \end{eqnarray*}
{'timestamp': '2020-08-18T02:17:18', 'yymm': '2008', 'arxiv_id': '2008.06899', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06899'}
arxiv
\section{Introduction} Bitcoin is a decentralized crypto currency originally proposed by Satoshi Naka-moto in 2008 \cite{bitcoin2008}. Since then, it has attracted wide attention in the world both academically and commercially because of its soaring price and the characteristics of decentralization. Bitcoin realizes its decentralization by \textit{blockchain}, which is a global ledger maintained by distributed system. This ledger can record historical transactions and other information. One main difference between Bitcoin and most existing currencies is the way of currency issuance and the method of bookkeeping. Bitcoin is implemented on a P2P network and everyone is able to join or leave the network without any permission. The participants in generating new blocks are called \textit{miners}, and their tasks are to verify the legitimacy of undetermined transactions and pack those legal transactions into a block. In order to validate the block, every miner needs to work on a cryptographic puzzle, which needs large amount of computational resources (like electricity and hardware). To motivate the miners to generate new blocks, the first miner who solves the puzzle correctly, will get rewarded. Roughly speaking, the probability that a miner can propose a block successfully is proportional to her computational power among all miners. The above protocol of identifying the block generator is called \textit{proof of work} and the process of solving puzzles is called \textit{mining}. More detailed of Bitcoin system description can be referred to the Bitcoin white paper \cite{bitcoin2008} and wiki\footnote{\url{https://wikipedia.org/wiki/Bitcoin}}. To control the frequency of block generation, the difficulty of puzzles is adjusted dynamically in Bitcoin system, which is about every ten minutes in expectation. With the development of Bitcoin, the computational power in the system is extremely large nowadays. Thus, it is very difficult for a solo miner to propose a block successfully. This means the miner may spend several years to obtain (huge) rewards which is of course unacceptable. To pursuit stable reward, a lot of miners join in the \textit{mining pools} which are gatherings of individual computational powers \cite{Rosenfeld2011bwa}. Miners in the same mining pool work together on the proof of work protocol, thus a pool can obtain reward much more frequently compared to mining individually. After obtaining reward, the mining pool will distribute the reward among miners in this pool based on the computational power of each miner. For a solo miner, attending a mining pool cannot increase the expected reward, but the variance is improved significantly. Nowadays, there are more than 12 Bitcoin mining pools and more than 90\% of Bitcoin mining is done by those pools\footnote{Bitcoin hashrate distribution. \url{https://blockchain.info/pools}. Accessed June 14, 2019.}. However, it is shown in \cite{Eyal2015pbwa} that the permissionless mining pools have strong incentives to launch the {\em pool block withholding attacks (PBW attacks)} on each other: one strategic pool manager sends some of her miners to other pools and these miners pretend to work on the puzzles but actually do nothing. In Bitcoin or any decentralized system, the pool managers are not able to recognize such malicious miners, thus these miners can still obtain the reward from mining pool proportional to their computing powers. Eyal \cite{Eyal2015pbwa} proved that although infiltrating the other pools consumes some of her computational power, the reward from infiltrating miners may still increase the pool's total utility. PBW attack is also demonstrated in \cite{luu2015power} with a different reward function. Eyal \cite{Eyal2015pbwa} modeled the above scenario as {\em pool block withholding games (PBW games)} and showed that with any number of pools, no-pool-attacks is not a Nash equilibrium. When there are two pools, the situation faced by the two managers is similar to prisoner's dilemma, which is called {\em miner's dilemma}: in an equilibrium, both manages launch the PBW attack and accordingly earn less rewards compared to when they mine honestly. Alkalay-Houlihan and Shah \cite{AlkalayHoulihan2019aaai} further studied the miner's dilemma between two strategic mining pools and obtained the bound of the social loss due to noncooperation, i.e., price of anarchy. They showed that the pure Nash equilibrium always exists, and the pure price of anarchy is at most 3 in this game. They also conjectured the tight bound should be 2 and demonstrated this in some special cases. It is disappointing that launching PBW attacks to be always profitable for the pools, and would dramatically decrease the social welfare. Such bad news is derived from the inaction of the malicious Bitcoin pools. Actually, in both \cite{Eyal2015pbwa} and \cite{AlkalayHoulihan2019aaai}, the authors assume that all the rewards are proportionally distributed to the miners. Accordingly, a natural question to ask would be \begin{quote} \em Is there any other approach to reallocate the rewards such that PBW attacks can be avoided or discouraged. \end{quote} \subsection{Main Contributions} Briefly, we resolve the above question affirmatively by refining the PBW games and show that for any number of mining pools, no-pool-attacks is always a Nash equilibrium under a proper \textit{way to award the successful miner}. Moreover, with only two minority pools participating, no-pool-attacks is the unique Nash equilibrium. We summarize our contributions as follows. \begin{itemize} \item We refine the PBW game by allowing all pool managers to deduct (different) percentages of their rewards before they distribute the reward to the miners, where the deducted reward is used to award the successful miner. We call the refined model DPBW game. We believe such a new reward distribution rule in DPBW games is more realistic than the proportional way, as, intuitively, the former provides enough motivation for the miners to work hard on mining. Moreover, it should also be careful that the manager cannot deduct too much from the total reward since the more they deduct, the less incentives are left to the miners to join the pools. \item We prove that for arbitrary number of pools, no-pool-attacks is always a Nash equilibrium of DPBW games with reasonable deductions. Thus the price of stability (PoS) of DPBW games is 1. This is intriguing for the situations in which there is some authority that can influence the managers a bit and help them converge to the optimal solution that is also stable. \item Particularly, for two minority pools participating, the unique Nash equilibrium of DPBW games with reasonable deductions is no-pool-attacks. This result is more exciting for the special case: even without such authorities, every manager is automatically willing to not launch PBW attacks. \end{itemize} Thus in the present work, we improve the negative results proved in \cite{Eyal2015pbwa} and \cite{AlkalayHoulihan2019aaai} by designing a new way to allocate the reward to the miners and award the successful miner such that all the computing power will be used to mining. \subsection{Related Works} Recent years have seen a number of studies on security issues of blockchain, such as the selfish mining attack \cite{Eyal2014selfishmining}, the Eclipse attack \cite{Heilman2015129eclipse} and the distributed denial-of-service attack \cite{Johnson2014ddos}. A closely relevant attack to our study is the {\em Block Withholding Attack (BW attack)} which is first defined by Rosenfeld in \cite{Rosenfeld2011bwa}. In this attack, a miner who has found a legal block chooses not to submit it to the mining pool immediately but rather delays to submit or even directly abandons it. Many follow-up studies focus on the simulation and countermeasures of BW attacks. To resist BW attacks, Schrijvers et al. \cite{schrijvers2016incentive} designed a new incentive compatible reward function and showed proportional mining rewards are not incentive compatible. It was shown in \cite{Bag2016preventBWA} that by giving extra reward to a miner who actually finds the winning block on behalf of the pool, it is possible to discourage BW attacks. Tosh et al. \cite{Tosh2017security} modeled the BW attacks in a blockchain cloud and demonstrates that attacker's access to extra computational power could disrupt the honest mining operation. Very recently, Wu et al. \cite{WU2019Equilibrium} constructed a generalized model where two participants can choose to either cooperate with each other or employ a BW attack. They showed that increasing the information asymmetry by utilizing information conceal mechanisms could lower the occurrence of BW attacks. More studies in this line can be found in \cite{Bag2017,Mousavinejad2018detect,Haghighat2019}. The Pool Block Withholding Attack (PBW attack) is a variation of BW attacks, the difference is that the PBW attack is launched by a pool manager rather than a miner. Eyal \cite{Eyal2015pbwa} describes PBW attacks from the perspective of game theory in which the players are pool managers and the strategy of each manager is allocating some powers to launch the block withholding attack. Eyal also proves that with any number of pools, all pools mining honestly and not attacking each other is never a Nash equilibrium. Subsequently, \cite{AlkalayHoulihan2019aaai} follows Eyal's study on the case of two pools attacking each other. They show that this game always admits a pure Nash equilibrium, and its pure price of anarchy is at most 3. Finally, there are also many other game theoretic studies about Bitcoin and other crypto currencies. For example, \cite{babaioff2012bitcoin} studies how to incentivize the users to propagate each transaction in a tree network; \cite{carlsten2016instability} shows that with only transaction fees (and negligible block rewards), the miners have strong incentive to fork a block and generate a greater reward; \cite{lewenberg2015bitcoin} views Bitcoin from a cooperative game theoretic perspective and show under high transaction loads, it is difficult for pool managers to distribute rewards in a stable way; \cite{chen2019axiomatic} adopts an axiomatic approach to investigate how the reward should be distributed among the miners. \section{Model} In this section, we formally define the {\em Discouraging pool block withholding games (DPBW games)}. Similar with \cite{Eyal2015pbwa} and \cite{AlkalayHoulihan2019aaai}, it is assumed that each miner exactly joins one pool and is totally operated by that pool's manager. Thus the players in a DPBW game are the managers of $n$ mining pools, denoted by $N$. Let $m_i \in \mathbb{R}^{+}$ be the mining power of manager $i\in N$. Assume $m$ is the total mining power in the worldwide Bitcoin system and $m \ge \sum_{i \in N} m_i$. By $m > \sum_{i \in N} m_i$, we mean there are extra mining power outside of the studied pools $N$, due to any solo miners or inaccessible mining pools. In a DPBW game, each player $i$ might only allocate $\alpha_{i}$ fraction of the total reward to her miners proportionally to their mining power and award the left to the successful miner. She might also use a fraction of its mining power to infiltrate another pool~$j$. Such mining power does not actually work for pool $j$, but gets a fraction of the total reward from $j$. It is assumed that the mining powers are continuous and can be arbitrarily divided. In this work, we study how to select these $\alpha_{i}$'s for the players so that all of them do not want to infiltrate others. Thus player $i$'s strategy space is all possible ${\bf x}_{i} = (x_{ij})_{j\in N\backslash\{i\}}$ such that $\sum_{j=1}^{n} x_{ij} \le m_{i}$ and $x_{ij} \ge 0$ for all $j\in N\backslash\{i\}$. Each $x_{ij}$ with $j\neq i$ represents the amount of mining power that $i$ wants to infiltrate pool $j$. Denote by ${\bf x} = ({\bf x}_{1}, \cdots, {\bf x}_{n})$ a full strategy profile. To make us focus on the pool block withholding behaviors, we assume the reward for each block is fixed, thus the selection of the transactions does not matter. Given a strategy profile ${\bf x}$, the players' utilities are defined as follows: Assume each player $i$ first gets a total reward of $r_{i}({\bf x})$ by mining and infiltrating other pools. Then she deducts $(1-\alpha_{i})$ fraction from $r_{i}({\bf x})$ used for award and obviously only her honest miners can get this. The remaining reward $\alpha_{i}r_{i}({\bf x})$ is proportionally allocated to all her miners including both her honest and the infiltrated ones from the other pools. Thus the pool's true utility is the total reward allocated to her honest miners. More precisely, each player $i$'s reward $r_{i}({\bf x})$ consists of two parts: {\em direct reward} and {\em infiltrating reward}. Since every player $i$ only uses $m_{i} - \sum_{l \neq i} x_{il}$ mining power for honest mining, player $i$'s direct reward is proportional to the fraction of the honest mining power contributed by her pool, denoted by $$DR_{i}({\bf x}) = \frac{m_{i} - \sum_{l \neq i} x_{il}}{m - \sum_{j=1}^{n} \sum_{l \neq j} x_{jl}};$$ since the pools cannot distinguish infiltrating miners from honest miners, player $i$'s infiltrating reward from every other pool $j$ is proportional to the fraction of her infiltrating mining power to $j$, denoted by $$IR_{i}({\bf x}) = \sum_{j\in N\setminus\{i\}} \frac{\alpha_{j} \cdot r_{j}({\bf x}) \cdot x_{i}} {m_{j} + \sum_{l\neq j}x_{lj}}.$$ Note that both the direct reward and the infiltrating reward will be allocated to all miners. Accordingly, player $i$'s total reward is $$r_{i}({\bf x}) = DR_{i}({\bf x}) + IR_{i}({\bf x}),$$ and her utility is \begin{equation}\label{eq:utility} U_{i}({\bf x}) = (1 - \alpha_{i} + \frac{m_{i}\alpha_{i}}{m_{i} + \sum_{j\neq i}x_{ji}}) r_{i}({\bf x}). \end{equation} For any vector ${\bf v} = (v_{1},\ldots, v_{n})$ and a particular $1 \le i \le n$, denote by ${\bf v}_{-i}$ the resulting vector of ${\bf v}$ when element $v_{i}$ is omitted. A strategy profile ${\bf x}$ is called a Nash equilibrium if for every player $i$ and every possible strategy ${\bf x}'_{i}$, $$ U_{i}({\bf x}) \ge U_{i}({\bf x}'_{i}, {\bf x}_{-i}). $$ In a non-cooperative game, the {\em price of anarchy} (PoA) is defined as the ratio between the optimal social welfare and the worst social welfare of any possible Nash equilibria; while the {\em price of stability} (PoS) is defined as the ratio between the optimal social welfare and the best social welfare of any possible Nash equilibria. In DPBW games, the social welfare is defined as the total mining power that is used to honest mining. \section{The PoS of DPBW Games is 1} In this section, we prove that for most reasonable $\alpha_{i}$'s, no-pool-attacks is always a Nash equilibrium of DPBW games for any number of mining pools, that is, the PoS of DPBW games is always 1. Formally, \begin{theorem}\label{thm:anypools} Strategy profile $({\bf 0}, \ldots, {\bf 0})$ is a Nash equilibrium for any DPBW game if $\forall i, \alpha_{i} \leq 1-\frac{m_{\max}}{m}$, where $m_{\max}=\max_{i\in N} m_i$. \end{theorem} \begin{proof} Let ${\bf x}=({\bf x}_{1}, \ldots, {\bf x}_{n})$ be the strategy profile such that $x_{ij} = 0$ for any $i\in N$ and $j\in N\setminus\{i\}$. Note that, in Equation~\eqref{eq:utility}, the coefficient before $r_{i}({\bf x})$ is always 0 as $x_{ji} = 0$ for all $j\neq i$. Thus, in the rest proof we show $r_i({\bf x'}_i, {\bf x}_{-i})\ge r_i({\bf x})$ instead of $U_i({\bf x'}_i, {\bf x}_{-i})\ge U_i({\bf x}_i)$, where ${\bf x}'_i$ is any feasible strategy of player $i$. Arbitrarily fix a player $i$ and it is easy to see $r_i({\bf x}) = \frac{m_i}{m}$. To prove the theorem, it suffices to show that for any feasible strategy ${\bf x}_{i}'$ with all $j\neq i$ and $x'_{ij} \ge 0$, $$r_i({\bf x}'_{i}, {\bf x}_{-i}) \le \frac{m_i}{m}.$$ Denote $i$'s total infiltrating mining power under strategy ${\bf x}'_{i}$ by $x_{i}' = \sum_{j\neq i}x'_{ij}$. Then \begin{eqnarray*} r_i({\bf x}'_{i}, {\bf x}_{-i}) &=& \frac{m_i-x'_i}{m-x'_i}+\sum_{j\in N\setminus\{i\}}\frac{\alpha_jx'_{ij}m_j}{(m-x'_i)(m_j+x'_{ij})}\\ &=& \frac{m_i}{m}\left(\frac{m}{m_i}\cdot\frac{m_i-x'_i}{m-x'_i} +\sum_{j\in N\setminus\{i\}}\frac{m}{m_i}\cdot\frac{\alpha_jx'_{ij}m_j}{(m-x'_i)(m_j+x'_{ij})}\right)\\ &=& \frac{m_i}{m}\left(1+\frac{x'_i}{m_i}\cdot\frac{m_i-m}{m-x'_i} +\sum_{j\in N\setminus\{i\}}\frac{m}{m_i}\cdot\frac{\alpha_jx'_{ij}m_j}{(m-x'_i)(m_j+x'_{ij})}\right)\\ &=& \frac{m_i}{m}\left(1+\sum_{j\in N\setminus\{i\}}\frac{x'_{ij}}{m_i}\cdot\frac{m_i-m}{m-x'_i} +\sum_{j\in N\setminus\{i\}}\frac{m}{m_i}\cdot\frac{\alpha_jx'_{ij}m_j}{(m-x'_i)(m_j+x'_{ij})}\right). \end{eqnarray*} Now we claim the following inequality: \begin{equation}\label{eq:proof_of_thm1_1} \frac{x'_{ij}}{m_i}\cdot\frac{m_i-m}{m-x'_i}+ \frac{m}{m_i}\cdot\frac{\alpha_jx'_{ij}m_j}{(m-x'_i)(m_j+x'_{ij})}\leq 0. \end{equation} Note that Inequality (\ref{eq:proof_of_thm1_1}) implies $r_i(\textbf{x}'_{i}, \textbf{x}_{-i}) \leq \frac{m_i}{m}=r_i(\textbf{x})$, which completes the proof of Theorem~\ref{thm:anypools}. The remaining is dedicated to show the correctness of Inequality (\ref{eq:proof_of_thm1_1}). By rearranging the terms, the lefthand of Inequality (\ref{eq:proof_of_thm1_1}) equals $$ \frac{x'_{ij}[(m_i-m)(m_j+x'_{ij})+mm_j\alpha_{j}]}{m_i(m-x'_i)(m_j+x'_{ij})}. $$ As the denominator is always positive, we only need to consider the sign of its numerator: \begin{eqnarray*} (m_i-m)(m_j+x'_{ij})+mm_j\alpha_{j} &\leq& (m_i-m)m_j+mm_j\alpha_{j}\\ &\leq& (m_i-m)m_j+mm_j(1-\frac{m_{max}}{m})\\ &=&m_im_j-m_{max}m_j\leq 0, \end{eqnarray*} where the first inequality is because $x'_{ij} \ge 0$ and the second is because $\alpha_{i} \leq 1-\frac{m_{max}}{m}$. \end{proof} \paragraph{Remark.} Note that $\frac{m_{\max}}{m}$ fraction of the reward cannot be too large for any dencentralized system, thus we believe the requirement of $\alpha_{i} \leq 1-\frac{m_{\max}}{m}$ in Theorem~\ref{thm:anypools} is a reasonable tradeoff between complementing the maintenance of a pool and incentivizing the miners to join it. \section{The Uniqueness of Nash equilibrium for Two-Pool Case} In this section, we study a special case of the DPBW game when only two pools are included, which is exactly the same setting with the previous work \cite{AlkalayHoulihan2019aaai}. However, as will be proved, in PBWA+ game, it is possible for the pool managers to deduct a small fraction from the reward, so that no-pool-attacks is a unique Nash equilibrium. \begin{theorem} \label{thm:2pools:unique} For PBWA+ Game with two players, by setting $\alpha_1 \le 1-\frac{m_2}{m}$, $\alpha_2 \le 1-\frac{m_1}{m}$ and $m > 3(m_1 + m_2)$, the game has a unique Nash equilibrium where both players do not infiltrate the other pool. \end{theorem} We believe the requirement of $m > 3(m_1 + m_2)$ in the theorem is reasonable as the statistic website\footnote{\url{https://btc.com/stats/pool?pool_mode=month}} shows that the largest two pools have roughly a third of the total computational power. \subsection{Notations and Proof Ideas of Theorem \ref{thm:2pools:unique}} Before we prove Theorem \ref{thm:2pools:unique}, we first simplify our notions to ease our representation. Since there are only two players, we simplify our notions as follows. Let $(x_{1}, x_{2})$ be a strategy profile, where $x_i \in [0, m_{i}]$ means how much player $i$ infiltrates player $j = 3-i$. Thus each player $i$'s direct reward $r_{i}(x_{1}, x_{2})$ is $$DR_{i}(x_{1}, x_{2})=\frac{m_{i} - x_{i}}{m - x_1 - x_2};$$ her total reward is \begin{eqnarray*} r_{i}(x_{1}, x_{2}) & = & R_{i}(x_{1}, x_{2}) + \frac{\alpha_{j} r_{j}(x_1, x_2) x_{i}} {m_{j} + x_{i}} = \frac{m_{i} - x_{i}}{m - x_1 - x_2} + \frac{\alpha_{j} r_{j}(x_1, x_2) x_{i}} {m_{j} + x_{i}}; \end{eqnarray*} and her utility is $$ U_{i}(x_{1}, x_{2}) = (1 - \alpha_{i} + \frac{m_{i}\alpha_{i}}{m_{i} + x_{j}}) r_{i}(x_{1}, x_{2}). $$ Here note that in $U_{i}(x_{1}, x_{2})$, the first coefficient $1 - \alpha_{i} + \frac{m_{i}\alpha_{i}}{m_{i} + x_{j}}$ only depends on $x_{j}$, thus when we analyze player $i$'s utility gain by unilateral deviation, without loss of generality, we just ignore this coefficient and only consider her total reward $r_{i}(x_{1}, x_{2})$. Solving the reward system of equations in $r_{i}(x_{1}, x_{2})$ for $i=1,2$, we get the closed forms for the reward functions: \begin{eqnarray*} & r_{1}(x_{1}, x_{2}) = \dfrac{(m_1 + x_2) \left[(m_1 - x_1)(m_2 + x_1) + \alpha_2 x_1 (m_2 - x_2) \right]} {(m - x_1 - x_2) \left[(m_1 + x_2)(m_2 + x_1) - \alpha_1 \alpha_2 x_1 x_2 \right]} \end{eqnarray*} and \begin{eqnarray*} & r_{2}(x_{1}, x_{2}) = \dfrac{(m_2 + x_1) \left[(m_2 - x_2)(m_1 + x_2) + \alpha_1 x_2 (m_1 - x_1) \right]} {(m - x_2 - x_1) \left[(m_2 + x_1)(m_1 + x_2) - \alpha_1 \alpha_2 x_1 x_2 \right]}. \end{eqnarray*} Let $x_i+ \Delta x_i$ be player $i$'s deviation, where $\Delta x_i \in [-x_i, m_i - x_i]$. Denote by $$ f_1(\Delta x_1) = r_1(x_1+ \Delta x_1, x_2) - r_1(x_1, x_2)$$ and $$ f_2(\Delta x_2) = r_2(x_1, x_2 + \Delta x_2) - r_2(x_1, x_2)$$ the reward gain by unilateral deviation. By definition, the necessary and sufficient condition for strategy profile $(x_1, x_2)$ to be a Nash equilibrium is for any $\Delta x_i \in [-x_i, m_i - x_i]$, $$ \begin{array}{ll} \left\{ \begin{array}{ll} f_1(\Delta x_1) \leq 0 \\ f_2(\Delta x_2) \leq 0. \\ \end{array} \right. \end{array} $$ Thus the problem of finding all possible Nash equilibria becomes finding all such $(x_1, x_2)$ strategy profiles. Since players 1 and 2 are symmetric, in the following, without loss of generality, we often use player 1 for illustration. The formula of $f_1(\Delta x_1)$ can be simplified as a quadratic function of $\Delta x_1$: \begin{eqnarray} &f_1(\Delta x_1) = A_1(x_1, x_2) (\Delta x_1)^2 + B_1(x_1, x_2) \Delta x_1 + C_1(x_1, x_2), \nonumber \end{eqnarray} where the formulas of $A_1(x_1, x_2)$, $B_1(x_1, x_2)$ and $C_1(x_1, x_2)$ are shown in Table~\ref{table:eq:ABC}. \begin{table*}[h] \begin{center} \begin{eqnarray*} A_1(x_1, x_2) & = &- (m_1 + x_2) + r_1(x_1, x_2) (m_1 + x_2 - \alpha_1 \alpha_2 x_2) \\ B_1(x_1, x_2) & = &(m_1 + x_2) \left[m_1 - m_2 - 2x_1 + \alpha_2(m_2 - x_2) \right] \\ &&+ \dfrac{(m_1 + m_2) \left[(m_1 - x_1)(m_2 + x_1) + \alpha_2 x_1 (m_2 - x_2) \right]}{m - x_1 - x_2} \\ & & + \dfrac{(m_1 + x_2 - \alpha_1 \alpha_2 x_2) (m_1 + x_2) \left[(m_1 - x_1)(m_2 + x_1) + \alpha_2 x_2 (m_2 - x_2)) \right]} {(m_1 + x_2) (m_2 + x_1) - \alpha_1 \alpha_2 x_1 x_2},\\ C_1(x_1, x_2) & = & 0. \end{eqnarray*} \end{center} \caption{The formulas of $A_1(x_1, x_2)$, $B_1(x_1, x_2)$ and $C_1(x_1, x_2)$.} \label{table:eq:ABC} \end{table*}% Note that since $r_1(x_1, x_2) \leq 1$, $A_1(x_1, x_2) \le 0$. Thus, for any strategy profile $(x_1, x_2)$, in order to make $f_{1}(\Delta x_1) \le 0$ for any $\Delta x_1 \in [-x_1, m_1 - x_1]$, there are three possible cases, as shown in Figures \ref{figure:strategy:x1=0}, \ref{figure:strategy:0<x1<m1} and \ref{figure:strategy:x1=m1}: \begin{description} \item[Case 1. ] $x_1 = 0$ and $B_1(x_1, x_2) \le 0$; \item[Case 2. ] $0 < x_1 < m_1$ and $B_1(x_1, x_2) = 0$; and \item[Case 3. ] $x_1 = m_1$ and $B_{1}(x_1, x_2) \ge 0$. \end{description} Symmetrically, we have all the corresponding definitions of $f_2(\Delta x_2)$, $A_2(x_1, x_2)$, $B_2(x_1, x_2)$ and $C_2(x_1, x_2)$ for player~2. Therefore, combining with players 1's and 2's strategies, we have nine kinds of possible Nash equilibria. By Theorem~\ref{thm:anypools}, we already know that $(0,0)$ is a Nash equilibrium. In the following, we will show that $(0,0)$ is actually the only possible Nash equilibrium for among the nine situations. Thus in any DPBW game with two players, both the PoA and the PoS are 1. \begin{figure}[ht] \begin{subfigure}{0.5\linewidth} \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-3.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(2.3,.75){$\Delta x_1$} \put(0,0){\vector(0,1){3.2}} \put(1.2,3){\makebox(0,0){$f_1(\Delta x_1)$}} \multiput(-1,0)(0, 0.4){8}{\line(0,1){0.2}} \qbezier(-1, 2)(0, 2) (1, 0) \qbezier(-1, 2)(-2, 2) (-3, 0) \end{picture} \caption{$x_1 = 0$, $B_1(x_1, x_2) \le 0$.} \label{figure:strategy:x1=0} \end{subfigure}% \begin{subfigure}{0.5\linewidth} \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-3.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(2.3,1.75){$\Delta x_1$} \put(0,0){\vector(0,1){3.2}} \put(-1.2,3){\makebox(0,0){$f_1(\Delta x_1)$}} \qbezier(1, 2)(2, 2) (3, 0) \qbezier(1, 2)(0, 2) (-1, 0) \multiput(1,0)(0, 0.4){8}{\line(0,1){0.2}} \end{picture} \caption{$x_1 = m_1$, $B_{1}(x_1, x_2) \ge 0$.} \label{figure:strategy:x1=m1} \end{subfigure}% \newline \vspace{0.4cm} \begin{subfigure}{1\linewidth} \centering \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-2.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(3.1,1.45){$\Delta x_1$} \put(0,0){\vector(0,1){3.2}} \put(1.2,3){\makebox(0,0){$f_1(\Delta x_1)$}} \qbezier(0, 1.5)(1, 1.5) (2, 0) \qbezier(0, 1.5)(-1, 1.5) (-2, 0) \end{picture} \caption{$0 < x_1 < m_1$, $B_1(x_1, x_2) = 0$.} \label{figure:strategy:0<x1<m1} \end{subfigure} \caption{Three possible strategies for player $1$} \label{figure:strategy} \end{figure} \subsection{Proof of Theorem \ref{thm:2pools:unique}} In the remaining of this section, we prove Theorem~\ref{thm:2pools:unique} by showing that all the eight situations, except $(0, 0)$, are not possible to be Nash equilibria. \subsection{Case 2 + Case 2: $B_1(x_1, x_2) = B_2(x_1, x_2) = 0$} To simplify our analysis, we first multiply $B_1(x_1, x_2)$ by $$\dfrac{(m - x_1 - x_2)\left[(m_1 + m_2)(m_2 + m_1) -\alpha_1 \alpha_2 x_1 x_2) \right]}{m_1 + x_2}$$ to eliminate the denominator, denoting the resulting polynomial by $Q_1(x_1, x_2)$. By rearranging every monomials, $Q_1(x_1, x_2)$ can be denoted as a quadratic function of $x_{1}$: $$ Q_1(x_1, x_2) = a_1(x_2) x_1^2 + b_1(x_2) x_1 + c_1(x_2), $$ where $a_1(x_2)$, $b_1(x_2)$ and $c_1(x_2)$ are independent of $x_{1}$ and their formulas are shown in Table~\ref{table:eq:abcsmall}. Similarly, we also have all the corresponding definitions of $Q_2(x_1, x_2), a_2(x_1), b_2(x_1)$, and $c_2(x_1)$ for player 2. \begin{table*}[h] \begin{center} \begin{eqnarray*} a_1(x_2)& = &\left(-\alpha_1 \alpha_2^2 m_2+\alpha_1 \alpha_2 m-\alpha_1 \alpha_2 m_1-\alpha_2 m_1+\alpha_1 \alpha_2 m_2+\alpha_2 m_2-m+2 m_1\right)x_2 \\ &&+\left(\alpha_1 \alpha_2^2-\alpha_1 \alpha_2-\alpha_2+1\right) x_2^2+\alpha_2 m_2 m_1+m_1^2-m m_1 ,\\ b_1(x_2) & = & -2m m_1 m_2 + 2 m_1^2 m_2 + (-2 m m_2 + 4 m_1 m_2 - 2 \alpha_1 \alpha_2 m_1 m_2) x_2 + 2 m_2 x_2^2 ,\\ c_1(x_2) & = & \alpha_2 m_2 x_2^3 +(-m\alpha_2 m_2 + \alpha_2 m_1 m_2 - \alpha_1 \alpha_2 m_1 m_2 + m_2^2 - \alpha_2 m_2^2) x_2^2 \\ &&+(-mm_1m_2^2 + m\alpha_2m_1m_2^2 + m_1m_2^2) \\ &&+(-m\alpha_2m_1m_2 + m\alpha_1\alpha_2m_1m_2 - m m_2^2 + m\alpha_2m_2^2 + 2 m_1m_2^2 - \alpha_2m_1m_2^2) x_2. \end{eqnarray*} \caption{The formulas of $a_1(x_1, x_2)$, $b_1(x_1, x_2)$ and $c_1(x_1, x_2)$.} \label{table:eq:abcsmall} \end{center} \end{table*} To show the impossibility of Case 1, it suffices to prove the following lemma. \begin{lemma}\label{lem:q1=q2=0} For any strategy profile $(x_1, x_2)$, $Q_1(x_1, x_2)$ and $Q_2(x_1, x_2)$ cannot be 0 simultaneously. \end{lemma} Before we prove Lemma \ref{lem:q1=q2=0}, we first prove the following claims (Claim \ref{claim:Q_1:c_1}, Claim \ref{claim:Q_1:b1} and Claim \ref{claim:Q_1:a1<0}). \begin{claim} \label{claim:Q_1:c_1} $c_1(x_2) \le 0$ for any $x_2\in [0, m_2]$. \end{claim} \begin{proof} To prove Claim \ref{claim:Q_1:c_1}, We first show the following facts: \begin{itemize} \item $c_1(0) \le 0$; \item $c_1(m_2) < 0$; \item $c_1(x_2)$ achieves its local maximal value at some $y<0$. \end{itemize} If the above three facts setting up, the curve of $c_1(x_2)$ can be shown in Figure \ref{figure:c1}, and $c_1(y) < 0$ for any $y\in [0, m_2]$ (the red part), Combing the three facts, the curve of $c_1(x_2)$ can be shown in Figure \ref{figure:c1}, and $c_1(x_2) < 0$ for any $x_2\in [0, m_2]$ (the red part), which completes the proof of the claim. \begin{figure}[htbp] \begin{center} \setlength{\unitlength}{0.6cm} \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-2.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(3.1,1.45){$x_2$} \put(0,0){\vector(0,1){3.2}} \put(-0.8,3.3){\makebox(0,0){$c_1(y)$}} {\color{red}\qbezier(0, 0.7)(0.9, -1) (2, 1.5)} \qbezier(2, 1.5)(2.15,1.8) (2.5, 2.8) \qbezier(0, 0.7)(-1.5, 4) (-2.8, 0.2) \multiput(-1.35,0)(0, 0.4){8}{\line(0,1){0.2}} \multiput(0.6,0)(0, 0.4){8}{\line(0,1){0.2}} \end{picture} \caption{$c_1(x_2)$.} \label{figure:c1} \end{center} \end{figure} Now we prove these facts one by one. To see the first fact, observe that when $\alpha_2 \le 1- \frac{m_1}{m}$, \[ c_1(0) = (\alpha_2 - 1) m m_1 m_2^2 + m_1^2 m_2^2 \le -\frac{m_1}{m} m m_1 m_2^2 + m_1^2 m_2^2 \le 0. \] To see the second fact, we note that \begin{eqnarray*} \frac{c_1(m_2)}{m_2^2} & = & m_1^2 -m m_2 +m_2^2 -m m_1 + \alpha_1 \alpha_2 m m_1 - \alpha_1 \alpha_2 m_1 m_2 + 2 m_1 m_2\\ & = & m_1^2 + m_2^2 - m m_2 + (\alpha_1 \alpha_2 - 1)mm_1 + (2 - \alpha_1 \alpha_2)m_1m_2\\ & < & m_1^2 + m_2^2 - m m_2 + (\alpha_2 - 1) m m_1 + 2 m_1 m_2 \\ & \le & m_1^2 + m_2^2 - 2 m_1 m_2 - m_2^2 - m_1^2 + 2 m_1 m_2 \\ &=& 0, \end{eqnarray*} where the last inequality is because $m \ge 2(m_1 + m_2)$ and $\alpha_2 - 1 \le - \frac{m_1}{m}$. To prove the third fact, we first compute the derivative of $c_1(x_2)$, \begin{eqnarray*} c'_1(x_2) & = & (3 \alpha_2 m_2) x_2^2 - 2( \alpha_2 m m_2 - \alpha_2 m_1 m_2 + \alpha_1 \alpha_2 m_1 m_2 - m_2^2 + \alpha_2 m_2^2) x_2 \\ && -\alpha_2 m m_1 m_2 + \alpha_1 \alpha_2 m_1 m_2 - m m_2^2 + \alpha_2 m m_2^2 + 2 m_1 m_2^2 - \alpha_2 m_1 m_2^2, \end{eqnarray*} which is a quadratic function of $x_2$. Combing the previous two facts and the property that $3 \alpha_2 m_2 > 0$, to show the third fact, it suffices to show the ``constant term'' of $c'_1(x_2)$ is smaller than 0. This sufficient condition can be proved by the following derivation. \begin{eqnarray*} & & - \alpha_2 m m_1 m_2 + \alpha_1 \alpha_2 m_1 m_2 - m m_2^2 + \alpha_2 m m_2^2 + 2 m_1 m_2^2 - \alpha_2 m_1 m_2^2\\ && = - \alpha_2 m m_1 m_2 (1 - \alpha_1) - m m_2^2 (1 - \alpha_2) + m_1 m_2^2 (2 - \alpha_2) \\ && \le -\alpha_2 m_1 m_2^2 - m_1 m_2^2 + m_1 m_2^2 (2 - \alpha_2) \\ && = m_1 m_2 (-\alpha_2 - 1 + 2 - \alpha_2) = m_1 m_2 (1 - 2 \alpha_2) < 0. \end{eqnarray*} Again, the first inequality is because $1 - \alpha_1 \ge \frac{m_2}{m}$ and $1 - \alpha_2 \ge \frac{m_1}{m}$; and the second is because $\alpha_i > \frac{1}{2}$. \end{proof} \begin{claim} \label{claim:Q_1:b1} $b_1(x_2) < 0$ for any $x_2 \in [0, m_2]$. \end{claim} \begin{proof} As $m \geq 3(m_1 + m_2)$, the claim easily follows by the following inequalities. \begin{eqnarray*} b_1(x_2) & = & -2m m_1 m_2 + 2 m_1^2 m_2 + 2 m_2 x_2^2 + (-2 m m_2 + 4 m_1 m_2 - 2 \alpha_1 \alpha_2 m_1 m_2) x_2 \\ &<& -2m_1^2 m_2 + 2 m_1^2 m_2 + 2 m_2 x_2^2 + (-2 (2(m_1+x_2)) m_2 + 4 m_1 m_2 ) x_2 < 0. \end{eqnarray*} \end{proof} \begin{claim} \label{claim:Q_1:a1<0} (1) Given any $0 < x_2 < m_2$ such that $a_1(x_2) \le 0$, then $Q_1(x_1, x_2) \neq 0$ for all $0 < x_1 < m_1$; (2) given any $0 < x_1 < m_1$ such that $a_2(x_1) \le 0$, then $Q_2(x_1, x_2) \neq 0$ for all $0 < x_2 < m_2$. \end{claim} \begin{proof} Since players 1 and 2 are symmetric, we only prove for player 1. If $a_1(x_2)=0$, then the curve of $Q(x_1, x_2)$ (a quadratic function of $x_1$) will degenerate to a line (see Figure~\ref{figure:a1=0}). Since its slope $b_1(x_2)$ is negative and y-intercept is non-positive, $Q_1(x_1, x_2)$ cannot be $0$ for any $x_1>0$. \begin{figure}[ht] \begin{subfigure}{0.5\linewidth} \setlength{\unitlength}{0.6cm} \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-3.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(3.1,1.45){$x_1$} \put(0,0){\vector(0,1){3.2}} \put(1.5,3){\makebox(0,0){$Q_1(x_1, x_2)$}} \put(0,1.3){\line(-2,1){2}} {\color{red}\put(0,1.3){\line(2,-1){2}}} \end{picture} \caption{$a_1(x_2)=0$} \label{figure:a1=0} \end{subfigure}% \begin{subfigure}{0.5\linewidth} \setlength{\unitlength}{0.6cm} \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-3.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(3.1,1.45){$x_1$} \put(0,0){\vector(0,1){3.2}} \put(1.5,3){\makebox(0,0){$Q_1(x_1, x_2)$}} \qbezier(-2.8, 0.5)(-1.2, 3.8) (0, 1.15) {\color{red} \qbezier(0,1.15)(0.18, 0.75) (0.4, 0.3)} \end{picture} \caption{$a_1(x_2)<0$} \label{figure:a1<0} \end{subfigure}% \caption{$Q_1$: The case when $a_1(x_{2}) \le 0$.} \label{figure:a1<=0} \end{figure} As $b_1(x_2) < 0$ and $a_1(x_2) < 0$, $$-\dfrac{b_1(x_2)}{2a_1(x_2)} < 0.$$ Combing with the result $c_1(x_2)\leq 0$ for any $x_2\in[0,m_2]$ in Claim \ref{claim:Q_1:c_1}, the curve of $Q_1$ (a quadratic function of $x_{1}$) can only be the case shown in Figure~\ref{figure:a1<0}. Accordingly, $Q_1(x_1, x_2) < 0$ for all $0 < x_1 < m_1$ (the red part). \end{proof} Having the above three Claims, we are ready to show the proof of Lemma~\ref{lem:q1=q2=0}. \subsubsection{Proof of Lemma \ref{lem:q1=q2=0}.} We prove by contradiction. If there is a strategy profile $(x_1, x_2)$, $0 < x_1 < m_1$ and $0 < x_2 < m_2$, such that $Q_1(x_1, x_2) = Q_2(x_1, x_2) = 0$, by Claim \ref{claim:Q_1:a1<0}, it must be the case that (shown in Figure \ref{figure:a1>0}) \begin{enumerate} \item $a_1(x_2) > 0$ and $Q_1(m_1, x_2) > 0$; and \item $a_2(x_1) > 0$ and $Q_2(x_1, m_2) > 0$. \end{enumerate} \begin{figure}[htbp] \begin{center} \setlength{\unitlength}{0.6cm} \thicklines \setlength{\unitlength}{0.6cm} \begin{picture}(4.3,3.6)(-2.5,-0.25) \put(-3,1.5){\vector(1,0){6}} \put(3.1,1.45){$x_i$} \put(0,0){\vector(0,1){3.2}} \put(0.1,3.5){\makebox(0,0){$Q_i(x_i, x_{3-i})$}} \qbezier(-2, 3)(0.25, -2.5) (2.5, 3) \qbezier(2, 3)(-0.25, -2.5) (-2.5, 3) \end{picture} \caption{$Q_i$: if $a_i(x_{3-i}) \ge 0$.} \label{figure:a1>0} \end{center} \end{figure} Note that \begin{eqnarray} &&Q_1(m_1, x_2) = \nonumber\\ && -\alpha_2 m_1 (m - m_1 - x_2) (m_2 - x_2)(m_1 + x_2 - \alpha_1 \alpha_2 x_2) \label{eq:q1:1} \\ && + (-m_1 - m_2 + \alpha_2 (m_2 - x_2)) (m - m_1 - x_2) \nonumber \\ && ~~~\cdot ( - \alpha_1 \alpha_2 m_1 x_2 + (m_1 + m_2) (m_1 + x_2)) \label{eq:q1:2} \\ && + \alpha_2 m_1 (m_2 - x_2) (-\alpha_1 \alpha_2 m_1 x_2 + (m_1 + m_2) (m_1 + x_2)). \label{eq:q1:3} \end{eqnarray} Let $\bar{Q}_1 (x_2) = \frac{(\ref{eq:q1:1}) + (\ref{eq:q1:3})}{\alpha_2m_1(m_2-x_2)}$, then $\bar{Q}_1 (x_2) > 0$ since (\ref{eq:q1:2}) is always negative and $\alpha_2m_1(m_2-x_2)$ is positive. Thus, \begin{eqnarray*} \bar{Q}_1(x_2) & = & 2m_1^2 + x_2 (-m + m_2 + \alpha_1 \alpha_2 (m - x_2) + x_2) \\ && + m_1 (-m + m_2 + (3 - 2 \alpha_1 \alpha_2) x_2). \end{eqnarray*} We assume $m=\ell(m_1 + m_2)$ for some $\ell\geq 3$, thus \begin{eqnarray*} \bar{Q}_1(m_2) & = & (2 - \alpha) m_1^2 + (2- \alpha - \alpha_1 \alpha_2 + \alpha \alpha_1 \alpha_2) m_2^2 \\ && + (4 - 2 \ell + 2 \alpha_1 \alpha_2(-2 + \ell)) m_1 m_2 > 0. \end{eqnarray*} By the symmetricity of $\bar{Q}_1(m_2)$ and $\bar{Q}_2(m_1)$, we have \[ \bar{Q}_1(m_2) + \bar{Q}_2(m_1) = (4 - 2 \ell - \alpha_1 \alpha_2 + \ell \alpha_1 \alpha_2) (m_1 + m_2)^2 - 2 \alpha_1 \alpha_2 m_1 m_2 > 0, \] which implies $$ \alpha < \dfrac{4 - \alpha_1 \alpha_2}{2 - \alpha_1 \alpha_2} \le 3. $$ Thus we get a contradiction with $m \geq 3(m_1 + m_2)$, which completes the proof of Lemma \ref{lem:q1=q2=0} and accordingly Case 1 + Case 1 cannot be a Nash equilibrium. \subsection{Case 2 + Case 1/3: $B_1(x_1, x_2) = 0$ and $x_2\in\{0, m_2\}$} We follow the notation $Q_1(\cdot)$ in the prior subsection, \[ Q_1(x_1, x_2) = a_1(x_2)x_1^2+b_1(x_2)x_1+c_1(x_2) \] and $c_1(x_{2}) \le 0$ has been shown in Claim~\ref{claim:Q_1:c_1}. \begin{lemma} \label{lem:case2+case13} $Q_1(x_1, x_2)$ cannot be $0$ for any $x_1\in (0, m_1)$ and $x_2\in\{0, m_2\}$. \end{lemma} \begin{proof} As shown in Claim~\ref{claim:Q_1:c_1} and Claim~\ref{claim:Q_1:b1}, we have $c_1(x_2) \le 0$ and $b_1(x_2) < 0$ for any $x_2\in\{0, m_2\}$. Similar to figure~\ref{figure:a1=0} and \ref{figure:a1<0}, if $a_1(0) \le 0$ then $Q_1(x_{1}, 0)$ cannot be $0$ for all $x_1\ge0$. And for the case $a_1(0) \ge 0$, \begin{eqnarray*} Q_1(m_1, 0) & = & \alpha_2m_1^2m_2(-m+2m_1+m_2) \\ Q_1(m_1, m_2) & = & -(m_1+m_2)(m-m_1-m_2) (-\alpha_1\alpha_2m_1m_2+(m_1+m_2)^2) \end{eqnarray*} are obviously less than $0$. Thus, $Q_1$ cannot be $0$ for any $x_1\in(0,m_1)$ and $x_2\in\{0, m_2\}$. \end{proof} By Lemma \ref{lem:case2+case13}, Case 2 + Case 1/3 cannot be Nash equilibria, and symmetrically, Case 1/3 + Case 2 cannot either. \subsection{Other Situations} Finally, we briefly discuss the remaining situations: $(x_1,x_2)\in \{(0, m_2), (m_1, 0),\allowbreak (m_1, m_2)\}$. It is not hard to see that neither of them can benefit by sending all her mining power to attack the other: for case $(m_1, m_2)$, both two players get no reward; for case $(0, m_2)$, player $2$ only gets $$\frac{m_1}{m-m_2}\cdot\frac{m_2}{m_1+m_2}(1-\alpha_1) < \frac{m_2}{m};$$ and the case $(m_1, 0)$ is symmetric to $(0, m_2)$. In conclusion, all the eight situations, except $(0, 0)$, are not Nash equilibria, which finishes the proof of Theorem~\ref{thm:2pools:unique}. \section{Conclusion and Future Directions} In this work, we refine the game-theoretic model for pool block withholding attacks when the managers of the pools individually deduct small fractions from the total rewards. For most reasonable deductions, we show that no-pool-attacks is always a Nash equilibrium for any number of pools, and particularly, when there are only two pools under consideration, it is the unique Nash equilibrium. A direct open problem is to generalize our second result to more than two pools, that is, is it possible for an arbitrary number of managers to make small deductions so that no-pool-attacks is also a unique Nash equilibrium? There are many other future directions that deserve exploration. For example, in all works about PBW games that we know, it is assumed that every miner for a pool is always loyal to her pool manager. This assumption does not hold when the miners have their own interests on how to report their solutions. We hope that, by combining tools in cooperative game theory, our work can inspire further study in this direction. \bibliographystyle{plain}
{'timestamp': '2020-08-18T02:18:09', 'yymm': '2008', 'arxiv_id': '2008.06923', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06923'}
arxiv
\section{Introduction} The number of Internet connected entities was approximately 27 billion in 2019, and is expected to rapidly reach the enormous number of 75 billion by 2025~\cite{Maayan}. The modern Internet is a global network of intelligent devices ranging from traditionally connected devices such as desktop and laptop computers and smartphones to objects of daily use such as watches and spectacles, electronic home appliances (even window shutters), sensing and actuating devices such as patients' medical sensors and industrially deployed temperature sensors and machinery~\cite{Das1}. The introduction of IPv6 addresses~\cite{Jiang} has made it possible for all these devices to connect to the Internet and has helped in automation of tasks, decreased the need for human intervention, increased accessibility and convenience in functionality and data acquisition. The ability to connect resource-constrained devices such as sensors and actuators as well as everyday objects to the Internet has led to the notion of the \emph{Internet of Things} (IoT)~\cite{Weber}. Compared to traditional devices such as desktop computers and laptops, IoT devices have low computational and storage power. As a result, they are not able to run the protocols traditionally used to achieve secure communications in the Internet, e.g., those that use public key cryptography~\cite{Granjal}. At the same time, confidentiality and message-integrity of data communicated by and to IoT devices is essential. It may relate to the geographical coordinates of a user, medication provided to a patient, customized use of home appliances, parameters and commands exchanged by industrial machinery or security alarms. This broad range of essential functions, without sufficient security, can potentially result in huge losses. Hence, it is crucial to design effective security mechanisms for resource-constrained IoT devices. A review of prior research literature in which security mechanisms for the IoT are proposed is provided in Section~\ref{RW}. Many present-day scenarios require communication to and data acquisition from multiple devices with similar functionalities, e.g., medical sensors, Industrial Wireless Sensor Network nodes and nodes installed in smart homes. For such scenarios, \emph{group communication} in the form of multicasting and broadcasting has proven to be effective~\cite{Veltri}. \emph{Group Key Management} (GKM) involves the handling, revocation, updation and distribution of cryptographic keys to members of various groups in a communication network~\cite{Rafaeli}. GKM can be adopted in a centralized or distributed manner~\cite{Omar}. Centralized GKM schemes involve a centralized entity like a Key Distribution Center, which generates keys and performs the aforementioned functions. On the other hand, in distributed GKM schemes, nodes are clustered into several groups and cluster heads are assigned to manage keys locally~\cite{Esposito}. However, the latter approach incurs high computational costs; as a result, most research, including this paper, is based on the centralized approach. Now, classical GKM schemes perform inefficiently in \emph{dynamic} IoT environments, which are those wherein nodes frequently leave or join a network or migrate from one group to another over time~\cite{Kung}. In such scenarios, whenever changes occur in the network, keys need to be updated and distributed in such a way that \emph{backward and forward secrecy}~\cite{Rafaeli} is maintained. Apart from this, the use of asymmetric cryptography in dynamic IoT environments limits the overall scalability of the system. Therefore, a GKM scheme based on symmetric cryptography is needed that can scale well in dynamic settings. One major goal of such a GKM scheme is to exercise access control over the network~\cite{Kung}. Specifically, a set of users, also called subscribers, send data to and receive data from an IoT device. For example, these users may be nursing staff appointed for a patient, who wish to obtain periodic vital sign data from medical sensors deployed on the patient's body. It is of utmost importance to provide confidentiality and integrity of messages, as well as avoid any unauthorized access. Sharing a group key between a device and its subscribers is an effective way to impose such access control. However, as users join, leave or migrate between groups (e.g., a nurse is allocated to or deallocated from a patient or allocated to a different patient), real-time GKM is desired to fulfill the security requirements. In this paper, we present a centralized GKM scheme for dynamic IoT environments, which maintains forward and backward secrecy at all times. Our scheme only employs resource-constrained network friendly symmetric encryption, due to which the centralized controller can efficiently handle a large number of subscription changes, node entries and exits at any given time. Moreover, our scheme is designed in such a way that no user outside the network can collude with a registered device and deduce group secrets. In our scheme, we have also made provisions for new scenarios in which device or user dynamics may take place, e.g., allowing a device group to join or leave the network or creation or dissolution of a user group, which were not provided by schemes proposed in prior literature~\cite{Kung}; this makes our proposed scheme more flexible in handling dynamics. Finally, via mathematical analysis and numerical computations, we evaluate the performance of the proposed scheme and show that it outperforms the GKM scheme proposed for dynamic IoT environments in prior work~\cite{Kung}. The rest of the paper is organized as follows. In Section~\ref{RW}, we review the prior research literature on security in the IoT and GKM. Section~\ref{model} describes our system model, problem formulation and reviews some relevant background. In Section~\ref{GroupIt}, we briefly describe the GKM scheme `GroupIt' proposed for dynamic IoT environments in~\cite{Kung} and identify its limitations. Our proposed GKM scheme is described in Section~\ref{PP}. In Section~\ref{performance}, a mathematical analysis of the performance of the proposed scheme in terms of storage, computation and communication costs is provided. In Section~\ref{numerical}, we provide a numerical computations based performance evaluation of the proposed scheme. Finally, we provide conclusions and directions for future research in Section~\ref{conclusion}. \section{Related Work} \label{RW} Security in the IoT has gained significant attention in the research community-- surveys of various enabling technologies for the IoT (e.g., RFID, Zigbee, MQTT, CoAP), including security aspects, are provided in~\cite{Granjal},~\cite{Lin},~\cite{Sicari}. The IEEE standard 802.15.4 defines rules for the physical and medium access control (PHY and MAC) layers, aimed at providing low cost, low power and low data rate wireless connectivity among constrained devices~\cite{Gutierrez}. The Internet Engineering Task Force (IETF) has also developed protocols for various layers to support the IoT~\cite{Sheng}. IPv6 over Low power Wireless Personal Area Networks (6LoWPAN)~\cite{Schrickte}, an IETF standard, is one of the technologies adopting 802.15.4. It acts as a gateway between the Internet and constrained devices, performing various tasks such as header compression, fragmentation and reassembly of IPv6 packets from the Internet into sizes that can be sent over constrained networks using 802.15.4. The Routing Protocol for Low Power and Lossy Networks (RPL) is another IETF standard, designed for routing over constrained networks. DTLS header compression and TLS-DTLS mapping~\cite{Yang} have also been proposed to increase the allowed application-layer payload. The design of secure protocols for various IoT standards is a topic of recent research~\cite{Granjal}. Multifactor authentication has been extensively studied in the past decade and a plethora of schemes have been proposed for various IoT settings. In~\cite{Turkanovic}, a novel $2$-factor authentication scheme for any remote user to securely connect with a given sensor node is presented. Wireless Sensor Networks (WSNs) form an integral part of the IoT. In~\cite{Jiang}, the authors propose an efficient and lightweight $3$-factor authentication and key establishment scheme, based on Biohashing and the Rabin Cryptosystem, for WSNs to securely connect to the Internet. Elliptic Curve Cryptography has also found novel applications in designing keying protocols for constrained network architectures~\cite{Porambage,Das,Chang,Ferrari}. Online validation of public key certificates is another problem in the field of IoT security. In~\cite{Park}, the authors introduced a protocol that employs a cryptographically generated address for bootstrapping to secure the join and certificate issuance mechanisms. Over the years, several highly efficient \emph{Group Key Establishment} (GKE) schemes have been proposed. GKE refers to one-time authentication and key agreement among two or more parties in a group who wish to exchange messages. In~\cite{Eldefrawy}, a lightweight key distribution protocol for Industrial IoT, based on the Chinese Remainder Theorem, which requires only a single message transmission, and provides backward and forward secrecy is proposed. In~\cite{Robinson}, the authors explored the use of Physical Unclonable Functions with appropriate guarantees as a tool for GKE. In~\cite{Ferrari1}, a context based GKE protocol, in which devices calculate a fingerprint from their surrounding context and generate a shared secret among them, was proposed. However, recent literature has shown a shift towards Group Key Management (GKM) in the IoT. Complementing GKE, GKM deals with the updation, revocation and distribution of established cryptographic keys in a group. In~\cite{Rafaeli}, a broad survey and comparison of several centralized, decentralized and distributed GKM protocols was provided. The authors compared various mechanisms proposed in the research literature for GKM, including LKH, OFT, ELK and MARKS. In~\cite{Veltri}, the authors proposed a novel batch based centralized approach to efficiently manage group keys in generic ad hoc networks, while limiting the computational and communication costs due to group membership changes caused by users joining and leaving. They handle such membership changes and events of explicit membership revocation at different pre-assigned times by partitioning time into fixed length intervals. Our scheme, on the other hand, allows more flexibility for users by removing the need to alter memberships at pre-assigned times. In~\cite{Omar}, a Logical Neighbor Tree (LNT) based approach to distribute key update messages in the events of membership changes is proposed. The proposed scheme reduces the key update latency from $O(n)$ to $O(\log(n))$, where $n$ is the number of group members. Unlike equally ranked group entities in our protocol, their scheme includes a group controller for each group, which is responsible for local security inside the respective groups. In~\cite{Wong}, the Logical Key Hierarchy (LKH) approach in which keys are arranged in a hierarchy and a Key Distribution Center maintains and updates all the keys was proposed. It makes use of symmetric key encryption to multicast key update messages to group members, which are located at the leaf nodes of a logical tree; the communication cost of this scheme is of the order of $O(\log(n))$, where $n$ is the number of nodes in the network. As we will see later, we have also used LKH as a basic mechanism to form groups in our model. Later,~\cite{Son} presented a Topological Key Hierarchy (TKH) scheme for WSNs as an alternative to LKH. TKH generates a key tree by using the underlying sensor network topology and considering subtree-based key tree separation. A basic difference from LKH is that topologically adjacent entities share similar key material, and therefore, receive similar rekeying messages. Recently in~\cite{Mughal}, the authors proposed a logical tree based secure mobility management scheme (LT-SMM) using mobile service computing for the IoT. The model includes a group head for each group, which is computationally more capable than other nodes in the group. Although using the LKH scheme as in our proposed protocol, their main focus is on reducing excessive rekeying when a node only migrates from one group to another-- coordinating the group heads through the Base Station helps in exchanging key material, and completing the migration process with a small overhead for the migrating node. The closest to our research is the work~\cite{Kung}, which, to the best of our knowledge, is the only paper in prior work that proposes a GKM scheme for dynamic IoT environments. In~\cite{Kung}, a system model that consists of several groups of users, which selectively subscribe to a desired subset of device groups and collect data, was considered. The authors proposed a two-tier GKM scheme, GroupIt, to handle frequent subscription changes. They leveraged the LKH scheme and the Chinese Remainder Theorem (CRT) to reduce the communication overhead incurred due to node entry and exit events. While the CRT manages keys shared between the centralized controller and groups, LKH handles key distribution within groups. In~\cite{Kung}, it is claimed that the GroupIt scheme achieves forward and backward secrecy, as well as a low probability of collusion attacks. However, in this paper, we propose a scheme that outperforms the GroupIt scheme in several respects; in particular, our scheme completely eliminates collusion attacks and is more efficient since, in contrast to the GroupIt scheme, it does not use asymmetric encryption. Moreover, our proposed GKM scheme is more flexible than GroupIt since the former handles new scenarios in which device or user dynamics may take place, e.g., allowing a device group to join or leave the network or creation or dissolution of a user group; GroupIt does not explicitly handle any of the above scenarios. Finally, we show via a combination of mathematical analysis and numerical computations that our proposed scheme outperforms GroupIt in terms of the computation and communication cost incurred by users as well as devices. \section{Model, Problem Formulation and Background} \label{model} We describe the system model and adversarial model in Sections~\ref{model:A} and~\ref{model:B}, respectively. Then in Section~\ref{model:C}, we provide a brief overview of the LKH scheme, which we use as a part of our proposed scheme. \subsection{System Model} \label{model:A} The system consists of a Key Distribution Center (KDC), IoT devices and subscribers (users). Henceforth, the terms ``user'' and ``subscriber'' are used interchangeably. The KDC is a trusted centralized entity that generates, distributes and updates key material for all devices and users. The KDC is assumed to have high computational and storage capability; hence, while quantifying the protocol's efficiency, we focus on the computational and storage costs incurred by the devices and users. Each IoT device collects the required data and periodically sends it to its subscribers. For instance, devices (sensors) attached to a patient's body may periodically send the patient's vital signs to their subscribers (authorized nurses). One or more devices of similar functionality or security classification are grouped together into a ``\emph{Device Group}'' (DG). Also, one or more users are grouped together into a ``\emph{Subscriber Group}'' (SG). Each user (respectively, device) belongs to exactly one SG (respectively, DG). Each SG is subscribed to one or more DGs. In particular, a SG is a group of users subscribing to a specific subset of DGs. Thus, if there are $P$ DGs, then there are $2^{P}-1$ possible SGs, corresponding to different non-empty subsets of the collection of the $P$ DGs. Each user or device in the network has to authenticate itself and have a secret key established with the KDC before becoming part of any group. Also, each user or device group has its own group key, initially provided by the KDC. Each device can exchange encrypted data with its subscribed users using a key that is known only to the KDC and the communicating parties, called the ``\emph{device key}'' of the device. Fig.~\ref{fig1} illustrates the system model. \begin{figure} \centering \includegraphics[scale=0.32]{fig1_model.png} \caption{There are five DGs, DG\textsubscript{1}, \ldots, DG\textsubscript{5}, and $n$ UGs, UG\textsubscript{1}, \ldots, UG\textsubscript{n}. UG\textsubscript{1} subscribes only to DG\textsubscript{1}, UG\textsubscript{2} subscribes to DG\textsubscript{1}, DG\textsubscript{2} and DG\textsubscript{3}, and so on.} \label{fig1} \end{figure} Our objective is to design a GKM scheme that enables efficient updation or revocation of the cryptographic keys assigned to different users and devices in the network when changes take place in the network such that \emph{forward and backward secrecy} is maintained at all times. Recall that by forward (respectively, backward) secrecy, we mean that a leaving (respectively, joining) user is prevented from decrypting messages exchanged after (respectively, before) it leaves (respectively, joins) the group~\cite{Rafaeli}. The possible scenarios in which key material needs to be updated or revoked are as follows: A user or a device joining or leaving the network, addition or removal of a DG, a user occupying an empty SG and an existing user leaving the last spot in a SG. Also, we seek to design a GKM scheme that minimizes the computational, communication and storage costs incurred to the users and devices in the network when changes take place in the network. Similar to most prior works in GKM, we make the following assumptions. First, all network entities use the same cipher suite and keys are sufficiently large~\cite{Porambage}. Second, the system is reactive to tampering; therefore, any node capture or compromise will be detected in practically small time, resulting in appropriate revocation and updation of device and user key material. Different approaches such as mobility based~\cite{Conti} and control theoretic~\cite{Bonaci} modelling have been presented in prior work to detect and revoke compromised nodes. Finally, we assume that the message integrity of all communication exchanged during the network operation is protected using standard mechanisms (e.g., message authentication codes)~\cite{Granjal}. \subsection{Adversarial Model} \label{model:B} In our model, the adversary may be a node outside the network, a malicious user belonging to one of the user groups, or a corrupted device that tries to access data belonging to other devices. If the adversary is a user belonging to the network, it may try to either compromise forward or backward secrecy or access the data trasmitted by devices to which it is not subscribed. The adversary aims to breach access control and decrypt the periodic data transmitted by devices, which it is not authorized to access, either by illegitimately gaining access to key material or colluding with devices existing in the network. \subsection{Logical Key Hierarchy (LKH)} \label{model:C} LKH is a centralized GKM technique designed for achieving secure and efficient rekeying and message transmissions within a group~\cite{Wong}, while providing forward and backward secrecy. LKH provides methods to update the cryptographic keys shared within a group when a node joins or leaves the group. Moreover, it helps to multicast messages to different nodes in the group while incurring a low communication cost. Under the LKH scheme, a KDC maintains a tree of keys~\cite{Rafaeli} as shown in Fig.~\ref{fig2}. A group arranged in an LKH tree structure has all its members occupying the leaf nodes of the tree. Each node of the tree other than the leaves and the root is associated with a key called the \emph{Key Encryption Key} (KEK). Also, the root node is associated with a key called the \emph{group key}. A member knows all the KEKs belonging to its ancestors in the tree and the group key. For example, node L122 in Fig.~\ref{fig2} knows the KEKs corresponding to N12 and N1 and the group key. Note that each member stores at most $\lceil \log_2(k) \rceil$ KEKs, where $k$ is the number of group members. Apart from this, every member also has a secret key shared with the KDC. \begin{figure} \centering \includegraphics[scale=0.28]{fig2_LKH_structure.png} \caption{The figure shows an example LKH tree structure.} \label{fig2} \end{figure} An LKH tree structure helps to reduce the communication cost incurred in sending multicast messages from the KDC to group members. In the example in Fig.~\ref{fig2}, if a message is to be sent to the nodes L111, L112, L121 and L122, then a single multicast encrypted with the KEK corresponding to the common ancestor N1 can be sent under LKH; this is significantly more efficient than the transmission of four separate unicast messages encrypted using the different secret keys shared between the KDC and the four recipient nodes. \begin{figure} \centering \includegraphics[scale=0.28]{fig3_LKH_new_node_joins.png} \caption{The figure shows the LKH tree before and after node L22 joins the group.} \label{fig3} \end{figure} \begin{figure} \centering \includegraphics[scale=0.24]{fig4_LKH_node_leaves.png} \caption{The figure shows the LKH tree before and after node L112 leaves the group.} \label{fig4} \end{figure} The KDC is responsible for updating the group secrets in the events of member entry or exit so as to maintain backward and forward secrecy. Consider the LKH tree shown in Fig.~\ref{fig3}(a). When a new node L22 joins the group, the KDC first establishes a secret key with it. This is followed by creation or updation of all the keys corresponding to the ancestors of the joining node L22 in the new LKH tree shown in Fig.~\ref{fig3}(b) (i.e., the KEK corresponding to N2 and the group key) so as to maintain backward secrecy. The KDC then sends the newly created KEK of N2 and the updated group key to L22 using the secret key shared between the KDC and L22, and to other affected members who share a common ancestor with L22 using efficient multicasts using shared KEKs or secret keys. In this example, the KDC sends the new KEK of N2 and the group key to L21 using the shared secret key between the KDC and L21, and sends the updated group key to L11 and L12 using the KEK corresponding to N1. Similarly, if an existing member leaves the group, as shown in Fig.~\ref{fig4}, all its ancestral KEKs and the group key need to be updated to maintain forward secrecy. The KDC sends the updated KEKs and/ or the group key to the remaining members using suitable shared KEKs or secret keys. In this example, after L112 leaves, the KDC sends the updated KEK corresponding to N1 and the group key to L11 using the shared secret key between the KDC and L11, and to L121 and L122 using the KEK corresponding to N12. It also sends the updated group key to L21 and L22 using the KEK corresponding to N2. \section{Review and Limitations of GroupIt Scheme} \label{GroupIt} In Section~\ref{GroupIt:A}, we briefly review the GroupIt scheme proposed for dynamic IoT environments in~\cite{Kung} and in Section~\ref{GroupIt:B}, we discuss its limitations. \subsection{GroupIt} \label{GroupIt:A} GroupIt is a scheme designed for GKM in a dynamic IoT environment. The system model for which GroupIt is designed is the same as the one described in Section~\ref{model:A}. GroupIt uses LKH and the Chinese Remainder Theorem (CRT) to limit the communication overhead incurred for key updation due to node entry and exit events. While the CRT manages keys between the KDC and groups, LKH handles key distribution within a group. To initialize, the KDC generates secret keys for all users and devices and the LKH KEKs and group keys for all SGs and DGs, and distributes them to the respective users and devices. Each device is associated with a unique ID, and each DG is associated with a secret Traffic Encryption Key (TEK), both of which are known to each user subscribed to the device. In this way, the user can calculate the device key, which is a function of the device ID and TEK of the device group, for each device to which it is subscribed. The authors enlist four scenarios, discussed below, in which key material (group key, KEKs, TEKs) needs to be updated, and provide the corresponding steps to achieve forward and backward secrecy. For all these cases, LKH is used to update the group key and KEKs within a SG or DG. \subsubsection{New User (U\textsubscript{i}) Joins a Group SG\textsubscript{x}} First, the KDC establishes a secret key with the new user. It also notifies all the DGs subscribed by SG\textsubscript{x}, and the users subscribed to those DGs to hash-update their TEKs. Hash update refers to the application of a cryptographic hash function~\cite{Granjal} to the TEK, so that backward secrecy can be achieved. Then, the KEKs within SG\textsubscript{x} are updated as per the LKH join algorithm described in Section~\ref{model:C}. Finally, the new user is provided the required key material using the secret key established between the KDC and the new user. \subsubsection{Existing User (U\textsubscript{i}) Leaves a Group SG\textsubscript{x}} The KDC first updates the group key of SG\textsubscript{x}. Then, for each DG that was subscribed to by the leaving user, it broadcasts to the other users, updated TEKs and methods to update the device IDs of the devices, using double encryption, i.e., two layers of encryption, first using an asymmetric key on the message and then encrypting the output with a symmetric key TEK. Finally, the new TEKs and device IDs are sent to the devices subscribed to by the leaving user. \subsubsection{New Device Joins a Group} First, the KDC establishes a secret key with the joining device. Then, it updates the group key and the KEKs of its DG. Finally, the ID of the new device is shared with the users subscribed to it. \subsubsection{Existing Device Leaves a Group} The KDC first broadcasts over the network that the device is no longer available, and then updates the group key and KEKs for the other devices in the group. \subsection{Limitations of GroupIt} \label{GroupIt:B} \subsubsection{Employment of Asymmetric Encryption} When an existing user leaves a SG, the KDC broadcasts doubly encrypted messages to the other users, each containing update methods for a DG subscribed to by the leaving user. The inner layer of this encryption requires asymmetric decryption by the other users. This has a significant computational cost~\cite{Wang}. \subsubsection{Collusion Attacks} \label{SSSC:GroupIt:B:collusion} The device keys are derived from device IDs and TEKs of the DGs. If the device ID is not updated when a user subscribed to the device leaves, and the leaving user colludes with a device having the new TEK, then they can combine their knowledge to derive the other devices' new device keys. GroupIt has a non-zero probability that these device IDs will not be updated when a user leaves. \subsubsection{Erroneous Steps of Key Updation} To achieve backward secrecy, the LKH group key of the SG must be updated when a new user joins the SG. But the scheme does not account for such a key update. Also, when an existing user leaves, the KEKs of the SG are not updated. Due to this, the new group key can be compromised by being revealed to the leaving user. Moreover, in the double encryption performed when a user leaves, the old TEK is available with the leaving user and it does not add to the forward secrecy of the system, since the user can easily decrypt the outer layer of encryption even after leaving. \subsubsection{Low Flexibility} GroupIt does not explicitly handle the cases when a new DG joins, an old DG leaves, a new user occupies an empty SG, and an existing user leaves the last occupied spot in a SG. \section{Proposed GKM Scheme} \label{PP} Our proposed GKM scheme is described in the following subsections. \subsection{Setup and Pre-deployment} \label{PP:1} Users (respectively, devices) in a SG (respectively, DG) are arranged in an LKH tree structure and occupy the leaf nodes of the tree (see Fig.~\ref{fig5}). Also, the SGs themselves are part of a bigger (outer) LKH structure, which we refer to as the `uLKH', as shown in Fig.~\ref{fig6}; we refer to a KEK in the outer LKH structure as a `uKEK'. When we say that a SG is assigned a set of uKEKs, it means that each user in the SG is assigned that set of uKEKs. In the example in Fig.~\ref{fig6}, all users in SG\textsubscript{111} and SG\textsubscript{112} have uKEK\textsubscript{11}, uKEK\textsubscript{1} and the group key, uN, corresponding to the root, uNode. Note that uN can be used to securely broadcast a message to all the users in the network. The group key, uN, and the uKEKs together enable the KDC to multicast messages to multiple SGs. In the example in Fig.~\ref{fig6}, if a message is to be sent to SG\textsubscript{111}, SG\textsubscript{112}, SG\textsubscript{121} and SG\textsubscript{122}, then the KDC will simply encrypt it with uKEK\textsubscript{1} and multicast the message to the four groups. \begin{figure} \centering \includegraphics[scale=0.26]{fig5_dg_and_sg.png} \caption{The LKH tree structure of four devices in a DG (left) and five users in a SG (right).} \label{fig5} \end{figure} \begin{figure} \centering \includegraphics[scale=0.26]{fig6_outer_LKH.png} \caption{The outer LKH tree structure of 8 SGs.} \label{fig6} \end{figure} The device key for a device $j$ is defined as: \begin{equation} \label{EQ:E:m:j} DK_j=h(ID_j||n_j) \end{equation} where $h(\cdot)$ is a cryptographic hash function, $ID_j$ is a secret and $n_j$ is a nonce, both $ID_j$ and $n_j$ are shared between device $j$ and the KDC, and $||$ denotes a concatenation. Each device $j$ encrypts messages containing its periodic data using $DK_j$ and multicasts it to all the SGs subscribed to device $j$. Each user subscribed to a device $j$ knows its device key $DK_j$. At the beginning of the network operation, the KDC performs the following actions: \begin{itemize} \item Establishes secret keys with each user and device. \item Generates and distributes the group key GK\textsubscript{y} for each device group DG\textsubscript{y}. \item Generates and distributes the group key SK\textsubscript{x} for each subscriber group SG\textsubscript{x}. \item Generates and distributes the KEKs for the LKH tree of each SG and DG. \item Generates the device IDs and nonces for all devices, distributes them to the respective devices and computes the device keys for all devices. \item Distributes the device key of each device $j$ to all the SGs subscribed to device $j$. \item Generates and distributes the uKEKs and the group key for the outer SG tree. \end{itemize} \subsection{When a New User Joins} \label{PP:2} When a new user $U_i$ joins a non-empty user group SG\textsubscript{x}, the following actions are performed: \begin{itemize} \item The KDC establishes a secret key with the new user $U_i$. \item The KDC sends a broadcast message that all devices from the DGs to which SG\textsubscript{x} subscribes and the old users from SGs subscribed to those DGs should hash update the device keys, say $DK_j$, and that the users in SG\textsubscript{x} should hash update the group key SK\textsubscript{x}. The above updates are performed as follows: \begin{enumerate} \item $DK^{\prime}_j = h(DK_j)$ \item $SK^{\prime}_x = h(SK_x)$ \end{enumerate} This ensures backward secrecy. \item The KDC sends the updated KEKs, say $KEK^{\prime}$s, corresponding to the ancestors of $U_i$ in the new LKH tree of SG\textsubscript{x} to the members of SG\textsubscript{x} encrypted by the appropriate secret keys or shared KEKs. \item The KDC sends the updated uKEKs, say $uKEK'$s, of the outer LKH tree to the SGs having a common ancestor with SG\textsubscript{x}, encrypted by the appropriate group keys or shared uKEKs. \item The KDC shares the relevant secret information ($DK^{\prime}_j$, $SK^{\prime}_x$, $KEK^{\prime}$s, $uKEK'$s) with the new user $U_i$. \end{itemize} \subsection{When an Existing User Leaves} \label{PP:3} Suppose an existing user leaves its SG, say SG\textsubscript{x}, but SG\textsubscript{x} continues to be non-empty. Then a simple hash updation of secret information will not suffice, and therefore, the following procedure is adopted. The exit of the user not only affects the SG, SG\textsubscript{x}, from which the user left, but also the SGs that subscribe to the devices to which the leaving user subscribed, called the ``concerned SGs''. As a result, we first update the uKEKs in the outer LKH tree and then send the updated device keys using them to the concerned SGs. The following actions are performed: \begin{itemize} \item The KDC sends a message to the devices subscribed to by the leaving user to update their nonces. The nonce can be simply incremented by one, i.e., $n_j^{\prime} = n_j + 1$. This update does not require any unicast communication between the KDC and the devices, thus helping in limiting the communication cost. The new device key is calculated in the same way as before by the devices: \[DK'_{j} = h(ID_{j}||n'_{j})\] This helps in achieving forward secrecy. \item The KDC sends the updated KEKs for the users having a common ancestor with the leaving user in the LKH tree of SG\textsubscript{x} and the updated group key, $SK_x^{\prime}$, to the appropriate members of SG\textsubscript{x}, encrypted by appropriate secret keys or KEKs. \item The KDC sends the updated uKEKs to the SGs having a common ancestor with SG\textsubscript{x} in the outer LKH tree, encrypted by the appropriate group keys or shared uKEKs. \item For each DG subscribed to by SG\textsubscript{x}, the KDC sends a multicast containing the updated device keys to the SGs subscribed to the DG, using the appropriate updated uKEKs. \end{itemize} \subsection{When a New Device Joins} \label{PP:4} The new device, say $D_k$, is added to one of the DGs, say DG\textsubscript{y}. The KDC creates a secret identity, $ID_k$, and a secret nonce, $n_k$, for $D_k$. The following actions are performed: \begin{itemize} \item The KDC establishes a secret key with the device, provides it with $ID_k$ and $n_k$, and both the KDC and the device $D_k$ derive the device key as follows: \[DK_{k} = h(ID_{k}||n_{k}).\] \item The KDC sends a message to the existing devices in DG\textsubscript{y} to hash update their group key: $GK'_y = h(GK_y)$. This helps in achieving backward secrecy. \item The KDC sends the updated KEKs corresponding to the ancestors of $D_k$ in the LKH tree of DG\textsubscript{y} to the appropriate devices in DG\textsubscript{y}, encrypted by appropriate secret keys or shared KEKs. \item The KDC securely multicasts the device key $DK_k$ to the SGs subscribed to DG\textsubscript{y} using the appropriate uKEKs. \end{itemize} \subsection{When an Existing Device Leaves} \label{PP:5} Suppose an existing device, say $D_k$, leaves a DG, say DG\textsubscript{y}, but DG\textsubscript{y} continues to be non-empty. Then the following actions are performed: \begin{itemize} \item The KDC sends a broadcast message to all SGs indicating that device $D_k$ is no longer available. This broadcast message is sent using the group key of the outer LKH tree, i.e., the key, uN, corresponding to the root uNode. \item The KDC sends the updated KEKs and the updated group key, $GK_y^{\prime}$, of the LKH tree of DG\textsubscript{y} to the appropriate members of DG\textsubscript{y}, encrypted using the appropriate secret keys or shared KEKs. \end{itemize} \subsection{When a New User Occupies an Empty Group} \label{PP:6} When a new user, say $U_i$, joins an empty SG, say SG\textsubscript{x}, the following actions are taken: \begin{itemize} \item The KDC establishes a secret key with the user $U_i$. \item The KDC creates a new LKH tree for the group SG\textsubscript{x} and derives its group key SK\textsubscript{x}. \item The KDC sends a broadcast message announcing that all devices to which SG\textsubscript{x} subscribes and the old users subscribed to those devices should hash update the device keys: $DK'_j = h(DK_j)$. This helps in achieving backward secrecy. \item The KDC modifies the outer LKH structure, uLKH, to add SG\textsubscript{x} to it; in particular, the KDC sends the updated uKEKs, say $uKEK'$s, and the updated group key, say $uN'$, corresponding to uNode to the SGs having a common ancestor with SG\textsubscript{x}, encrypted by the appropriate group keys or shared uKEKs. \item The KDC shares the relevant secret information ($DK_j'$, SK\textsubscript{x}, $uKEK'$, $uN'$) with the user $U_i$, by encrypting it using the secret key shared between the KDC and user $U_i$. \end{itemize} \subsection{When an Existing User Leaves the Last Spot in a SG} \label{PP:7} When an existing user leaves the last spot in a SG, say SG\textsubscript{x}, the LKH tree keys of the SG need not be updated since new keys are derived if and when the SG starts re-populating. Nevertheless, we need to update the uKEKs in the outer LKH tree and then send device keys using them to the concerned SGs as in Section~\ref{PP:3}. The following actions are performed: \begin{itemize} \item The KDC sends a message to the devices subscribed to by the leaving user to update their nonces as in Section~\ref{PP:3}: $n'_j = n_j + 1$. The new device key will be $DK'_j = h(ID_j \vert \vert n'_j)$. This helps in achieving forward secrecy. \item The KDC sends the updated uKEKs to the SGs having a common ancestor with SG\textsubscript{x}, encrypted by appropriate group keys or shared uKEKs. \item For each DG subscribed to by the leaving user, the KDC sends a multicast containing the updated device keys to the SGs subscribed to the DG, using the updated uKEKs. \end{itemize} \subsection{When a New DG Joins} \label{PP:8} Recall that a SG is a group of users subscribing to a specific subset of DGs. So when a new DG joins, the possible number of SGs will change from $2^{P}-1$ to $2^{P+1}-1$, where $P$ is the number of DGs before the new DG joined, i.e., it will approximately double. Also, a given SG may be split into two unique SGs-- one with users with the same subscriptions as the original SG, and the other with users who opt to additionally subscribe to the new DG. This splitting is performed as follows: in the outer LKH tree, the two newly formed SGs become child nodes of the node corresponding to the original SG. In the example in Fig.~\ref{fig12}, when SG\textsubscript{12} splits, SG\textsubscript{121} and SG\textsubscript{122} become child nodes of the node corresponding to SG\textsubscript{12}. Also, the group key of SG\textsubscript{12} becomes the uKEK for both the child nodes after splitting; this uKEK is uKEK\textsubscript{12} in Fig.~\ref{fig12}. As a result, splitting does not necessitate updation of uKEKs to maintain forward or backward secrecy. However, we observe that the inner LKH trees of the newly formed SGs need to be constructed appropriately based on which users from the original SG opt to subscribe to the new DG. The KDC constructs these inner LKH trees, securely sends their KEKs and group keys to the newly formed SGs, and sends, to the newly formed SGs that subscribe to the newly joined DG, the device keys of the devices of the DG. The splitting of a SG can cost heavy communication overhead to the network; however, since in practice, a new DG would only rarely join the network, this overhead would be small. We will later show that even under this rare event, the per user computation is small under our proposed protocol (see Sections~\ref{performance:B}.7 and~\ref{performance:C}.7). The following actions are performed: \begin{itemize} \item For each SG that splits into two SGs, the KDC modifies the outer LKH tree by making the new SGs the child nodes of the original SG's node as explained above. \item Whenever a SG is split into two SGs, the KDC constructs the inner LKH trees of the two SGs appropriately and securely distributes the group keys and KEKs of the newly formed SGs to the members of the SGs. \item The KDC arranges the devices of the new DG in a LKH tree and generates its group key and KEKs. \item As in Section~\ref{PP:4}, the KDC establishes a secret key, creates a secret identity and a nonce for each of the devices in the newly joined DG. \item The KDC provides each of the devices in the newly joined DG with the respective individual (identity and nonce) and group (group key and KEKs) secrets using the established shared secret keys between the devices and the KDC. Then the KDC as well as the devices derive the device keys. \item Whenever a SG is split into two SGs, the KDC securely multicasts, to the members of the newly formed SG that subscribes to the newly joined DG, the device keys of the devices of the DG, using the group key of the inner LKH tree of the SG. \end{itemize} \begin{figure} \centering \includegraphics[scale=0.29]{fig12_SG_split.png} \caption{The figure on the left (respectively, right) shows the outer LKH tree before (respectively, after) SG\textsubscript{12} splits into two SGs-- SG\textsubscript{121} and SG\textsubscript{122}. The group key of SG\textsubscript{12} becomes the uKEK, uKEK\textsubscript{12}, for the users in the two SGs.} \label{fig12} \end{figure} \subsection{When an Existing DG Leaves} \label{PP:9} This case is exactly opposite to the case when a new DG joins (Section~\ref{PP:8}). In particular, recall that a SG is a group of users subscribing to a specific subset of DGs. So when an existing DG leaves, the possible number of SGs will change from $2^{P}-1$ to $2^{P-1}-1$, where $P$ is the number of DGs before the existing DG leaves, i.e., it will approximately halve. Also, merging of pairs of SGs may be needed. Specifically, suppose before the DG left, there were two SGs, SG\textsubscript{X} and SG\textsubscript{Y}, which subscribed to the same set of DGs, except that SG\textsubscript{X} (respectively, SG\textsubscript{Y}) subscribed (respectively, did not subscribe) to the leaving DG. Then after the DG leaves, SG\textsubscript{X} and SG\textsubscript{Y} will be subscribed to the same set of DGs and hence need to be merged, forming a bigger SG, say SG\textsubscript{XY}. Under our proposed protocol, this merging is performed as follows. The inner LKH tree structures of SG\textsubscript{X} and SG\textsubscript{Y} are not changed; also, the root nodes (corresponding to group keys) of the two SGs become children (corresponding to KEKs) of the new root node of SG\textsubscript{XY}. Fig.~\ref{fig13} shows the inner LKH trees of two SGs, SG\textsubscript{X} and SG\textsubscript{Y}, before merging and Fig.~\ref{fig14} shows the inner LKH tree of the new SG, SG\textsubscript{XY}, formed after merging. The nodes (root nodes) corresponding to the group keys, SK\textsubscript{X} and SK\textsubscript{Y}, of the two SGs become child nodes, corresponding to the KEKs KEK\textsubscript{X0} and KEK\textsubscript{Y0}, respectively, of the new root node corresponding to the group key SK\textsubscript{XY}. Also, SK\textsubscript{XY} can simply be the hash of the group key of the bigger group out of SG\textsubscript{X} and SG\textsubscript{Y}, say SG\textsubscript{Y}. Additionally, similar to Section~\ref{PP:7}, the LKH tree keys of the leaving DG need not be updated since new keys are derived if and when the DG starts re-populating. Also, the KDC sends a broadcast message to all SGs that the devices in the leaving DG are no longer available. For each instance of merging of two SGs, SG\textsubscript{X} and SG\textsubscript{Y}, into a bigger SG, SG\textsubscript{XY}, the following actions are performed: \begin{itemize} \item The KDC arranges the LKH trees of the two SGs as shown in Fig.~\ref{fig14}, and the KDC and users in the bigger SG, SG\textsubscript{Y}, calculate the new group key of the merged group SG\textsubscript{XY} as SK\textsubscript{XY} = h(SK\textsubscript{Y}). \item The KDC securely multicasts SK\textsubscript{XY} to all the users of the subscriber group SG\textsubscript{X} by encrypting it using the key KEK\textsubscript{X0}. \end{itemize} Also, unlike Section~\ref{PP:8}, modification of the outer LKH tree post-merging is, in general, non-trivial and depends on which pairs of SGs are merged. The KDC constructs the new outer LKH tree obtained after merging, and securely distributes its updated uKEKs to all the SGs using appropriate uKEKs or group keys. Although this may incur significant communication cost, since the leaving of an existing DG would typically be a rare event in practice, the resulting overhead would be small. Also, the per user computational cost incurred when an existing DG leaves is small (see Sections~\ref{performance:B}.8 and ~\ref{performance:C}.8). \begin{figure} \centering \includegraphics[scale=0.29]{fig13_before_sg_merger.png} \caption{The figure shows the inner LKH trees of the groups SG\textsubscript{X} and SG\textsubscript{Y} before merging.} \label{fig13} \end{figure} \begin{figure} \centering \includegraphics[scale=0.31]{fig14_after_sg_merger.png} \caption{The figure shows the inner LKH tree of the group SG\textsubscript{XY} obtained by merging of the SGs SG\textsubscript{X} and SG\textsubscript{Y}. Note that SK\textsubscript{XY} is securely multicast to U\textsubscript{X1}, U\textsubscript{X2}, U\textsubscript{X3} and U\textsubscript{X4} by encrypting it using KEK\textsubscript{X0}.} \label{fig14} \end{figure} \subsection{Collusion} \label{PP:10} In~\cite{Kung}, the authors discussed about a possible collusion attack, which can occur under their proposed scheme, GroupIt, wherein a leaving user colludes with an existing device. This happens because the old user is aware of the device IDs of all the subscribed devices and the existing device knows the updated TEK. They can combine their knowledge to derive the other devices' new device keys. However, in our proposed scheme, users are not aware of any device's ID. Even if a user knows the device keys of all its subscribed devices, whenever a user leaves, the device keys are updated as explained in Section~\ref{PP:3} and Section~\ref{PP:7}. Hence, there is no possibility of a collusion attack under our proposed scheme. \subsection{Discussion} Throughout, we have focused on designing a lightweight, flexible and secure GKM scheme. The incorporation of the outer LKH tree structure in the proposed scheme makes key distribution (especially that of device keys) across SGs highly efficient. Unlike GroupIt, which uses asymmetric encryption, the use of only symmetric encryption under our proposed scheme has also added to its efficiency. Also, we have provided increased flexibility by including the ability to handle the cases where a new DG joins, an old DG leaves, a new user occupies an empty SG, and an existing user leaves the last occupied spot in a SG in our proposed scheme; note that GroupIt does not explicitly handle any of the above events. We have also achieved better security as compared to GroupIt by maintaining forward and backward secrecy during all events of user and group dynamics, as well as completely preventing collusion attacks. \section{Performance Analysis} \label{performance} \begin{table} \centering \caption{Notation used in Sections~\ref{performance} and~\ref{numerical}.} \label{Index} \begin{tabular}{|c|c|} \hline Notation & Meaning\\ \hline $L_y$ & No. of SGs subscribed to DG\textsubscript{y} \\ $N_x$ & No. of users in SG\textsubscript{x} \\ $M_y$ & No. of devices in DG\textsubscript{y} \\ $M_{max}$ & Maximum no. of devices in any DG \\ $Y_x$ & No. of DGs subscribed to by SG\textsubscript{x} \\ $\lceil x \rceil$ & Ceiling of $x$ \\ $P$ & No. of DGs \\ $Q$ & No. of SGs \\ Dec & Symmetric Decryption \\ AsyDec & Asymmetric Decryption \\ Hash & Cryptographic hash function \\ \hline \end{tabular} \end{table} In Sections~\ref{performance:A},~\ref{performance:B}, and~\ref{performance:C}, we analyze the storage, communication, and computational costs, respectively, of our proposed protocol and compare them with those under the GroupIt protocol. Table~\ref{Index} lists the notation used in this and the next section. \subsection{Storage} \label{performance:A} Under our proposed protocol, a user of group SG\textsubscript{x} stores at most $Y_x M_{max}$ device keys (the total number of DGs subscribed to by the user multiplied by the maximum number of devices in a DG, since there is a key for each device in each subscribed DG), at most $\lceil \log(N_x) \rceil$ KEKs (for multicast communication within SG\textsubscript{x}), one secret key (for message communication between the KDC and the user), one group key (for multicast messages between the KDC and the users of SG\textsubscript{x}), and at most $P$ uKEKs, which includes the key corresponding to the root uNode (for message communication using the outer LKH tree keys). On the other hand, a device of group DG\textsubscript{y} stores one ID and one nonce (for device key generation), at most $\lceil \log(M_y) \rceil$ KEKs (for multicast communication within DG\textsubscript{y}), one secret key (for message communication between the KDC and the device), and one group key (for multicast communication between the KDC and devices of DG\textsubscript{y}). In GroupIt, a user of group SG\textsubscript{x} stores at most $Y_x M_{max}$ device IDs, $Y_x$ TEKs, at most $\lceil \log(N_x) \rceil$ KEKs, one secret key, and one group key. On the other hand, a device of group DG\textsubscript{y} stores one ID, at most $\lceil \log(M_y) \rceil$ KEKs, one secret key, one TEK, and one group key. We can see that in terms of storage, both our proposed protocol and GroupIt have a similar overhead for devices, and depending on the values of $P$ and $Y_x$, GroupIt may marginally outperform the proposed protocol with respect to the costs borne by the users. \subsection{Communication} \label{performance:B} \subsubsection{New User Joining Group SG\textsubscript{x}} Under our proposed protocol, the KDC establishes one secret key with the user, sends one broadcast message for the updation of device keys and the group key of SG\textsubscript{x}, at most $\lceil \log(N_x) \rceil$ multicasts to update KEKs, at most $P$ multicasts to update uKEKs and one unicast to share key material. Under GroupIt, the KDC establishes one secret key with the user, sends one broadcast message to update TEK, at most $\lceil \log(N_x) \rceil$ multicasts to update KEKs and one unicast to share key material. The communication cost under our proposed protocol is higher than that under GroupIt; however, this is because of the provision of backward secrecy under our proposed protocol, but not under GroupIt (see Section~\ref{GroupIt:B}.3). \subsubsection{Existing User Leaving Group SG\textsubscript{x}} Under our proposed protocol, the KDC sends one broadcast message to the devices subscribed to by the leaving user for the updation of device keys, at most $\lceil \log(N_x) \rceil$ multicasts to update KEKs and the group key, at most $P$ multicasts to update uKEKs and $Y\textsubscript{x}P$ multicasts for the updation of device keys with the remaining users. Under GroupIt, the KDC sends at most $\lceil \log(N_x) \rceil$ multicasts to update KEKs and the group key, at most $Y_x M_{max}$ multicasts and $Y_x$ broadcasts for devices subscribed to by the leaving user and users subscribed to those devices to update their TEKs, respectively, and at most $Y_x \log(M_{max})$ multicasts to update device IDs. Hence, the proposed protocol is highly efficient in terms of communication overhead when an existing user leaves. This efficiency further improves if the number of devices within a DG increases or if the SG is subscribed to a large number of DGs. Through our solution, we have also eliminated the possibility of collusion, which exists under the GroupIt protocol (see Section~\ref{SSSC:GroupIt:B:collusion}). \subsubsection{New Device Joining Group DG\textsubscript{y}} Under our proposed protocol, the KDC establishes one secret key with the device, sends one unicast containing the ID and nonce, one multicast for other members of the DG to update the group key, at most $\lceil \log(M_y) \rceil$ multicasts to update KEKs and at most $L_y$ multicasts for delivering the device's key to its subscribed users. Under GroupIt, the KDC establishes one secret key with the device, sends one multicast for other members of the DG to update the group key, at most $\lceil \log(M_y) \rceil$ multicasts to update KEKs, one broadcast containing the device's ID for the subscribed users and one unicast to share key material with the new device. We can see that if $L_y > 1$, then depending on the positions of the SGs subscribed to the DG of the new device in the outer LKH tree, GroupIt may have a lower communication cost in this case as compared to our proposed scheme. \subsubsection{Existing Device Leaving Group DG\textsubscript{y}} Both under our proposed protocol and GroupIt, the KDC sends one broadcast notifying about the exit of the device, and at most $\lceil \log(M_y) \rceil$ multicasts to update the KEKs and group key of the devices in DG\textsubscript{y}. \subsubsection{New User Occupying an Empty SG} Under our proposed protocol, the KDC establishes one secret key with the user, sends one broadcast message for the updation of device keys with the users who have common subscriptions with the new user, at most $P$ multicasts to update uKEKs and one unicast to share key material with the new user. GroupIt does not explicitly handle this scenario. \subsubsection{Existing User Leaves the Last Spot in Group SG\textsubscript{x}} Under our proposed protocol, the KDC sends one broadcast message to the devices subscribed to by the leaving user for the updation of device keys, at most $P$ multicasts to update uKEKs and $Y\textsubscript{x}P$ multicasts for the updation of device keys with the remaining users. Again, GroupIt does not explicitly handle this scenario. \subsubsection{New Device Group DG\textsubscript{y} Joins} We saw earlier that depending on which users subscribe to DG\textsubscript{y}, the communication cost for KEK updates may vary. In the worst case scenario, for a subscriber group SG\textsubscript{x}, of which every alternate member, going from left to right in its inner LKH tree, opts for this subscription, the KDC needs to send $N_x$ unicasts encrypted with the respective shared secret keys, one to each member of the two groups formed after SG\textsubscript{x} splits. The unicasts contain KEKs and group keys for the newly formed SG that does not subscribe to DG\textsubscript{y}, and they contain KEKs, group keys and the new devices' keys for the newly formed SG that subscribes to DG\textsubscript{y}. Additionally, under our proposed protocol, the KDC performs $M_y$ key establishments, one with each of the devices of the new DG, and sends $M_y$ corresponding unicasts containing IDs, nonces, group key and KEKs. GroupIt does not explicitly handle this scenario. \subsubsection{An Existing DG Leaves} Under our proposed protocol, the KDC sends one broadcast notifying about the exit of the DG. For each instance of merging of two SGs, the KDC sends one multicast to the users of the bigger SG to hash their group key, and sends one multicast to the users of the smaller SG containing the new group key. We also observe that the number of uKEK updates required depends on the positions of different SGs in the outer LKH tree, and in the worst case scenario, the KDC sends one multicast to the members of each SG after merging, containing the updated uKEKs encrypted by the respective group keys. As before, GroupIt does not handle this scenario. \subsubsection{Summary} We observe that when a new user joins, our proposed protocol requires more multicasts than GroupIt to update uKEKs, which helps in achieving backward secrecy under our proposed protocol, which is not provided under GroupIt. However, GroupIt is significantly outperformed by our scheme when an existing user leaves, owing to the use of symmetric encryptions under our proposed protocol, unlike under GroupIt, which uses asymmetric encryption. In case of a device joining or leaving, both schemes have similar communication overhead. \subsection{Computation} \label{performance:C} In this section, we analyze the computational costs per user and per device. \subsubsection{New User Joining Group SG\textsubscript{x}} Under our proposed protocol, a device needs to perform one hash to update its device key. Each existing user performs one hash to update the group key, at most $Y_x M_{max}$ hashes to update device keys and two symmetric decryptions to update KEKs and uKEKs, whereas the new user performs one symmetric decryption to get the key material. Under GroupIt, each device needs to perform two hashes to update its device key. Each existing user performs $O(\log(N_x))$ symmetric decryptions to update KEKs, whereas the new user performs one symmetric decryption to get the key material. Hence, our proposed protocol outperforms GroupIt in terms of the computational cost for both devices and users. \subsubsection{Existing User Leaving Group SG\textsubscript{x}} Under our proposed protocol, a device needs to perform one hash to derive the new device key. Each remaining user performs two symmetric decryptions to update KEKs and uKEKs, and $Y_x$ symmetric decryptions to get the updated device keys. Under GroupIt, a device needs to perform two symmetric decryptions and two hashes to derive the device keys. Each remaining user performs two symmetric and one asymmetric decryptions to gain KEKs and update information, and at most $Y_x M_{max}$ hashes to derive the new device keys. It is evident that our proposed protocol significantly improves upon GroupIt in terms of the overhead for devices, and also eliminates the need for asymmetric decryption, which is computationally expensive, for users. \subsubsection{New Device Joining} Under both our proposed protocol and GroupIt, the new device performs one symmetric decryption and one hash to derive its device key, whereas each existing device performs one hash to update the group key and one symmetric decryption to get the updated KEKs. Each subscribed user under our protocol performs one symmetric decryption to get the new device's device key, while it needs to perform an additional hash computation under GroupIt. \subsubsection{Existing Device Leaving} Under both our proposed protocol and GroupIt, each remaining device needs to perform one symmetric decryption to get the updated KEKs and group key, and users need not perform any computation. \subsubsection{New User Occupying an Empty User Group SG\textsubscript{x}} Under our proposed protocol, each device needs to perform one hash to update the device key. Each user having common subscriptions with the new user performs $Y_x M_{max}$ hashes to update device keys and each user in a SG having a common ancestor with SG\textsubscript{x} performs one symmetric decryption to update uKEKs, whereas the new user performs one symmetric decryption to get the key material. GroupIt does not explicitly handle this scenario. \subsubsection{Existing User Leaving the Last Spot in Group SG\textsubscript{x}} Under our proposed protocol, each device needs to perform one hash to derive the new device key. Each user in an SG having a common ancestor with SG\textsubscript{x} performs one symmetric decryption to update uKEKs, and $Y_x$ symmetric decryptions to get the updated device keys. Again, GroupIt does not explicitly handle this scenario. \subsubsection{New DG Joining} Under our proposed protocol, each user that occupies a new leaf node in an inner LKH tree after splitting of an SG performs one symmetric decryption to get the updated KEKs, group keys and new devices' keys (if subscribed). Each device in the new DG needs to perform one symmetric decryption and one hash to get the key material and derive its device key. GroupIt does not handle this scenario. \subsubsection{An Existing DG Leaving} Under our proposed protocol, for every instance of merging of two SGs, each of the users in the bigger SG performs one hash, while each of the users in the smaller SG performs one symmetric decryption to get the new group key. A user needs to perform at most one symmetric decryption to get the updated uKEKs. As before, GroupIt does not handle this scenario. \subsubsection{Summary} Evidently, our proposed scheme outperforms GroupIt in every user join or leave scenario. When a new user joins, our scheme requires only two symmetric decryptions per user, in contrast to GroupIt, for which this number of decryptions scales with $N_x$. When a user leaves, under our proposed protocol, devices need not perform any decryptions, whereas they perform two decryptions each under GroupIt. Users also gain a significant advantage under our proposed protocol since asymmetric decryption is not required. Also, in case of a new device joining, our proposed protocol marginally outperforms GroupIt in terms of the computation costs borne by users. \section{Numerical Results} \label{numerical} In this section, via numerical computations, we compare the performance of our protocol with that of GroupIt for the events of user joining and leaving a group SG\textsubscript{x}, in terms of the communication cost (Section~\ref{numerical:A}) and computation cost (Section~\ref{numerical:B}). Suppose there are $P = 10$ DGs and $Q = 2^P - 1 = 1023$ SGs. Also, suppose each DG contains $M$ devices, each SG contains $N$ users, each SG is subscribed to $Y$ DGs and $L$ SGs are subscribed to each DG. Note that since $Q = 2^P - 1$, the number of SGs subscribed to each DG will be $2^{P-1}$; therefore, $L = 512$. In~\cite{Piedra}, the performances of Advanced Encryption Standard (AES), the SHA-256 cryptographic hash function, and Elliptical Curve Cryptography (ECC) in commercial and research sensor nodes were compared. This study shows that ECC is much more computationally intensive as compared to AES, which is, in turn, more computionally intensive than SHA-256. As in~\cite{Kung}, for concreteness, we assume that hashing (Hash) using SHA-256 takes $T_0 = 460$ ns, encryption (Enc) or decryption (Dec) using AES-256 of block size $64$ takes $T_1 = 800$ ns $=1.74 T_0$, and asymmetric decryption (AsyDec) using ECC-224 takes $T_2 = 114000$ ns $=247.83 T_0$. Note that these absolute values are for a particular processor; however, the relative trends that we observe in the following numerical results hold for other processors as well. \subsection{Communication Cost} \label{numerical:A} We now calculate the number of messages exchanged when a user leaves group SG\textsubscript{x}, as a function of the aforementioned variables. The following equations are derived from Section~\ref{performance:B}.2. First, we fix $N$ = 100 and $M$ = 20, and vary the number of DGs subscribed to by the leaving user ($Y$). Under our proposed scheme, the number of messages exchanged is: \begin{align*} 1\mbox{ Broadcast} + (\lceil \log(N) \rceil + 2P)\mbox{ Multicasts}\\ = 1\mbox{ Broadcast} + 27\mbox{ Multicasts} \end{align*} Under GroupIt, the number of messages exchanged is: \begin{align*} Y\mbox{ Broadcasts} + (\lceil \log(N) \rceil + Y\lceil \log(M) \rceil)\mbox{ Multicasts}\\ + M Y \mbox{ Unicasts}\\ = Y \mbox{ Broadcasts} + (7 + 5 Y)\mbox{ Multicasts} + 20Y\mbox{ Unicasts} \end{align*} The communication costs for both the protocols are depicted in Fig.~\ref{fig15}. Evidently, our scheme outperforms GroupIt as the number of messages required is low and does not depend on the value of $Y$. However, for GroupIt, it increases linearly in $Y$. \begin{figure} \centering \includegraphics[scale=0.65]{fig15_comm_cost_user_leaves.png} \caption{The figure shows the communication costs under GroupIt and the proposed protocol versus the number of DGs subscribed to by the user for the case when a user leaves group SG\textsubscript{x}.} \label{fig15} \end{figure} Next, we fix $Y = 3$ and $M = 20$ and vary $N$. The number of messages exchanged under our proposed scheme is: \begin{align*} 1\mbox{ Broadcast} + (\lceil \log(N) \rceil + 20)\mbox{ Multicasts} \end{align*} The number of messages exchanged under GroupIt is: \begin{align*} 3\mbox{ Broadcasts} + (\lceil \log(N) \rceil + 15)\mbox{ Multicasts} + 60\mbox{ Unicasts} \end{align*} Again, as shown in Fig.~\ref{fig16}, our proposed protocol has lower communication cost than GroupIt. \begin{figure} \centering \includegraphics[scale=0.65]{fig16_comm_cost_user_leaves_2.png} \caption{The figure shows the communication costs under GroupIt and the proposed protocol versus the number of users in group SG\textsubscript{x} for the case when a user leaves group SG\textsubscript{x}.} \label{fig16} \end{figure} Next, we fix $Y = 3$ and $N = 100$ and vary the number of devices in each DG ($M$). Under our proposed protocol, the number of messages exchanged is: \begin{align*} 1\mbox{ Broadcast} + 27\mbox{ Multicasts}. \end{align*} On the other hand, under GroupIt, the number of messages exchanged is: \begin{align*} 3\mbox{ Broadcasts} + (7 + 3\lceil \log(M) \rceil)\mbox{ Multicasts} + 3M\mbox{ Unicasts}. \end{align*} Fig.~\ref{fig17} shows that the communication cost under our proposed protocol does not increase in $M$, whereas that under GroupIt increases in $M$. The cost under our proposed protocol is lower than that under GroupIt when $M$ is sufficiently large. \begin{figure} \centering \includegraphics[scale=0.65]{fig17_comm_cost_user_leaves_3.png} \caption{The figure shows the communication costs under GroupIt and the proposed protocol versus the number of devices in a DG for the case when a user leaves group SG\textsubscript{x}.} \label{fig17} \end{figure} \subsection{Computation Cost} \label{numerical:B} We now study the computational costs borne by users and devices in the network under the proposed protocol and GroupIt when a new user joins and when an existing user leaves. We fix $Y$ = 3 in the rest of this section. The following computational costs are derived from Sections~\ref{performance:C}.1 and~\ref{performance:C}.2. First, when a new user joins SG\textsubscript{x}, the total computational load for all devices under the proposed protocol is: \begin{align*} M Y \mbox{ Hash} = 3T_{0}M \end{align*} For GroupIt, the load is: \begin{align*} 2M Y\mbox{ Hash} = 6T_{0}M \end{align*} Both the above costs are plotted versus $M$ in Fig.~\ref{fig18}. Thus, when a new user joins SG\textsubscript{x}, the computational load for devices under our proposed protocol is half that under GroupIt. \begin{figure} \centering \includegraphics[scale=0.65]{fig18_comp_cost_new_user.png} \caption{The figure shows the total computational load for all devices under GroupIt and the proposed protocol versus the number of devices in a DG for the case when a new user joins.} \label{fig18} \end{figure} Now, when a new user joins SG\textsubscript{x}, the total computational load for all users under our proposed protocol is: \begin{align*} & & L N \mbox{ Hash} + N \mbox{ Hash} + \log(N)\mbox{ Dec} + P\mbox{ Dec}\\ & = & 513T_{0}N + 1.74T_{0} \log(N) + 17.4T_{0}\\ & = & (513N + 1.74 \log(N) + 17.4)T_{0} \end{align*} For GroupIt, the corresponding load is: \begin{align*} & & L N \mbox{ Hash} + L N \mbox{ Hash} + \log(N)\mbox{ Dec}\\ & = & 1024T_{0} N + 1.74T_{0} \log(N)\\ & = & (1024 N + 1.74 \log(N))T_{0} \end{align*} Fig.~\ref{fig19} shows the above costs versus the number of users in a SG ($N$). We can see that for all, except very small values of $N$, our proposed protocol outperforms GroupIt. This advantage increases linearly in $N$. \begin{figure} \centering \includegraphics[scale=0.6]{fig19_comp_cost_new_user_2.png} \caption{The figure shows the total computational load for all users under GroupIt and the proposed protocol versus the number of users in a SG for the case when a new user joins.} \label{fig19} \end{figure} Next, we examine the device computation cost when an existing user leaves SG\textsubscript{x}. Under our proposed protocol, the total computation cost for all devices is: \begin{align*} M Y \mbox{ Hash} = 3T_{0}M \end{align*} Under GroupIt, the corresponding cost is: \begin{align*} & & M Y \mbox{ Dec} + Y \log(M)\mbox{ Dec} + 2M Y \mbox{ Hash}\\ & = & 5.22T_{0}M + 5.22T_{0} \log(M) + 6T_{0}M\\ & = & (11.22M + 5.22 \log(M))T_{0} \end{align*} Fig.~\ref{fig20} shows that our proposed protocol significantly outperforms GroupIt in terms of the total computational load for all devices in the case when a user leaves SG\textsubscript{x}. This is due to the introduction of `nonces' as a part of the device key calculation in our proposed protocol, which eliminates the requirement to perform any decryption operation during device key updates. \begin{figure} \centering \includegraphics[scale=0.65]{fig20_comp_cost_user_leaves_1.png} \caption{The figure shows the total computational load for all devices under GroupIt and the proposed protocol versus the number of devices in a DG for the case when a user leaves SG\textsubscript{x}.} \label{fig20} \end{figure} Finally, we consider the computational load incurred by users when an existing user leaves SG\textsubscript{x}. Under our proposed protocol, the total computational cost incurred by all the users is: \begin{align*} & & \log(N)\mbox{ Dec} + \log(Q)\mbox{ Dec} + M Y L \mbox{ Dec}\\ & = & 6.64\times{1.74T_{0}} + 10\times{1.74T_{0}} + 512\times{3}\times{1.74T_{0}M}\\ & = & (28.95 + 2672.64 M)T_{0} \end{align*} The corresponding cost under GroupIt is: \begin{align*} & & \log(N)\mbox{ Dec} + M Y L \mbox{ Dec} + M Y L \mbox{ AsyDec}\\ & = & 6.64\times{1.74T_{0}} + 1536\times{1.74T_{0}M} + 1536\times{247.83T_{0}M}\\ & = & (11.55 + 383339.52M)T_{0} \end{align*} Fig.~\ref{fig21} shows the total user computation costs under both the schemes for the case when a user leaves SG\textsubscript{x} (note that the $y$-axis is on a log scale). The plot shows that our proposed protocol outperforms GroupIt by several orders of magnitude. This gain is achieved due to the use of symmetric encryptions under our proposed protocol in place of asymmetric double encryption, as well as due to the introduction of the outer LKH tree structure in our protocol. \begin{figure} \centering \includegraphics[scale=0.65]{fig21_comp_cost_user_leaves_2.png} \caption{The figure shows the total computational load for all users under GroupIt and the proposed protocol versus the number of devices in a DG for the case when a user leaves SG\textsubscript{x}.} \label{fig21} \end{figure} \section{Conclusions and Future Work} \label{conclusion} We presented a highly efficient and secure GKM protocol for dynamic IoT settings, which maintains forward and backward secrecy at all times. Our proposed protocol uses only symmetric encryption, and is completely resistant to collusion attacks. Also, our protocol is highly flexible and can handle several new scenarios in which device or user dynamics may take place, e.g., allowing a device group to join or leave the network or creation or dissolution of a user group, which are not handled by the GroupIt scheme. We evaluated the performance of the proposed protocol via extensive mathematical analysis and numerical computations, and showed that it outperforms the GroupIt scheme in terms of the communication and computation costs incurred by users and devices. In this paper, we used the LKH scheme for GKM within SGs and DGs as well as by constructing an outer LKH tree structure, of which all the SGs are a part. One interesting direction for future work is to improve the performance of our proposed protcool by replacing LKH with other GKM schemes proposed in prior work such as OFT, ELK, MARKS etc. \bibliographystyle{ieeetr}
{'timestamp': '2020-08-18T02:16:58', 'yymm': '2008', 'arxiv_id': '2008.06890', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06890'}
arxiv
\section{\label{sec:background}Background} In this section, we provide the following: (1) a definition of the OOD problem and our requirements for a solution, and (2) relevant background on Gaussian distribution use in DNN architectures. \subsection{Problem Formalization} In a DNN classifier without OOD detection capability, there is an underlying assumption that a test sample $x$ is associated with one of the $C$ classes in the training dataset. By denoting the class that $x$ is associated with as $c(x)$, the classification can be expressed as: \begin{equation} \mathop{\mathrm{arg\,max}}_{i\in\{1,\ldots,C\}} p(i|x \wedge \exists j ; c(x) = j) \label{eq1} \end{equation} OOD detection necessitates the option of classifying the input $x$ as none of the learned classes associated with the training dataset. In this case, the classification can be expressed as: \begin{equation} \mathop{\mathrm{arg\,max}}_{i\in\{1,\ldots,C\}\cup\{OOD\}} p(i| x) \label{eq2} \end{equation} \\ We propose a novel OOD detection method that meets the following requirements: \begin{enumerate} \label{restrictions} \item \textit{Fast inference time - } The method must be able to be applied in scenarios where inference time is limited. Therefore, no significant inference time overhead is permitted. \item \textit{In-distribution data only - } The method must only use in-distribution data for training. \end{enumerate} \subsection{Gaussian Distribution in DNN} The multivariate Gaussian function is integrated in DNN methods and architectures in numerous ways~\cite{van2014factoring, wang2017maximum, wan2018rethinking}. For computational reasons, usually the log values of the likelihoods are calculated instead of the likelihoods' values themselves. Given the parameters $\Sigma\in \mathcal{R}^{d\times d}$ and $\mu \in \mathcal{R}^{d}$, it is defined as in~\cite[chap.~3]{anderson1958introduction}: \begin{multline} \log\big(\mathcal{N}(x; \mu,\Sigma) \big) = \\ = -\frac{d}{2}\log(2\pi) -\frac{1}{2}\log(|\Sigma|) -\frac{1}{2}\big\Vert x-\mu \big\Vert^{2}_{{\Sigma}^{-1}} \label{eq3} \end{multline} \\ A Gaussian layer was proposed to improve DNN classification accuracy~\cite{wan2018rethinking} by employing the multivariate Gaussian distribution. Each of the Gaussian layer's outputs corresponds to a density function with respect to the layer's input. The Gaussian layer assumes a multivariate Gaussian distribution on its input, and each of its outputs match the log likelihood, as presented in Equation (\ref{eq3}). In practice, it is based on a DNN architecture in which the classification layer (last fully connected layer) is replaced with a Guassian layer designed for classification. The Gaussian layer contains the trainable parameters that define the distribution of each class. For each class $c$, the layer assigns a score that corresponds to the log likelihood of the penultimate layer's output, modeled as a Gaussian: \begin{equation} log(p(f(x)| c)) = \log\big(\mathcal{N}(f(x); \mu_{c},\Sigma_{c}) \big) \label{eq4} \end{equation} where $\mu_{c}$ and $\Sigma_{c}$ are the layer's parameters for the $c^{th}$ class, and $f(x)$ is the penultimate layer's output. Diagonal covariance matrices are used instead of full covariance matrices, resulting in significantly reduced computational complexity. To train the parameters of the modified DNN, the authors used softmax paired with cross-entropy loss ($\mathcal{L}_{ce}$) on the outputs of the Gaussian layer. In addition to $\mathcal{L}_{ce}$, a regularization term that maximizes the likelihood of the correct output is employed. Given a sample $\{x_{i},y_{i}\}_{i=1}^{m}$(where $m$ is the sample size), the regularization term is defined as: \begin{multline} \mathcal{R}_{ML}=-\log(p(\{f(x_{i}), y_{i}\}_{i=1}^m ;\{\Sigma_{c}, \mu_{c}\}_{c=1}^{C})) = \\ = -\frac{1}{m}\sum_{c=1}^{C}\sum_{i=1}^{m}\mathrm{1}_{c=y_{i}}\cdot \log(\mathcal{N}(f(x);\mu_{c}, \Sigma_{c})) \label{eq5} \end{multline} The model optimization target $\mathcal{L}$ can be summarized as: \begin{equation} \mathcal{L} = \mathcal{L}_{ce}+\lambda\mathcal{R}_{ML} \label{eq6} \end{equation} where $\lambda$ is a hyperparameter chosen using a validation set. \section{Conclusion} In this paper, we addressed the OOD detection problem from a real-world application perspective. We introduced FOOD, an OOD detector method with state-of-the-art OOD detection performance and fast inference time that does not require additional training data. To the best of our knowledge, this is the first paper to compare the inference time of state-of-the-art OOD detection methods. Our OOD detection performance evaluations demonstrate that FOOD outperforms the other fast state-of-the-art OOD detectors. This makes FOOD more suitable for real-world applications than other OOD detection methods. Our method for generating OOD samples captures the perceived boundaries of the training data from the DNN perspective. Thus, beyond generating artificial OOD data, it can be used for data augmentation, enabling samples to be generated in a deliberate manner. Moreover, we hypothesize that other OOD detection methods can employ our data generation process to eliminate the need to acquire OOD data. In future work, we plan to evaluate FOOD in conjunction with unsupervised learning methods to enhance the representations learned by the model. \section{Experimental setup} In this section, we provide details about our experimental process, evaluation measures, and datasets. We evaluate FOOD's capabilities using three image datasets: CIFAR-10, CIFAR-100, and SVHN, which are considered the standard datasets for OOD detection. The datasets that the networks train on (in-distribution) are considered the positive class, and the OOD benchmarks, including LSUN, iSUN, and Tiny ImageNet, are considered the negative class (out-of-distribution). We evaluate the proposed methods using the following commonly used metrics: \begin{itemize} \item TNR95: The true negative rate (TNR) when the true positive rate (TPR) is 95\%, which is a measure of how many OOD samples are detected correctly when we set the threshold so that the detector detects 5\% of the in-distribution as OOD. \item AUROC: The area under the receiver operating characteristic curve, which is a measure of performance for the detector over all possible detection thresholds. \item Detection accuracy: The overall detection accuracy when adjusting the threshold for maximum detection between in-distribution samples and OOD samples. \end{itemize} We performed our evaluation using the PyTorch deep learning framework on a NVIDIA 2080 Ti GPU. For the evaluation of FOOD's OOD detection performance, we trained five Resnet34 and five Resnet18\cite{he2016deep} models for each in-distribution dataset. Each model was fine-tuned to have a Gaussian final layer, as presented in Equation~\ref{eq7}. As for optimization, we trained the models using SGD with a learning rate of $0.1$, momentum of $0.9$, and weight decay of $0.5e-4$. For the fine-tuning process, we used the RMSprop optimizer with a learning rate of $0.0001$ and selected the value for $\lambda$ ($\mathcal{R}_{ML}$ coefficient) using the validation set. All of the other methods examined in our evaluation were implemented in PyTorch using the authors' code when possible. For G.ODIN, MD, and MD*, we implemented the code ourselves. All methods (including ours) were based on the same 10 Resnet models. (r) postfix denotes that the mentioned dataset was used in its resized version. Our code can be found on GitHub, along with the evaluation scripts of the other methods.\footnote{https://github.com/guyAmit/GLOD } \section{\label{sec:intro}Introduction} Deep neural networks (DNNs) have been successfully used in many classification tasks in various domains, including computer vision~\cite{xu2015show}, autonomous driving~\cite{Bojarski2016EndTE} and speech recognition~\cite{lecun2015deep}. While capable of learning complex patterns, DNNs are limited in their ability to correctly classify samples that are not associated with any of the training data classes. Such samples are known as out-of-distribution (OOD) samples, and they have been identified as a major risk in AI~\cite{amodei2016concrete,mohseni2019practical}. The capability of detecting that a sample is OOD is even more significant in safety-critical systems, such as autonomous driving systems. What makes autonomous driving systems particularly challenging for OOD detection is that significant operational overhead cannot be tolerated, and the consequences of an error are severe~\cite{mohseni2019practical}. Previous studies addressed the OOD challenge with various real-world design considerations. Some studies suggested OOD detection models that perform fast inference~\cite{mohseni2020self,hendrycks2018deep}, however the proposed detection models depend on access to OOD samples for training, which may not be possible in real-world applications. In addition, the OOD samples used for training may not be representative, and thus the OOD detector cannot generalize well on unexpected inputs~\cite{shafaei2019less}. There are methods that refrain from using OOD samples to train their models~\cite{hsu2020generalized,sastry2019detecting}, however those models suffer from increased inference time. To both achieve fast inference and eliminate the need to acquire OOD samples for training, we designed our method guided by two assumptions: (1) The inherent OOD detection capability in a DNN is enhanced when it is trained to model the in-distribution classes as density functions. (2) The density functions can be exploited to simulate the behavior of the DNN when encountering OOD samples. We propose FOOD -- Fast Out-of-Distribution Detector, a DNN model featuring a final Gaussian~\cite{wan2018rethinking} layer that models a density function for each class. Using a log likelihood ratio statistical test on the outputs of the Gaussian layer, we generate samples that are perceived as OOD by the DNN. We employ those samples to train our OOD detector, which is implemented as an additional output neuron. \textbf{Contributions.} We introduce FOOD, a fast OOD detector that does not require OOD samples for training or hyperparameter tuning. We perform an inference time comparison, showing that current state-of-the-art methods suffer from a trade-off between inference time overhead and OOD detection performance. We evaluate FOOD on commonly used benchmark datasets for OOD detection: SVHN~\cite{netzer2011reading}, CIFAR-10~\cite{krizhevsky2009learning}, and CIFAR-100~\cite{krizhevsky2009learning}. Our evaluation demonstrates FOOD's state-of-the-art results, and our inference time comparison indicates that these results do not come at the cost of inference time overhead, which is minimal. Our contributions can be summed up as follows: \begin{enumerate} \item A fast OOD detection method that achieves state-of-the-art performance without the need for OOD data for training. \item A novel method for generating samples that are perceived by the DNN as OOD; this data generation process is insensitive to manual parameter choices and does not require adjustments when used on different datasets. \end{enumerate} \section{Approach} In this section, we introduce FOOD - Fast OOD Detector. We start by presenting the high-level steps of the method's training, and then we describe each of the components of our method in detail. The high-level steps for training FOOD are: (1) adjust the DNN for OOD detection by replacing its final layer with a Gaussian~\cite{wan2018rethinking} based one, (2) generate adversarial samples which serve as artificial OOD samples, (3) extract the internal representations of the artificial OOD samples and the in-distribution training samples from the DNN, (4) use the internal representations to train a logistic regression classifier that acts as an OOD detector; when the OOD detector is trained, the training samples are labeled as in-distribution, and the artificial OOD samples are labeled as OOD. \subsection{Architecture \& Training} \label{architecture} Because of the \textit{Fast inference time} requirement, we developed a detection method that can be implemented efficiently as part of the DNN, without additional processing. In the typical DNN classifier architecture, the final layer usually consists of linear transformation (a fully connected layer) and a softmax activation. The softmax output can technically be employed as a density function, however studies have shown that the OOD detection capabilities of softmax are limited, and more sophisticated methods can surpass its OOD detection performance~ \cite{liang2018enhancing, DBLP:conf/iclr/HendrycksG17}. Instead of using the softmax output, in this research we focus on the internal representations of the DNN, particularly the penultimate representation. In prior research, representation analyses were performed to explain the relations in the geometric nature of DNN's internal representations~\cite{katzir2019detecting, mahalanobis}. Those analyses showed that the samples of each class are naturally grouped in the internal representations, creating a clustering effect. The deeper the layer is, the more obvious the clustering effect becomes, resulting in a complete separation between the classes in the penultimate representation. This finding indicates that the penultimate layer has the potential to serve as the input to a density function. We developed our architecture based on a method that employs a Gaussian layer as its final layer, instead of a fully connected one~\cite{wan2018rethinking}. The Gaussian layer models each class ($c$) as a multivariate Gaussian, with its own trainable parameters - a positive semi-definite covariance matrix ($\Sigma_{c}\in \mathbb{R}^{d \times d}$) and a center vector ($\mu_{c}\in \mathbb{R}^{d}$). Since the likelihood term in the Gaussian layer (Equation \ref{eq3}) involves the calculation of $\log(|\Sigma_{c}|)$ and ${\Sigma^{-1}_{c}}$, diagonal covariance matrices are used to improve numerical stability. Moreover, it allows efficient paralleled computation of the Gaussian's log likelihood. Note that in our implementation, the covariance matrix is learned during training, in contrast to some other methods that employ Gaussians~\cite{yaseen2020preventing}. For simplicity, and unlike the procedure proposed in the original paper that introduced the Gaussian layer~\cite{wan2018rethinking}, we do not train our DNN from scratch, but rather fine-tune an existing trained DNN model. We replace its last layer with a Gaussian one and then initialize the layer parameters manually, using their statistical estimations from the training data penultimate representation. The calculation is performed as follows: \begin{equation} \mu_{c} = \frac{1}{|S_{c}|}\sum_{x\in S_{c}} f(x) \end{equation} \begin{equation} \Sigma_{c} = \frac{1}{|S_{c}|}\sum_{x\in S_{c}} (\mu_{c} -f(x))(\mu_{c} -f(x))^T \end{equation} \label{eq7} where $S_{c}$ is the set which contains all of the samples from class $c$, $f(x)$ is the penultimate representation of $x$, and $\mu_{c}$ and $\Sigma_{c}$ are the layer parameters for class $c$. After the layer's parameters are set, we fine-tune the model for 15 epochs using Equation (\ref{eq6}) as the optimization target. We stop the fine-tuning process when the validation loss starts to increase. \subsection{Gaussian-Based Log Likelihood Ratio (LLR)} The proposed DNN architecture outputs proper density values that correspond to the log likelihood of the classes' Gaussians in the penultimate representation. Taking advantage of this property, we perform the $\mathcal{LLR}$ test on the Gaussians' log likelihood values. We define two scores, the predicted class ($p_{pred}$) log likelihood and the log likelihood average over the other classes ($p_{other}$): \begin{equation} p_{pred}(x) = \max_{c\in \{1,\ldots, C\}} \log(\mathcal{N}(f(x); \mu_{c}, \Sigma_{c})) \end{equation} \begin{equation} p_{other}(x) = \frac{1}{C-1}\sum_{\substack{c'\neq c \\ c'\in \{1,\ldots,C\} }} \log(\mathcal{N}(f(x); \mu_{c'}, \Sigma_{c'})) \end{equation} We define the $\mathcal{LLR}$ score as: \begin{equation} \mathcal{LLR}(x) =p_{pred}(x)-p_{other}(x) \label{LLR} \end{equation} where $C$ is the number of classes, $x$ is the input sample, and $f(x)$ is the penultimate representation of $x$. We explain the $\mathcal{LLR}$ terms as follows: $p_{pred}$ is the log likelihood of a sample to be in the in-class distribution, and $p_{other}$ is the log likelihood of a sample to be out of the predicted class distribution. The $\mathcal{LLR}$ (on its own) can serve as a basic and efficient score for OOD detection (Table~\ref{table:ablation}) that does not require proprietary tuning. In-distribution samples have higher $\mathcal{LLR}$ values, while OOD samples have lower $\mathcal{LLR}$ values, allowing them to be differentiated from one another. \subsection{Artificial OOD Crafting} \label{mimicing OOD} One of the challenges that arises when creating an OOD detector is tuning it. To address this challenge without additional data sources, we developed a novel method to generate artificial OOD samples that can be used to train an OOD detector. We employ an adversarial crafting method to generate artificial OOD samples. Given the training set samples (in-distribtion data), one can observe that some training samples have higher $\mathcal{LLR}$ values than others (Figure \ref{fig:LLR_dist}). This implies that there are samples which are more likely to be associated with in-distribution samples than others. It is possible to use those values in order to estimate the boundaries of the in-distribution data. We estimate the boundary of the in-distribution data as the lower 95th percentile of the in-distribution data's $\mathcal{LLR}$ values; we refer to it as $Thres$. We use an adversarial sample crafting method to alter the samples, such that their $\mathcal{LLR}$ values are lower than $Thres$, making those samples less likely to be associated with in-distribution data. We utilize the $LLR$ as the loss target when crafting the adversarial samples, iteratively altering the samples towards a lower $LLR$ value until $Thres$ is reached. The data used to perform this operation is a subset of the training data that was not used during training (a validation set); the algorithm is described in Algorithm~\ref{alg: gen}. \begin{algorithm}[t] \small \scalebox{0.9}{ \begin{minipage}{0.92\linewidth} \label{Alg:Evolutionary_general} \begin{algorithmic}[0] \Procedure{Generate Sample}{x, $\epsilon$} \\ \hspace*{\algorithmicindent} \textbf{Input}: $x$ - an input sample and $\epsilon$ - a step size \\ \hspace*{\algorithmicindent} \textbf{Output}: $x_{art}$ an artificial OOD sample \\ \State $x_{art}\leftarrow x$ \For{$i \leq MaxIter$}\\ \hspace*{\algorithmicindent} \#\textit{Add a perturbation} \State $x_{art}~\leftarrow~ x_{art}-\epsilon \nabla_{x} \mathcal{LLR} ( x_{art} ) $\\ \hspace*{\algorithmicindent} \#\textit{Clip to maintain valid image range} \State $x_{art}~\leftarrow~clip(x_{art})$ \\ \hspace*{\algorithmicindent} \#\textit{Stopping criteria} \If{ $\mathcal{LLR}(x_{art}) \leq Thres$ } \State Stop \EndIf \EndFor \EndProcedure \caption{\label{alg: gen} } \end{algorithmic} \end{minipage} } \end{algorithm} $MaxIter$ was set at 10, because in most cases, the algorithm reaches its stopping criteria after 1-4 iterations. The $\epsilon$ was not tuned based on OOD samples and was set to $0.01$ in all of our evaluations. $Thres$ determines how large the perturbation will be for each sample, and it is calculated using only the in-distribution data. This eliminates the need to acquire OOD samples prior to tuning our detector. A sensitivity analysis is presented in Table~\ref{table:sensitivity}, showing that $\epsilon$ and $Thres$ are insensitive to changes. \subsection{Internal DNN Representation Feature Extraction} \label{internal} The internal DNN representations, which are the outputs of each layer's activation, are commonly used as input features for OOD detectors~\cite{mahalanobis, chen2020robust, sastry2019detecting}. We were inspired by those studies and combined this approach with the maximum likelihood approach. We extract the likelihood of the most likely class in each of the internal representations of the DNN and use it as features. In order to perform the likelihood calculation in each representation, we assume that the samples of each class are distributed as a Gaussian. Under this assumption, we empirically estimate the parameters for the Gaussians (mean vector and diagonal covariance matrix) using the training data, as in Equation \eqref{eq3}. To reduce the dimensionality, we apply a pooling function on the representations, instead of using the representations themselves. Unlike other OOD detection methods that only use average pooling over all representations, we use different pooling operations for different representations. Given a dataset, a sample $x$, and a DNN classifier of $C$ classes with $L+1$ hidden layers, for layers' representations $l \in \{1,\ldots, \frac{L}{2} \}$, we perform max pooling, and for $l \in \{\frac{L}{2}+1,\ldots, L\}$, we use average pooling. This modification was made because the clustering effect is more prominent in the deeper representations~\cite{katzir2019detecting}, and thus we assume that less noise reduction is required to extract useful information from them (i.e., average pooling can be used instead of max pooling). Note that the feature extraction does not include the penultimate layer. Our feature extraction algorithm does the following \begin{equation} F(x, l) = \max_{c \in \{1, \ldots, C\}} \log\big(\mathcal{N}(f^{[l]}(x); \mu^{[l]}_{c},\Sigma^{[l]}_{c}) \big) \label{eq8} \end{equation} where $F(x, l)$ is the feature extracted from layer $l$, i.e., the maximum log likelihood (Equation \ref{eq3}) estimated for a sample $x$ to belong to a certain class in the representation of layer $l$, using the diagonal covariance matrix $\Sigma^{[l]}_{c}$ and the mean vector $\mu^{[l]}_{c}$. $f^{[l]}(\cdot) \in\mathbb{R}^{d}$ is the output of the $l^{th}$ layer, $l\in \{1,\ldots, L\}$. \subsection{OOD Detection} \label{Detection} The artificial OOD samples generated ~(\ref{alg: gen}) allow us to use a supervised learning classifier that differentiates between OOD samples and in-distribution samples. We train our classifier with artificial OOD samples labeled as OOD and a subset of the training data which was not used for the DNN training, which is labeled as in-distribution (the same samples that were used for the artificial OOD samples generation). To achieve minimal inference time overhead, we employ a logistic regression classifier, implemented as an output neuron in the DNN, as our OOD detector. Given a sample $x$, the input to the detector is the internal representation features, as presented in Equation (\ref{eq8}), $ \{F(x, l)\}_{l=1}^{L}$, and the $\mathcal{LLR}$ presented in Equation (\ref{LLR}). The score function of the logistic regression classifier is: \begin{equation} score(x) = \sigma\big(\sum_{l=1}^{L} w_{l}\cdot F(x, l) + w_{L+1}\cdot \mathcal{LLR}(x) \big) \label{eq9} \end{equation} where $\sigma$ is the sigmoid function, and the $w_{l}$ are the weights of the logistic regression classifier. \section{\label{sec:relatedworks}Related Work} In this section, we (1) present methods from the field of OOD detection, (2) discuss how the methods meet the requirements presented in Section \ref{restrictions}, and (3) discuss the use of adversarial samples in OOD detection. \subsection{OOD Detection Methods for Comparison} \textbf{Max Softmax Probability (MSP)}~\cite{DBLP:conf/iclr/HendrycksG17} \label{ref:MSP} - A baseline for OOD detection. It employs the predicted maximum class probability as a score to separate OOD samples from in-distribution samples. \textbf{Mahalanobis Distance (MD)}~\cite{mahalanobis} - Based on analysis of DNN hidden representations and input preprocessing. This method operates under the assumption that in each layer's representation, the samples of each class are distributed as a Gaussian. Each Gaussian is parameterized by a center vector and a shared full covariance (all classes share one covariance matrix). The score for OOD detection is a weighted sum over the Mahalanobis distance calculated in each layer, whose weights are learned using OOD samples. The authors of \cite{hsu2020generalized} proposed a modification of this method, in which input preprocessing is not performed, and a simple sum is used instead of a weighted sum; we denote this method as MD*. \textbf{Outlier Exposer (OE)}~\cite{hendrycks2018deep} - A detection method in which the DNN is fine-tuned using OOD samples that are not from the OOD test dataset. OE optimizes a loss function which includes an additional term, forcing the DNN to output equal predictions for all classes when encountering an OOD sample. On inference, the MSP score is used for OOD detection. \textbf{Generalized Odin (G.ODIN)}~\cite{hsu2020generalized} - A detection method built upon the Odin method \cite{liang2018enhancing}, eliminating its need for OOD samples. Its architecture is comprised of temperature scaling and modification of the softmax function. During inference, G.ODIN uses input preprocessing to craft an adversarial sample from the input. The predicted maximum class probability of the output is used as the score for OOD detection. \textbf{Self-Supervised Learning for OOD detection (SSL)}~\cite{mohseni2020self} - A detection method in which the last layer of the DNN is extended with several additional neurons that are trained using OOD samples (not from the OOD test dataset). The additional neurons are trained using an proprietary loss function, and their sum is used as a score for OOD detection. \textbf{Gram matrices (GM)}~\cite{sastry2019detecting} - A detection method in which the correlation between different features in each layer's representation is extensively analyzed. Given a representation $F_{l}$ for layer $l$ and a maximal order $P$, the Gram matrix measure includes the calculation of the higher order Gram matrices: $(F_l^p F_{l}^{p^{T}})^{\frac{1}{p}}$, for $p\in\{1,\ldots, P\}$, where the power and root are element-wise operations. The deviation from the Gram matrix measure of the training data is used for OOD detection. \textbf{MALCOM}~\cite{chen2020robust} - A detection method that maps the internal representations to the string domain. In the string domain, a file compression technique is used to extract uncorrelated features from the DNN, which then serve as input to the most basic version of the MD method~\cite{mahalanobis}. \subsection{Requirement Compliance Comparison} \label{Considerations_Comparison} \input{tables/table1} In Table~\ref{table1:comperison}, we present a comparison of the various OOD methods with respect to our requirements, as specified in Section ~\ref{restrictions}. MSP~\cite{DBLP:conf/iclr/HendrycksG17} only relies on the DNN's original output which was trained without any OOD data, so it meets the \textit{In-distribution data only} requirement. The output is used directly, and therefore it complies with the \textit{Fast inference time} requirement as well. MD~\cite{mahalanobis} and G.ODIN~\cite{hsu2020generalized} employ preprocessing to craft a perturbation of the input, which incurs significant inference time overhead, so they do not meet the \textit{Fast inference time} requirement. MD also employs OOD samples to tune the OOD detection model, so it fails to comply with \textit{In-distribution data only}. However, MD* does not require OOD samples or perform input preprocessing, meaning that this modified version of MD meets both of our requirements. The SSL~\cite{mohseni2020self} and OE~\cite{hendrycks2018deep} methods are trained on OOD samples (not from the OOD test data), meaning that they fail to meet the \textit{In-distribution data only} requirement. The MALCOM~\cite{chen2020robust} detection method is based on file compression techniques, which appear complicated but can be implemented efficiently, and since it does not rely on OOD samples, it complies with both of our requirements. The GM~\cite{sastry2019detecting} method uses complex postprocessing calculations after the inference process has been performed. This postprocess increases inference time, as shown in the Results section (Figure~\ref{fig:Speed_comparison}); therefore, it does not comply with the \textit{Fast inference time} requirement. \subsection{Adversarial Methods in OOD Detection} Adversarial samples are in-distribution samples that have been carefully perturbed to shift their DNN prediction from the correct class to an incorrect one~\cite{szagdi}. There are different methods of crafting adversarial samples~\cite{Goodfellow2015ExplainingAH, carlini2017towards, akhtar2018threat}, each of which requires a different set of hyperparameters. Those hyperparameters guide the way in which the perturbation is crafted. The same techniques can be used to achieve the opposite effect (i.e., to strengthen the confidence of the DNN's prediction in the correct class). In general, it is possible to perturb the sample towards any direction of a differentiable score calculated by the DNN. There are two main approaches in which OOD detection methods take advantage of adversarial methods: In the first approach, it is assumed that adversarial perturbations have a different effect on OOD samples than on in-distribution samples. Based on this assumption, during inference, some OOD detection methods craft an adversarial sample out of the input sample in order to enhance OOD detection~\cite{mahalanobis, liang2018enhancing, hsu2020generalized}. Each method crafts the perturbation according to its OOD detection score. In general, given a score $\mathcal{D}(\cdot)$, an input $x$, and a perturbation size $\epsilon$, the perturbed input $x_{per}$ is calculated as follows: \begin{equation} x_{per} = x \pm \epsilon\cdot\frac{\partial \mathcal{D}(x)}{\partial x} \end{equation} The perturbation is either added or subtracted from the original $x$. Finally, the value of $\mathcal{D}(x_{per})$ is used for OOD detection. Another approach for using adversarial samples in OOD detection is to replace the OOD samples used in the training phase. In the paper proposing MD~\cite{mahalanobis}, the authors presented a version of MD that uses adversarial samples instead of OOD samples during the training phase. However, this MD version obtained suboptimal OOD detection results. \section{Results} \subsection{Method Analysis} \subsubsection{Ablation Study} \input{tables/table2} In Table \ref{table:ablation}, we evaluate the contribution of each of FOOD's stages to the overall method. The stages appear in the \textit{Method} column in the table. We present the simple MSP method \cite{he2016deep} as a baseline and the stages of our method are presented below it. The first stage is $\mathcal{LLR}$ (stage 1), which uses a DNN whose final layer was replaced with a Gaussian layer. To evaluate the OOD detection of this stage, we use the $\mathcal{LLR}$ value for OOD detection. The next stage is \textit{likelihoods sum + $\mathcal{LLR}$} (stage 2), which adds the sum of the likelihoods of the different representations, as presented in Section \ref{internal}. At this stage, the method uses only average pooling on the internal representations for dimensionality reduction, before calculating the likelihood. This stage uses the sum of the likelihoods from each internal representation and the LLR score from the final layer as a score for OOD detection. Stage 3 introduces the logistic regression classifier (as presented in Section \ref{Detection}), where different weights are assigned to each likelihood value of the different representations, instead of simply summing them. The only difference between this stage and the final version is the pooling method employed. Finally, we present the full version of our method (stage 4). We can see that in stage 1 the $\mathcal{LLR}$ obtains substantially better results compared to the MSP, implying that the $\mathcal{LLR}$ can be used as a preliminary OOD detection score. In stage 2 the performance is further improved, suggesting that the use of internal representations benefits OOD detection. An even more substantial improvement appears in stage 3 where almost all of the tests show a 20\% performance gain for the TNR95 metric. This reflects the critical improvement obtained by tuning the detector according to the artificial OOD samples (Section \ref{mimicing OOD}). Finally, in stage 4, we see the addition of mixed pooling, which improves the performance on most datasets. Although the value of the TNR95 metric decreases on the SVHN dataset, the AUROC improves from stage 3 to stage 4 on this dataset. Overall, the mixed pooling is better when considering the OOD detection results in an aggregative manner over the different thresholds. This indicates that our claim that less noise reduction is needed in deeper layers is correct. \\ \subsubsection{Generating Artificial OOD Samples} \begin{figure}[t] \centering \includegraphics[width=8cm]{images/In_vs_art.png} \caption{LLR values; CIFAR100 in-distribution training samples (blue) vs generated OOD samples (orange) crafted from the CIFAR100 model.} \label{fig:LLR_dist} \end{figure} To qualitatively demonstrate the effectiveness of the conversion of in-distribution samples to artificial OOD samples (Section \ref{mimicing OOD}), we measured the $\mathcal{LLR}$ values of each sample before and after converting it into its artificial OOD version. Figure \ref{fig:LLR_dist} presents how the samples behave in terms of the $\mathcal{LLR}$ value. The $\mathcal{LLR}$ values of the vanilla samples from the CIFAR100 validation dataset appear in blue, and the $\mathcal{LLR}$ values of converted samples created from the same samples appear in orange. As shown in the figure, after conversion, almost all of the samples obtain an $\mathcal{LLR}$ value lower than the 95th percentile bound (as presented in Section \ref{mimicing OOD}). \\ \subsubsection{Sensitivity Analysis} \input{tables/table4} In this subsection, we show that FOOD's artificial OOD generation method is resilient to to the choice of its hyperparameters, namely the step size $\epsilon$ and the threshold $Thres$. Table~\ref{table:sensitivity} presents the detection results for a range of hyperparameters choices. As shown in the table, the detection measures are not significantly affected by different hyperparameters choices. This shows that the $\epsilon$ and $Thres$ hyperparamters are not sensitive to changes within a reasonable range. \subsection{Inference Time Comparison} \begin{figure}[b] \centering \includegraphics[width=9cm]{images/Method_speed_comp.png} \caption{Inference time comparison (times measured for the DNN inference and OOD detection combined); all methods' inference times were measured on the CIFAR100 dataset with five different Resnet34 models and averaged.} \label{fig:Speed_comparison} \end{figure} Figure \ref{fig:Speed_comparison}, which provides a comparison of the inference times of state-of-the-art OOD detection methods, shows that there is a large variation between the methods. Unsurprisingly, methods that rely on MSP had the fastest inference time, as the only calculation required for them is the feedforward operation. FOOD's inference time is similar to those methods and is also the fastest of all of the methods that do not require OOD samples for training. MD* is a little slower; this can be explained by the use of full covariance matrices in this method, as opposed to FOOD which uses diagonal covariance matrices. We observe that methods which require adversarial preprocessing (e.g., G.ODIN, MD) are more than four times slower than FOOD, as they require backpropagation in order to edit the sample before inference. GM requires complicated postprocessing, causing its run to take the longest of the methods examined. Figure~\ref{fig:SpeedVsTNR} shows the trade-off between OOD detection performance and inference time for different methods, evaluating the TNR95 metric against the speed. The figure shows that methods that are both fast and accurate tend to appear closer to the top right corner, whereas methods with suboptimal detection performance or a long inference time appear respectively more to the left and closer to the $Speed$ axis. As seen in the plot, FOOD's inference time is faster than almost all the other methods, while maintaining high OOD detection capabilities. Methods that obtain higher TNR95 scores run significantly slower, and in the case of MD, use OOD samples for tuning. In addition, it is easy to see that methods which have a faster inference time than FOOD (i.e., OE, and SSL) have significantly lower OOD detection performance. \subsection{OOD Detection Performance Comparison} \input{tables/table3} Table \ref{table:main} presents a comprehensive OOD detection performance comparison of methods that meet the \textit{Fast Inference Time} requirement (Section \ref{restrictions}). As seen in the table, FOOD consistently obtains better results on the TNR95 metric, outperforming the other methods on all datasets on this metric. The smallest gap in performance was seen on the SVHN dataset, although the other metrics (AUROC and detection accuracy) indicate that there is a significant difference between the methods on that dataset as well. The most substantial performance gap between the methods examined is seen on the CIFAR100 dataset. DNN classification performance on CIFAR100 tend to be much lower than CIFAR10 and SVHN, this can affect the OOD detector's performance. We observe that the results obtained by FOOD and MALCOM (the method achieving the second best OOD detection results) for the TNR95 metric on the CIFAR100 dataset are respectively $88.9$ (on average) and $75.2$. Resnet18-based models showed similar trends; on the CIFAR100 dataset, the results for the TNR95 metric are $91$ (on average) for FOOD and $76.9$ for MALCOM, which again has the second best OOD detection results. Due to space limitations, we cannot present the full evaluation of the methods based on Resnet18. \begin{figure}[b] \centering \includegraphics[width=8cm]{images/SpeedVSTNR.png} \caption{${Speed}$ vs $TNR95$ comparison (times measured for the DNN inference and the OOD detection combined); all methods' inference times and OOD detection performance were measured on the CIFAR100 dataset with five different ResNet34 models and averaged.} \label{fig:SpeedVsTNR} \end{figure}
{'timestamp': '2021-02-24T02:26:04', 'yymm': '2008', 'arxiv_id': '2008.06856', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06856'}
arxiv
\section{Introduction} \label{sec:intro} Advances in deep learning techniques have brought about remarkable progress in many computer vision tasks such as detection, segmentation, tracking, and recognition. One major caveat with most deep learning algorithms is that they need to be trained with a huge amount of data that have been carefully labeled with ground truth~\cite{Everingham:2015:PVO:2725268.2725369,DBLP:journals/corr/LinMBHPRDZ14,DBLP:journals/corr/ZhouZPFBT16}. Furthermore, in many applications such as autonomous driving, visual analysis has to be done on every captured frame for real-time processing or for tasks that require dense spatio-temporal information. For these, dense per-frame region-level annotation becomes essential for training the models. Manually annotating detailed region boundaries for every video frame is a highly time-consuming, tedious, if not impossible, task. To our best knowledge, no publicly available dataset offers per-frame annotation. The lack of densely annotated video data has limited the research on detailed region-level video analysis and have forced researchers to explore image-based models instead. Frame-wise processing, however, misses the spatial-temporal relationships and can lead to inferior results. As such, dense per-frame region annotation with an affordable and efficient means becomes critical. Bounding box is a widely used and rather cheap supervision. What if we only need annotators to provide region bounding boxes for sparsely chosen keyframes and then the annotation tool automatically generates boundaries for the region of interest in every frame, as illustrated in Figure \ref{fig:teaser}? We introduce a novel dense video annotation method that only requires sparse bounding-box supervision. We fit an iteratively deforming volumetric graph to the video sub-sequence bounded by two chosen keyframes, so that its uniformly initialized graph nodes gradually move to the key points on the sequence of region boundaries. The model consists of a set of deep neural networks, including normal convolutional networks for frame-wise feature map extraction and a volumetric graph convolutional network for iterative boundary point finding. By propagating and integrating node-associated information (sampled from feature maps) over graph edges, a content-agnostic prediction model is learned for estimating graph node location shifts. The effectiveness and superiority of the proposed model and its major components are demonstrated on two latest public datasets: a large synthetic dataset Synthia and a real dataset named KITTI-MOTS capturing natural driving scenes. \if 0 This paper makes the following technical contributions. \begin{itemize \item \emph{A novel semi-automatic video region annotation tool} for efficiently building datasets with densely-annotated region masks/boundaries. The only inputs from human annotators for each sequence are bounding boxes of target regions on sparse keyframes. \item The method integrates spatial and temporal information for iteratively finding globally optimized region boundaries with \emph{a single Graph Convolutional Network-based model}. \item The method allows training with sparse ground-truth supervision and can easily adapt to an arbitrary new dataset. \end{itemize} \fi \section{Related Work} \paragraph{Region Annotation vs. Segmentation} Since one can easily get confused by the relationship between our work and large amounts of existing works on segmentation tasks (including semantic segmentation \cite{J.Li2019,Ding2019,Paul2019,Seyed2018}, object segmentation \cite{jain2017fusionseg}, and instance segmentation \cite{VIS2019}), we first clarify the difference. Annotation is the process of labeling data to be used for machine learning algorithms, including training and evaluation. Whilst there have been many studies in learning from unlabeled data \cite{Cho_2015_CVPR,Wang_2015_ICCV,Lee_2017_ICCV}, many state-of-the-art algorithms still need some sort of labeled data for training, and in any case quantitative performance evaluation generally requires ground-truth labels. On the other hand, segmentation is the process of predicting pixel-level class labels. The main difference between annotation and segmentation is that \emph{annotation is for building a dataset whilst segmentation is a vision task model trained on an annotated dataset. As such, any segmentation method would benefit from a better annotated data and hence the annotation tool}. This work focuses on region annotation for videos, aiming to alleviate the burden of the annotator to help make the process of creating ground truth data easier, and thus support the development of new video analysis models, including those for image/video based segmentation. \paragraph{Single-Image Annotation Tools} In general, one can still choose to annotate each frame using image annotation tools. Representative works are briefly discussed here. One of the earliest annotation tool that aimed to cut down the time required to annotate was GrabCut \cite{GrabCut} which does interactive foreground/background segmentation in still images using bounding boxes and foreground and background marking strokes as its inputs. Polygon-RNN \cite{PolyRNN} and Polygon-RNN++ \cite{acuna2018efficient} use a CNN-RNN architecture to sequentially trace object boundaries given a bounding box. The RNN can only output one vertex at a time which could mean slow inference time depending on the number of vertices to be inferred. In subsequent work, Curve-GCN \cite{Curve-GCN-CVPR19} attempts to get around this limitation by modeling object annotation as a boundary control point regression problem and using graph convolutions to do the joint regression for all the control points (i.e., graph nodes). It was demonstrated to be faster and also more effective than Polygon-RNN. Since these models/tools do not use temporal information among successive frames, simply extending them for the desired video region annotation task is likely to be inferior than our proposed solution. To demonstrate it, we build two extensions of the state-of-the-art model Curve-GCN \cite{Curve-GCN-CVPR19} and compare them with our proposed model in the experiment section (section \ref{sec:experiment}). \paragraph{Video Annotation Tools} Annotating objects in video is not as straight-forward as annotating them in images as it requires observing their motion paths and taking into account the possibility of change in shape over time. One of the earliest video annotation tools publicly available is VATIC \cite{10.1007/978-3-642-15561-1_44} which uses inter-frame interpolation to generate bounding boxes automatically. Bounding boxes, however, are not enough for detailed analyses including pixel-wise segmentation. There have also been efforts on annotating regions in videos using active contours \cite{TouchCut}, approximation of closed boundaries using polygons \cite{Bianco:2015:ITM:2735612.2741539} and partition trees \cite{Giro-i-Nieto2010}. Despite the differences in getting the region boundaries within a frame, all these tools do some kind of annotation propagation or interpolation across video frames to achieve video annotation. Instead, our proposed model jointly optimizes the boundaries in all frames. \section{Volumetric Graph Convolutional Network (VGCN)} \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{images/Figure2_Framework.pdf} \end{center} \caption{The overall framework of Volumetric Graph Convolutional Network (VGCN). Per-frame feature maps are illustrated on the right.} \label{fig:framework} \end{figure} Our aim is to automatically generate dense per-frame region boundary labels for all the regions of interest in all video frames, assuming only the bounding boxes of the target regions in sparse keyframes are given by human annotator(s). The whole task can be decomposed into subtasks each of which focuses on a key step: generating dense per-frame region boundary labels for a sub-sequence of video frames bounded by two keyframes, where a single region inside the target appears across all the frames, as shown in Figure \ref{fig:teaser}. This is a reasonable setting as human annotators can scan the whole video before annotation and place keyframes to cut the whole sequence of the target region (object, object part, or even stuff) into sub-sequences with reasonably consistent region shapes. We have three desiderata for a video annotation model. First, besides the raw video data, the model can only assume \emph{sparse bounding boxes} as the input during testing and inference. Second, the method should be applicable to \emph{arbitrary regions} (of different shapes and contents) appearing in sub-sequences of arbitrary lengths. Last, \emph{spatial-temporal inference} should be employed to ensure global joint optimization. In this paper, we propose a novel model which we refer to as Volumetric Graph Convolutional Network (VGCN) that meets all three requirements. It takes as input a pair of bounding boxes from two keyframes for data cropping and normalization, as well as initialization. Its local graph connections (i.e., edges) and weight sharing over same types of connections allow uniform formulation and robust modeling of arbitrary local shapes. The volumetric graph convolutions integrate and propagate information spatially and temporally, leading to global spatial-temporal inference and the ability to handle arbitrary video of various lengths. \subsection{Overall Framework} As shown in Figure \ref{fig:framework}, given an input video sub-sequence bounded by two chosen keyframes, the annotator-provided keyframe bounding boxes are used to crop the video frames, normalize them (following \cite{Curve-GCN-CVPR19}), and extract frame-wise feature maps whose contents are shown on the right. The bounding boxes also help VGCN initialize the locations of its volumetric nodes that correspond to the keypoints of desired boundaries of all video frames. Then the model samples features from the feature maps according to the node (i.e., boundary keypoint) locations, and such sampled features are fed into a group of graph convolutional blocks (8 of them in our implementation) for information integration and propagation. A fully-connected (FC) layer is adopted to map the updated features of each node to its predicted location shifts. After the actual shifting of node locations, another round of feature sampling and graph convolutions can be applied to predict a new round of location shifts. This process can be iterated several times to ensure an accurate fit to the actual region boundaries. \subsection{Graph Structure} Suppose the sub-sequence where a target region exists is bounded by two keyframes with a sparsity factor $K$ indicating the frame ID difference between them. The task is to find the region boundary in each frame. The 1st frame and the ``$K+1$''-th frame are the keyframes with bounding-box supervision. Assume the shape of the region boundary in each frame can be well-represented by $N$ control points $\mathcal{V}_k = \{\mathbf{cp}_k^0, \dots, \mathbf{cp}_k^{N-1}\}$, where $k$ indicates the $k$-th frame and $\mathbf{cp}_k^i = [x_k^i, y_k^i]^T$ is the location of the $i$-th control point in this frame, we construct a volumetric graph $G_v = (\mathcal{V}, \mathcal{E})$ covering all the frames of the sub-sequence, for which a three-frame slice is illustrated in Figure \ref{fig:graph_structure}. Let $\mathcal{V} = \bigcup_{k=1}^{K+1} \mathcal{V}_{k}$ denote the graph nodes which are the union of control points from all the frames, we define the edge set $\mathcal{E} = \mathcal{E}_s \cup \mathcal{E}_t$ by introducing two types of connections for each node $\mathbf{cp}_k^i$. The spatial connections $\mathcal{E}_s$ cover both the node's self-connection and the links between the node and its four neighboring nodes (the black lines in Figure \ref{fig:graph_structure}), while the temporal connections $\mathcal{E}_t$ link the node to its corresponding nodes in the two neighboring frames (cross-frame green lines) and optionally also those nodes' four spatial neighbors (orange lines). Depending on the temporal links, the former case is called ``decomposable local connection'' as the spatial and temporal links are orthogonal, and the later is called ``full local connection'' or simply ``full-connection'' which is the recommended structure. These spatial-temporal connections enable effective and efficient information integration and propagation among the graph nodes. For a better model-data fit, we add one more frame to each end of the sub-sequence. As a result, our model deals with $K+3$ frames and has $\mathcal{V} = \bigcup_{k=0}^{K+2} \mathcal{V}_{k}$. \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{images/Figure3_Graphs.pdf} \end{center} \caption{Graph structures of two variants of VGCN, full local connection (recommended) and decomposable local connection (simplest), illustrated with three adjacent frames. Note that all the nodes of an intermediate frame will have exactly the same number of edges. Some edges for ``full local connection'' are omitted for better visibility.} \label{fig:graph_structure} \end{figure} \subsection{Feature Extraction and Representation} With the two keyframe bounding boxes, we get the bounding boxes for other frames with linear interpolation. Then a 15\% margin is added to each size of the bounding box to ensure a sufficient coverage of data even when the bounding boxes are tight. The extended bounding boxes are used to crop the frames and normalize the cropped areas to uniform sizes (with spatial coordinates normalized to [0,1] by [0,1]). Following \cite{Curve-GCN-CVPR19}, we extract three types of features from the normalized data as shown in Figure \ref{fig:framework}: appearance features computed using the DeepLab-v2 \cite{DeepLabv2} model pre-trained, and fine-tuned for semantic segmentation on ImageNet and PASCAL, respectively, and boundary features computed using additional branches to predict the probability of existence of an object edge/vertex on a 28 x 28 grid and position features (normalized pixel coordinates). In contrast to Curve-GCN \cite{Curve-GCN-CVPR19}, we add motion information into the feature extraction in two ways: concatenating the optical flow map (obtained by FlowNet2.0 \cite{FlowNet2}) to the original image data before feature extraction, and directly concatenating the flows to the three types of extracted features to form the final frame-wise feature maps. The first one contributes to the boundary features via early fusion, making it motion-aware, and the second one directly adds in the flow information via late fusion. In our implementation, we found that it is better to have the late fusion only involved in the first iteration of graph convolutions rather than all of them. This is likely due to the potentially noisy flows around the region boundaries. When the graph nodes get close to the boundaries in later iterations, such noise can obstruct the model from learning proper shifts. \subsection{Graph Convolutional Block} \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{images/Figure4_GraphConvBlock.pdf} \end{center} \caption{The graph convolutional block of VGCN. Both full local connection (recommended) and decomposable local connection (simplest) are illustrated. The right subfigure shows how the information from graph nodes (boundary keypoints) is integrated spatially and temporally, using the decomposable model as an example.} \label{fig:graph_conv_block} \end{figure} Following Curve-GCN, we also adopt the multi-layer GCN architecture, where each layer has a Graph ResNet structure as shown in Figure \ref{fig:graph_conv_block}. Mathematically, the graph convolution for an arbitrary node $\mathbf{cp}_k^i$ can be formulated as \begin{equation} \hat{f}_{k,i}^l = W_o^l f_{k,i}^l+\sum_{\mathbf{cp}_k^j\epsilon \mathcal{E}_s(\mathbf{cp}_k^i) } W_s^l f_{k,j}^l + \sum_{\mathbf{cp}_{k-1}^j \epsilon \mathcal{E}_t(\mathbf{cp}_k^i) } {W_t^l f_{k-1,j}^l} + \sum_{\mathbf{cp}_{k+1}^j \epsilon \mathcal{E}_t(\mathbf{cp}_k^i) } {W_t^l f_{k+1,j}^l}, \end{equation} where $W_o^l$, $W_s^l$, and $W_t^l$ are the weight matrices at layer $l$ to be learned for transforming the control point's own features, the features of its spatial neighbors (i.e., the nodes connected to $\mathbf{cp}_k^i$ via edges in $\mathcal{E}_s(\mathbf{cp}_k^i)$), and the features of its temporal neighbors (i.e., the nodes connected to $\mathbf{cp}_k^i$ via edges in $\mathcal{E}_t(\mathbf{cp}_k^i)$), respectively, and $\hat{f}_{k,i}^l$ is the updated feature for $\mathbf{cp}_k^i$ at layer $l$ after one round of information propagation. Note that in the ``full-connection'' case the two types of temporal edges (the ones connecting corresponding nodes, and the others) have different weight matrices. After that, there is a ReLU activation $g_{k,i}^l = ReLU(\hat{f}_{k,i}^l)$. Then, there is another round of convolution \begin{equation*} \hat{g}_{k,i}^l = \tilde{W}_o^l g_{k,i}^l+\sum_{\mathbf{cp}_k^j\epsilon \mathcal{E}_s(\mathbf{cp}_k^i) } \tilde{W}_s^l g_{k,j}^l + \sum_{\mathbf{cp}_{k-1}^j \epsilon \mathcal{E}_t(\mathbf{cp}_k^i) } {\tilde{W}_t^l g_{k-1,j}^l} + \sum_{\mathbf{cp}_{k+1}^j \epsilon \mathcal{E}_t(\mathbf{cp}_k^i) } {\tilde{W}_t^l g_{k+1,j}^l}, \end{equation*} where $\tilde{W}_o^l$, $\tilde{W}_s^l$, and $\tilde{W}_t^l$ are the corresponding weight matrices. Finally, the residual structure combines the updated feature $\hat{g}_{k,i}^l$ and the original feature $f_{k,i}^l$ to generate the input feature for the next layer, together with a ReLU activation $f_{k,i}^{l+1} = ReLU(\hat{g}_{k,i}^l + f_{k,i}^l)$. After $L$ layers ($l=0, \dots, L-1$), $f_{k,i}^L$ is fed into a single fully connected layer to predict the location shift $(\Delta x_k^i, \Delta y_k^i)$ for $\mathbf{cp}_k^i$. Then its coordinates can be updated as $\mathbf{\tilde{cp}}_k^i = [x_k^i + \Delta x_k^i, y_k^i + \Delta y_k^i]^T$. With the new control point location, we can get the new features $\tilde{f}_{k,i}^{l+1}$ and have it go through the whole VGCN module again to get another location shift. Such shifting of control points can be done several times to nudge the graph nodes to move to the actual region boundaries. As shown in Figure \ref{fig:graph_conv_block}, the convolution can be viewed as spatio-temporal information integration and propagation. When several blocks are applied, each node can get information from a significantly large area of the video. We use the Normalized Bi-directional Chamfer Distance (NBCD) for the loss to get supervision from the ground-truth boundaries. It directly measures the accuracy on keypoints and corresponds to the NBCD metric in our performance evaluation. \section{Experiment} \label{sec:experiment} \subsection{Experimental settings} \textbf{Datasets}. \textbf{Synthia} \cite{Bengar_2019_ICCV} is a recently released synthetic driving dataset that has ground truth object boundaries for every frame. This dataset contains 178 training video sequences captured at 25fps, with lengths ranging from 15 seconds to 30 seconds. We consider dynamically moving objects relevant to driving scenarios: person, car, truck, bus, and bicycle. \textbf{KITTI MOTS} \cite{2019_MOTS_CVPR} is a newly built real dataset for Multi-Object Tracking and Segmentation (MOTS). It contains 21 training sequences (12 for training, 9 for validation), and 4 testing sequences are reserved for MOTS Challenge. The dataset only has two object categories: pedestrian and car, with 99 pedestrians and 431 cars for training, 68 pedestrians and 151 cars for validation. We use the 12 training sequences for training and the validate set for testing. Synthia is about 5 times larger in terms of frame/sub-sequence numbers. \noindent \textbf{Evaluation Metrics}. Besides the widely used mIoU and F1-score (1px) measure \cite{Curve-GCN-CVPR19} that measures mask and boundary matching accuracy, respectively, we also use the Normalized Bi-directional Chamfer Distance (NBCD) to directly measure the keypoint matching accuracy, so that the performance can be checked from different perspectives. \noindent \textbf{Implementation Details} Though VGCN can handle sub-sequences of various lengths, we use equal lengths by fixing $K$ (default: 10) to ease model transfer and comparisons across-datasets and ablation study on the factor of sparsity. The sequence numbers of train, validation and test split for our experiments on both are 11k:0.9k:1.3k and 1.5k:0.3k:0.4k (here `k' denotes the unit of a thousand), with train and validation from the original training sets and the test split from the original test sets. \subsection{Experimental Results} \noindent \textbf{Models for Comparison}. Instead of video-wise joint boundary inference, one may simply apply a frame-wise model (here we choose Curve-GCN \cite{Curve-GCN-CVPR19} as it is the state-of-the-art and also the most relevant model) to each video frame with either the provided bounding box (in case of keyframes) or some interpolated bounding box (for a intermediate frame). We refer to this model as Spatial Graph Convolutional Network (SGCN), as it is also based on GCN and only does the graph convolutions spatially. Despite its simplicity, SGCN has a natural limitation of omitting the temporal relationships among successive video frames. To overcome it, one may also think about simply smoothing the results of SGCN on successive video frames using a B-spline function, so that the overall model can be made indirectly video-wise. Such a simple solution is named `SGCN-smoothed'. However, we believe that a direct modeling of temporal relationships in the model like the proposed VGCN is necessary and superior. To better show the performance difference of direct spatio-temporal modeling and indirect result smoothing, we also test a simplified version of VGCN named `VGCN-basic', by only keeping the minimal temporal connection (i.e., the decomposable local connection as shown in Figure \ref{fig:graph_structure}) and excluding the motion features. Note that for a fair comparison, all the compared models are trained with the same data which only have ground-truths on the sparse key frames. \noindent \textbf{Effectiveness of VGCN}. As shown in Table \ref{table:res_Synthia} and Table \ref{table:res_Synthia_more}, VGCN significantly outperforms SGCN under all metrics on the Synthia dataset. Interestingly, the ignorable result differences between SGCN-smoothed and SGCN also indicate that simple temporal smoothing is not effective. We found that the training set of KITTI MOTS is too small to support our model, so we choose to do the generalization experiments on it instead as we detail below. \begin{table}[t!] \footnotesize \setlength\tabcolsep{2pt} \caption{Results on Synthia, measured by mean Intersection over Union (mIoU). Since different object categories have different amounts of samples, the number of frames in testing for each category is shown under its name.} \label{table:res_Synthia} \begin{center} \begin{tabular}{ cccccccc } \toprule \multicolumn{2}{c}{Model} & Person & Car & Truck & Bus & Bicycle & \multirow{2}{*}{Average} \\ \cmidrule{1-2} Name & Property & \footnotesize{(5.96K)} & \footnotesize{(10.50K)} & \footnotesize{(0.21K)} & \footnotesize{(0.18K)} & \footnotesize{(0.35K)} & \\ \midrule SGCN & \footnotesize{Frame-wise, based on \cite{Curve-GCN-CVPR19}} & 68.79 & 78.17 & 78.09 & 67.93 & 32.95 & 65.19 \\ SGCN-smoothed & Video-wise \footnotesize{(indirect)} & 68.27 & 78.10 & 78.46 & 68.76 & 33.26 & 65.37 \\ VGCN-basic & Video-wise & 71.75 & 79.09 & 79.91 & 65.74 & 35.53 & 66.41\\ VGCN & Video-wise\footnotesize{, proposed} & \textbf{72.68} & \textbf{80.29} & \textbf{80.48} & \textbf{69.49} & \textbf{36.09} & \textbf{67.80} \\ \bottomrule \end{tabular} \end{center} \end{table} \begin{table}[t!] \footnotesize \caption{Results on Synthia in Normalized Bi-directional Chamfer Distance (NBCD) and F1-score (F at 2px), shown in the ``NBCD/F1-score(2px)'' format for each entry.} \label{table:res_Synthia_more} \setlength\tabcolsep{3pt} \begin{center} \begin{tabular}{ ccccccc } \toprule \multirow{2}{*}{Model} & Person & Car & Truck & Bus & Bicycle & \multirow{2}{*}{Average} \\ & \footnotesize{(5.96K)} & \footnotesize{(10.50K)} & \footnotesize{(0.21K)} & \footnotesize{(0.18K)} & \footnotesize{(0.35K)} & \\ \midrule SGCN & 3.4/86.05 & 7.3/76.86 & 5.3/80.06 & 6.1/68.43 & 11.0/50.51 & 6.6/72.39 \\ SGCN-smoothed & 3.4/85.50 & 7.4/76.55 & 5.2/80.07 & 6.1/69.33 & 10.7/50.03 & 6.5/72.30 \\ VGCN-basic & 2.9/89.89 & 7.1/80.08 & 4.9/85.11 & 5.076.13 & 10.0/56.01 & 6.0/77.44\\ VGCN & \textbf{2.8/90.35} & \textbf{6.9/83.20} & \textbf{4.5/86.83} & \textbf{4.8/76.91} & \textbf{10.0/56.98} & \textbf{5.8/78.85} \\ \bottomrule \end{tabular} \end{center} \end{table} \begin{table}[t!] \footnotesize \setlength{\tabcolsep}{5pt} \caption{Results on KITTI-MOTS. Upper part: directly applying the models trained on Synthia; lower part: fine-tuned models (pre-trained on Synthia). `Ped' stands for `Pedestrian'. } \label{table:res_MOTS} \begin{center} \begin{tabular}{ cccccccccc } \toprule & & \multicolumn{2}{c}{mIoU}& &\multicolumn{2}{c}{NBCD} & &\multicolumn{2}{c}{F1-score (2px)} \\ \cmidrule{3-4} \cmidrule{6-7} \cmidrule{9-10} Model & & Ped & Car & & Ped & Car & & Ped & Car \\ \midrule SGCN & & 57.1 &58.2 & &10.6 & 19.0 & & 51.5 & 52.0 \\ SGCN-smoothed & & 55.4 &58.1 & &10.7 & 19.0 & & 47.6 & 49.6 \\ VGCN-basic & & \textbf{63.3} &70.3 & &\textbf{8.0} & 12.1 & & 60.6 & 63.4 \\ VGCN-basic + Full-connection & & 62.9 &\textbf{70.5} & &8.2 & \textbf{11.5} & & \textbf{62.6} & \textbf{64.0} \\ VGCN & & 61.7&67.2 & &9.0 & 12.0 & & 59.3 & 60.4 \\ \midrule SGCN & & 57.1 &66.1 & &9.8 & 13.7 & & 51.3 & 57.8 \\ SGCN-smoothed & & 55.7 &65.3 & &9.9 & 13.8 & & 48.1 & 54.9 \\ VGCN-basic & & 63.1 &70.9 & &8.9 & 11.8 & & 59.8 & 63.5 \\ VGCN-basic + Full-connection & & \textbf{65.2} &\textbf{72.6} & &\textbf{7.8} & \textbf{11.6} & & \textbf{65.7} & \textbf{68.9} \\ VGCN & & 65.1 &71.8 & &8.0 & 12.0 & & 65.6 & 66.2 \\ \bottomrule \end{tabular} \end{center} \end{table} \noindent \textbf{Generalizability}. Since the GCN-based models have no assumption on the data, they can be applied to arbitrary video data. We conduct two types of experiments to validate the generalizability of VGCN, in comparison with its competitors. One is about directly applying models trained on Synthia to the test set of KITTI MOTS. The results are shown in the upper part of Table \ref{table:res_MOTS}. The other is fine-tuning the pre-trained model (trained on Synthia) on the small training set of KITTI MOTS and then testing the fine-tuned models on its test set. The results for this are shown in the lower part of Table \ref{table:res_MOTS}. We fixed the feature extraction part, the FC layers of VGCN and its graph convolution layers, and just tuned the network for feature aggregation. VGCN models all outperform SGCN-based ones by large margins. We can see that motion features hurt VGCN in both direct application and fune-tuning, but full-connection significantly helps. Fine-tuning doesn't benefit VGCN-basic, but it significantly enhances VGCN when full-connection is adopted. These findings indicate that the major difference between synthetic data and real data is probably on the motion patterns, instead of adapting motion features which may be hard, fine-tuning the full temporal connections is more effective. Examples on how fine-tuning benefits VGCN are shown in Figure \ref{fig:generalization}, together with two representative failure cases: undesirable region due to badly interpolated boxes and extra part caused by object interaction. \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{images/Figure5_Results_MOTS_NEW.pdf} \end{center} \caption{Comparison of the generalizability of VGCN, and two representative failure cases } \label{fig:generalization} \end{figure} \noindent \textbf{Running Time}. Inference on a 13-frame sequence takes about 1.1s on a NVIDIA RTX2080Ti GPU. Note that interactive correction can be much faster, as features can be pre-computed and result refinement is much faster than inference-from-scratch as shown in \cite{Curve-GCN-CVPR19}. For this, we believe the computational speed of our method would be sufficient for real usage. \subsection{Ablation Studies} \label{subsec:ablation} \begin{figure}[t] \begin{center} \includegraphics[width=1.0\linewidth]{images/Figure6_Sparsity_NEW.pdf} \end{center} \caption{Performance changes w.r.t. annotation sparsity (keyframe interval $K$).} \label{fig:sparsity} \end{figure} \begin{table}[t!] \footnotesize \caption{Ablation studies on VGCN components using Synthia dataset, measured by mIoU.} \label{table:ablation_synthia} \setlength\tabcolsep{3pt} \begin{center} \begin{tabular}{ ccccccc } \toprule \multirow{2}{*}{Model} & Person & Car & Truck & Bus & Bicycle & \multirow{2}{*}{Average} \\ & \footnotesize{(5.96K)} & \footnotesize{(10.50K)} & \footnotesize{(0.21K)} & \footnotesize{(0.18K)} & \footnotesize{(0.35K)} & \\ \midrule VGCN-basic \footnotesize{(i.e., w/o both)} & 71.75 & 79.09 & 79.91 & 65.74 & 35.53 & 66.41\\ VGCN-basic + Motion-features & 70.40 & 79.79 & 81.20 & 67.87 & 35.34 & 66.92 \\ VGCN-basic + Full-connection & \textbf{73.42} & \textbf{80.30} & \textbf{81.74} & 63.92 & \textbf{36.21} & 67.12 \\ VGCN \footnotesize{(i.e., w/ both)} & 72.68 & 80.29 & 80.48 & \textbf{69.49} & 36.09 & \textbf{67.80} \\ \bottomrule \end{tabular} \end{center} \end{table} \noindent \textbf{VGCN Components}. As shown in Table \ref{table:ablation_synthia}, both the motion features and the full-connection can help improve the performance. Though full-connection contributes more than motion features, they are complementary and the VGCN model with both performs the best. \noindent \textbf{Sparsity of annotation}. Figure \ref{fig:sparsity} shows performance variation of the compared models on KITTI-MOTS, with different $K$ values. The results are averaged over `Ped' and `car'. All the models perform worse when $K$ is increased. VGCN models always outperform SGCN. \noindent \textbf{Impact of box interpolation}. To investigate the influence of box quality, we use GT-bbox in testing and find the superiority of VGCN to SGCN is even greater: 68.67\% (0.87\% up) vs.65.21\%(0.02\% up) in mIoU on Synthia and 71.1\% (6.0\% up) for `Ped', 79.2\% (7.4\% up) for `Car' vs. 58.4\% (1.3\% up) and 70.7\% (4.6\% up) respectively in mIoU on KITTI MOTS. \section{Conclusions} This paper presents a novel tool for video region annotation that can generate dense per-frame region boundaries with only bounding boxes on sparse keyframes provided by the annotators. We believe our method opens a new avenue of research for significantly extending video supervision for general deep vision applications. An important future work is to extend the method to allow interactive correction in a human-in-the-loop annotation scheme. \section*{Acknowledgement} This work was in part supported by JSPS KAKENHI 17K20143 and SenseTime Japan.
{'timestamp': '2020-08-18T02:22:11', 'yymm': '2008', 'arxiv_id': '2008.07049', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07049'}
arxiv
\section{Conclusion and Future Work} \label{sec:conclusion} In this paper, we conduct empirical studies to understand the prediction variation estimated by ensembles under various randomness control settings. Our experiments on two public datasets ({MovieLens}\ and {Criteo}) demonstrate that with more variation sources, ensemble tends to produce more accurate point estimates with higher prediction variations. More importantly, we demonstrate strong predictive power of neuron activation strength to infer ensemble prediction variations, which provides an efficient way to estimate prediction variation without the need to run inference multiple times as in ensemble methods. In the future, we are interested in exploring the proposed activation strength based methods in various applications, such as model-based reinforcement learning, and curriculum learning. In addition, we plan to make two further improvements to our activation strength based approach. First, we would like to study additional neuron activation patterns, such as adjacent neuron paths, to further improve the variation estimation model. Second, currently we re-train the variation estimation model for each new target task. Activation pattern is a universal and general feature, and we hope to find a universal model for prediction variation estimation without re-training each individual target task. \subsection{Model Ensemble Sizes} \label{sec:ensemble_size} Our prediction variation is estimated using the ensemble method, and we are interested in finding out how many models to ensemble to estimate prediction variation accurately. In this section, we conduct empirical experiments on {MovieLens-R}, and {Criteo}\ to answer this question. For each target task, using the same training data and model configuration, we first train 1000 models as the ensemble universe $M_{gt}$ to obtain ground-truth prediction variations. We used the R3 randomness setting here, as it is the most commonly used setting in practice. Given an example $x$, we obtain its prediction variation from the 1000 ensemble models as $PV_{gt}(x)$ . We calculate the mean prediction variation for all the examples as $\bar{PV}_{gt}$. Then we evaluate the prediction variation difference between an ensemble $M_N$ of a smaller size $N$ and $M_{gt}$. We use {\em delta ratio} to quantify the difference between the prediction variation estimated from the two ensembles $M_N$ and $M_{gt}$ as follows. \begin{definition} (Delta Ratio) Let prediction variation delta $\delta_{M_N}(x)$ be the absolute difference of the estimated prediction variation between a model ensemble $M_N$ of size $N$ and the ground-truth model ensemble $M_{gt}$, as $\delta_{M_N}(x) = |PV_{M_N}(x) - PV_{gt}(x)|$. We obtain the average prediction variation delta for all the examples in a dataset $D$ as $\delta_{M_N} =\frac{1}{|D|}\sum_{x \in D}\delta_{M_N}(x)$. We define delta ratio $dr_{M_N}$ to be the ratio of prediction variation delta $\delta_{M_N}$ to the average prediction variation in the ground-truth ensemble models $\bar{PV}_{gt}$, as $dr_{M_N} = \delta_{M_N} / \bar{PV}_{gt}$ \end{definition} In Figure~\ref{fig:ensemble_size}, we show the delta ratio of different ensemble sizes for the {MovieLens}\ regression task and the {Criteo}\ task. For each ensemble size $N$, we sample N models without replacement from the 1000 ground-truth model universe and obtain its delta ratio. We repeat this sampling process for 20 times, and obtain the mean and standard deviation of the delta ratio for the given $N$. We plot the delta ratio as shown in Figure~\ref{fig:ensemble_size}. We can see the delta ratio decreases when the ensemble size increases. The delta ratio statistics is similar on both datasets, {MovieLens}\ and {Criteo}. When the ensemble size is 100, the delta ratio is about 7\% which indicates 93\% of prediction variation from the ground-truth ensemble of 1000 models is captured. As a result, in this paper, we use 100 as the default ensemble size for all experiments. \section{Introduction} Deep neural networks (DNNs) have gained widespread adoption in recent years across many domains. Despite their impressive performance in various applications, most DNNs today only generate point predictions. And it is well known that a set of DNN models trained with the same model specification and the same data can produce very different predictions~\cite{lakshminarayanan2017simple, ovadia2019can, wen2020batchens}. Researchers realize that point predictions do not tell the whole story and raise questions about whether DNNs predictions can be trusted~\cite{jiang2018trust, schulam2019can}. In response, a growing number of researches are looking into quantifying prediction uncertainties for DNNs. Ensemble method is a state-of-the-art benchmark for prediction uncertainty estimation to consolidate agreements among the ensemble members and produce better point predictions~\cite{breiman1996bagging, dietterich2000ensemble, lakshminarayanan2017simple, ovadia2019can}. Many researches focus on whether these point predictions are well-calibrated on either in-distribution or out-of-distribution (OOD) data~\cite{ovadia2019can, guo2017calibration, lee2017training,liu2020simple}. However, there exist disagreements among the predictions in the ensemble, which we call {\bf \em prediction variation}. For example, different models in the ensemble often yield different prediction results even on the same input example. Although prediction variation contributes to model uncertainty~\cite{lakshminarayanan2017simple}, there is no comprehensive study to advance the understanding of it. Ensembles provide us with a good approximation of prediction variation, but they are computationally expensive as they require training multiple copies of the same model. At inference time, they require computing predictions on every example for every ensemble member, which can be infeasible for real-time large-scale machine learning systems. Researches propose various resource-saving techniques \cite{gal2016dropout, huang2017snapshot, wen2020batchens, lu2020uncertainty}. However, as far as we know, none of these works studies whether we can infer prediction variation from neuron activation strength collected from the DNN directly, without running predictions on the same data multiple times. Here, we use {\bf \em neuron activation strength} to indicate DNN's neuron output strength, {e.g.}, the value of the neuron after activation and whether the neuron is activated. We hypothesize that neuron activation strength could be directly used to infer prediction variation. Our intuition is based on neuroscience's Long-Term Potentiation (LTP) process~\cite{nicoll2017brief} which states that connections between neurons become stronger with more frequent activation. LTP is considered as one of the underlying mechanisms for learning and memorization. If we imagine deep networks learn like the brain, some groups of neurons will be more frequently and/or strongly activated, i.e. strengthened neurons. During learning, these strengthened neurons represent where the network has learned or memorized better. Therefore, we hypothesize that deep neural networks predict more confidently if an input activates through strengthened neurons, and less so if the input goes through weaker neurons. \vspace{0.1cm} \noindent {\bf Our Goal} --- In this paper, we aim to advance the understanding of prediction variations estimated by ensemble models, and look into the predictive power of neuron activation strength on prediction variations. To the best of our knowledge, we are the first to conduct comprehensive studies on prediction variations from different ensemble models, and we are also the first to demonstrate that we are able to infer prediction variation from neuron activation strength. \vspace{0.1cm} \noindent {\bf Challenges} --- We face the following challenges: {\em Variation Quantification} --- There are a variety of prediction problems. For example, predicting the target rating for a user on a given movie could be a regression task or a multi-class classification task by dividing the movie ratings into multiple buckets; predicting click-through rate is often modeled as a binary classification task. There is no standard way to quantify prediction variation for such a variety of tasks. {\em Variation Sources} --- Training a set of models with the same model specification and the same data can produce very different results, and the prediction disagreements are inherently caused by the nonconvex nature of DNN models in which multiple local minima exist. Multiple randomness sources could lead to the disagreements, such as random initialization of DNN parameters, random shuffling of training data, sub-sampling of training data, optimization algorithms, and even the hardware itself. It is often hard to identify the contribution of each randomness source to prediction variation. {\em Neuron Activation Strength} --- We hypothesize that a deep network's prediction variations are strongly correlated with neuron activation strength throughout training and at inference time. However, it is not straightforward to demonstrate this relationship for different prediction problems and randomness sources. \vspace{0.1cm} \noindent {\bf Our Approach} --- In this paper, we investigate sources for prediction variation, and by controlling the randomness sources explicitly, we demonstrate that neuron activation strength has strong prediction power to infer ensemble prediction variations in almost all the randomness-controlled settings. We demonstrate our findings on two popular datasets used to evaluate recommender systems, MovieLens and Criteo. First, we quantify prediction variation across different types of target tasks, including regression, binary classification, and multi-class classification tasks. We use standard deviation of the ensemble predictions to quantify prediction variation for regression and binary classification tasks, and use KL divergence based measurement to quantify prediction distribution disagreement for multi-class classification tasks. Second, we identify and examine three variation sources of randomness (data shuffling, weight initialization, and data re-sampling). By explicitly controlling randomness sources, we study their contributions to the performance of point prediction and prediction variation. Our results show that every variation source exhibits a non-negligible contribution towards the total prediction variation. The prediction variation may have different sensitivities to different types of variation sources on different target tasks. When we include more variation sources, the ensemble's prediction mean tends to be more accurate, while the prediction variations are higher. Finally, we demonstrate that neuron activation strength has strong prediction power in estimating prediction variation of ensemble models, while the neuron activation strength information can be obtained from a single DNN. We obtain the neuron activation strength information from the neural network. With this strength information, we can add a cheap auxiliary task to estimate prediction variation directly. Our experiment results show that our activation strength based method estimates prediction variation fairly well as a regression task. The average $R^2$ on {MovieLens}\ is 0.43 and 0.51 with different task definitions, and on {Criteo}\ is 0.78. Our method is especially good at detecting the lowest and highest variation bucket examples, on average with 0.92 AUC score for the lowest bucket and 0.89 AUC score for the highest bucket on both datasets. Our approach is complementary and orthogonal to many other resource-saving or single model prediction variation estimation techniques, as it doesn't alter the target task's optimization objectives and process. \vspace{0.1cm} \noindent {\bf Applications} --- Prediction variation quantification is a fundamental problem and our activation strength based approach opens up new opportunities for a lot of interesting applications. For example, in model-based reinforcement learning, prediction variation has to be quantified for exploration~\cite{zhou2019neural,chua2018deep}. In curriculum learning~\cite{bengio2009curriculum}, prediction variation can be used as a way for estimating example difficulty. In medical domain, prediction variation can be used to capture significant variability in patient-specific predictions~\cite{dusenberry2020analyzing}. Our proposed activation strength based method provides a simple and principled way to serve prediction variation estimate by deploying a cheap auxiliary task, instead of using an expensive ensemble model, during inference time. We explore applying our method in the above scenarios. \vspace{0.1cm} \noindent {\bf Contributions} --- Our contributions are four fold: \begin{itemize} \item Framework for prediction variation estimation using activation strength in Section~\ref{sec:preliminary}. \item Formal quantification on prediction variation for various target tasks in Section~\ref{sec:variation_definition}. \item Prediction variation understanding by explicitly controlling various randomness sources in Section~\ref{sec:prediction_sources}. \item Empirical experiments to demonstrate strong predictive power from neuron activation strength to estimate ensemble prediction variation in Section~\ref{sec:variation_estimation}. \end{itemize} We cover the related work in Section~\ref{sec:related_work}, and conclude with a discussion of future work in Section~\ref{sec:conclusion}. \section{Appendix} \input{ensemble_size.tex} \bibliographystyle{ACM-Reference-Format} \section{Variation Estimation Framework} \label{sec:preliminary} Similar to the work on model uncertainty estimation~\cite{nix1994estimating,nix1995learning,su2018tight}, we build two components for the prediction variation estimation framework: target task, and variation estimation task, as shown in Figure~\ref{fig:framework}. Before discussing the two tasks in detail, we first introduce the two experiment datasets that we use throughout this paper. \subsection{Datasets} \label{sec:datasets} Our studies are based on two datasets: {MovieLens}\ and {Criteo}. \vspace{0.1cm} \noindent {\bf {MovieLens}} --- The {MovieLens}~\footnote{\url{http://files.grouplens.org/datasets/movielens/ml-1m-README.txt}} contains 1M movie ratings from 6000 users on 4000 movies. This data also contains user related features and movie related features. \vspace{0.1cm} \noindent {\bf {Criteo}} --- The Criteo Display Advertising challenge ~\footnote{https://www.kaggle.com/c/criteo-display-ad-challenge} features a binary classification task to predict click-through rate (clicked event's label is 1, otherwise 0). The {Criteo}\ data consists of around 40M examples with 13 numerical and 26 categorical features. \begin{figure}[t!] \includegraphics[width=0.9\linewidth]{pic/framework.pdf} \caption{Our framework for prediction variation estimation using activation strength.} \label{fig:framework} \end{figure} \subsection{Target Task} \label{sec:target_tasks} The target task is defined by the original prediction problem, such as the rating prediction task on {MovieLens}, and the click-through prediction task on {Criteo}. The target task takes in the input features from the dataset, and predicts the target. In this paper, we focus on the multi-layer perceptron architecture (MLP), with ReLU as the activation function for all layers. Furthermore, we define three target tasks on {MovieLens}\ and {Criteo}. \vspace{0.1cm} \noindent {\bf {MovieLens}\ Regression ({MovieLens}-R)} --- The target task takes in user-related features ({i.e.}, id, gender, age, and occupation) and movie-related features ({i.e.}, id, title and genres), and predicts movie rating as a regression task. The movie ratings are integers from 1 to 5. We use mean squared error (MSE) as the loss function. MSE is a standard metric for evaluating the performance of rating prediction in recommenders~\cite{herlocker2004evaluating,saadati2019movie,bennett2007netflix}. For example, \cite{bennett2007netflix} used 100 million anonymous movie ratings and reported their Root Mean Squared Error (RMSE) performance on a test dataset as 0.95. Each model trains for 20 epochs with early-stopping. We only use the observed ratings in {MovieLens}\ as training data. Similar to the neural collaborative filtering framework~\cite{he2017neural}, we use fully connected neural network for the rating prediction task and ReLU as the activation function. We set the fully connected neuron layer sizes to be [50, 20, 10]. We set the user id and item id embedding size to 8~\cite{he2017neural}, the user age embedding size to 3, and user occupation embedding size to 5. \vspace{0.1cm} \noindent {\bf {MovieLens}\ Classification ({MovieLens}-C)} --- Similar to the {MovieLens}\ regression task, we predict movie ratings as 5 integer values from 1 to 5 and model this problem as a multi-class classification task with softmax cross entropy as the loss function. We experiment with temperature scaling values $T=$[0.1, 0.2, 0.5, 1, 2, 5, 10] with batch size of 1024 to make sure predictions are well calibrated~\cite{guo2017calibration}. We pick $T=0.2$ which gives the best Brier score\footnote{ \url{https://en.wikipedia.org/wiki/Brier_score}} while achieving similar accuracy compared to other settings. \vspace{0.1cm} \noindent {\bf {Criteo}} --- This target task uses a set of numerical and categorical features to predict the click-through rate. The label for the task is either 0 or 1 representing whether an ad is clicked or not. We model this problem as a binary classification task with sigmoid cross entropy loss function. The trained model outputs a float between 0 and 1 representing the predicted click-through probability. We use the same model setting as described in~\cite{ovadia2019can}, except for ReLU layer sizes. In the beginning, we set ReLU layer sizes to [2572, 1454, 1596] as in~\cite{ovadia2019can}, but found that only around 80 neurons are activated at least once on a 10k sample data. As a result, for the experiments in this paper, we use ReLU layer sizes of [50, 20, 10] and find the prediction performance is similar to the model with much larger ReLU layer sizes. Each model is trained for 1 epoch. \subsection{Variation Estimation Task} In this paper, we focus on using neuron activation strength to estimate prediction variation for each input example. We use ensemble to estimate prediction variation as the ground-truth label. We define prediction variation formally in Section~\ref{sec:variation_definition}. As shown in Figure~\ref{fig:framework}, we build a neural network model taking the neuron activation strength features to estimate prediction variation. During the inference time, we directly output the estimated prediction variation using activation strength as an auxiliary task. In our current setup, we collect the activation strength features from all the neurons in the target task. Also, we find that it is possible to identify important neurons in order to reduce the number of activation strength features. Due to the space limit, we will not discuss feature reduction in this paper. The detailed setup of the variation estimation task is discussed in Section~\ref{sec:variation_estimation}. \section{Related Work} \label{sec:related_work} In machine learning literature, researchers mostly focus on two distinct types of uncertainties: aleatoric uncertainty and epistemic uncertainty~\cite{der2009aleatory}. Aleatoric uncertainty is due to the stochastic variability inherent in the data generating process~\cite{liu2019accurate}. Aleatoric uncertainty corresponds to {\em data uncertainty}, which describes uncertainty for a given outcome due to incomplete information~\cite{knight1921risk}. Epistemic uncertainty is due to our lack of knowledge about the data generating mechanism~\cite{liu2019accurate}, and corresponds to {\em model uncertainty}, which can be viewed as uncertainty regarding the true function underlying the observed process~\cite{bishop2006pattern}. In this paper, we focus on studying model uncertainty, especially prediction variations or disagreements. There has been extensive research on methodologies for estimating model uncertainty and discussions on their comparisons~\cite{ovadia2019can}. Principled approaches include Bayesian approaches~\cite{neal2012bayesian,mackay1992practical,hinton1993keeping,louizos2017multiplicative,zhu2018bayesian} and ensemble-based approaches~\cite{lakshminarayanan2017simple}. Bayesian methods provide a mathematically grounded framework to model uncertainty, through learning the deep neural network as Gaussian processes~\cite{neal2012bayesian}, or learning approximate posterior distributions for all or some weights of the network ~\cite{blundell2015weight,kwon2018uncertainty}. Ensemble methods~\cite{lakshminarayanan2017simple}, on the other hand, is a conceptually simpler way to estimate model uncertainty. There are multiple ways to create ensembles of neural networks: bagging~\cite{breiman1996bagging}, Jackknife~\cite{mcintosh2016jackknife}, random parameter initialization, or random shuffling of training examples. The resulting ensemble of neural networks contains some diversity, and the variation of their predictions can be used as an estimate of model uncertainty. A lot of research work results are based on the ensemble method~\cite{berthelot2019mixmatch, de2018clinically, chua2018deep, leibig2017leveraging,ovadia2019can}. For example, \cite{de2018clinically} demonstrates promising results uses deep ensembles for diagnosis and referral in retinal disease. \cite{chua2018deep} proposes a new algorithm for model-based reinforcement learning by incorporating uncertainty via ensemble. In this paper, we use ensemble as the ground truth to produce prediction variations in different scenarios ({i.e.}, different randomness settings). Estimating model uncertainty through Bayesian modeling or ensemble usually incurs significant computation cost. For example, Bayesian neural networks that perform variational learning on the full network~\cite{blundell2015weight} significantly increase the training and serving cost. The cost for ensemble methods scales by the number of models in the ensemble, which can be prohibitive for practical use. To this end, researchers have proposed various techniques to reduce the cost for Bayesian modelling and ensemble methods. For example, single-model approaches are proposed to quantify model uncertainty by modifying the output layer~\cite{tagasovska2019single, liu2020simple}, deriving tractable posteriors from last layer output only~\cite{riquelme2018deep, snoek2015scalable}, or constructing pseudo-ensembles that can be solved and estimated analytically~\cite{lu2020uncertainty}. Our proposed method in this paper can also be viewed as a single-model approach for model uncertainty estimation. However, we do not impose any Bayesian assumptions on the network or any distributional assumptions on the ensembles. Instead, we build an empirical model to learn the association between activation strength and model uncertainty, and use it to estimate model uncertainty for new examples, which offers a relatively simple, robust and computationally efficient way to estimate prediction variation from a single model. \section{Prediction Variation Sources} \label{sec:prediction_sources} In this section, we diagnose the prediction variation sources, and we are interested in seeing their effects on the total prediction variation by controlling type of each randomness source. There are many sources contributing to prediction variation. Random initialization of DNN parameters contributes randomness to model predictions. Randomness can also come from training data shuffling or sub-sampling. In addition, asynchronous or distributed training could lead to training order randomness. More surprisingly, we observe the hardware itself contributes to the model prediction variation: we find that by fixing all the other settings, training a model on different CPUs might produce different models. In this paper, we consider three types of randomness sources: \vspace{0.1cm} \noindent {\bf 1. Shuffle (S)} --- Whether randomly shuffles input data, {i.e.}, randomizes input data order. \vspace{0.1cm} \noindent {\bf 2. RandInit (R)} --- Whether randomly initializes model parameters, including DNN weights and embeddings. We can fix the initialization by setting a global random seed in Tensorflow. \vspace{0.1cm} \noindent {\bf 3. Jackknife (J)} --- Whether randomly sampling input data by applying delete-1 Jackknife~\cite{mcintosh2016jackknife}. We split data into N Jackknife sub-samples and each ensemble member randomly leaves one Jackknife sample out. We use 100 models for each ensemble as discussed in Appendix~\ref{sec:ensemble_size}, and we split the data into 100 unique Jackknife sub-samples. Another popular data sampling method is bootstrap~\cite{wichmann2001psychometric}. For this work, we pick Jackknife due to its simplicity to implement. \vspace{0.1cm} We set up the prediction variation randomness control experiments as follows: First, if incorporating Jackknife randomness, we obtain the delete-1 Jackknife sub-samples; otherwise, we use all the training data. Second, if incorporating Shuffle randomness, we shuffle the training data; otherwise we do not. Finally, if incorporating RandInit randomness, we randomly initialize all the parameters without a fixed global seed for all the ensemble members; otherwise we use a fixed global seed.\footnote{When RandInit is enabled, we use a fixed set of 100 random seeds.} We use an ensemble of 100 models for each of the randomness settings: as discussed in Appendix~\ref{sec:ensemble_size}, 93\% of prediction variation in the ensemble of 1000 models can be captured with size 100 ensemble. On each dataset of {MovieLens}\ and {Criteo}, we randomly split the data into training and testing. On {MovieLens}\ we split the 1M data into 60\% for training, and 40\% for testing. On {Criteo}, same to~\cite{ovadia2019can}, we use 37M data for training and 4.4M for testing. We obtain the prediction variation estimation on all the testing examples for further analysis. \vspace{0.1cm} \noindent {\bf Randomness Source Comparison} --- Table~\ref{tab:randomness_control} shows the accuracy and prediction variation statistics for different combinations of the three randomness sources. For each type of randomness combination ({e.g.}, (R3) R+S means using RandInit and Shuffle only), we train 100 models of the same setting, and obtain the ensemble mean prediction for accuracy evaluation and report the prediction variations. For accuracy evaluation, we report Mean Squared Error (MSE) and accuracy (ACC) for {MovieLens-R}, ACC for {MovieLens-C}, and AUC score for {Criteo}. We obtain ACC for {MovieLens-R}\ by rounding the ratings to the closest integers. For prediction variation metrics, we report prediction variation (PV) mean and standard deviation, and PV coefficient (coeff). We obtain the PV coefficient for each example $x$ as PV(x) divided by the ensemble mean prediction. From the tables, we can see that each type of the randomness sources exhibits a non-negligible and different contribution towards the total prediction variations. As we add more randomness sources, the mean prediction of the ensembles tends to become more accurate, and the prediction variations get higher. On all three target tasks, the R7 setting appears to exhibit the best or close to best accuracy score, and its prediction variations are also the highest or close to the highest among all the randomness settings. It also seems that different target tasks or datasets are sensitive to different types of randomness sources. We observe that the {Criteo}\ data is more sensitive to Shuffle and Jackknife randomness while the {MovieLens}\ data is more sensitive to RandInit. We verify that by fixing all the randomness sources, we do not observe any prediction variation in the R0 settings. The PV Mean and PV std is always 0 for R0. According to PV coefficient, we notice that {MovieLens}\ shows around 5-6\% of prediction sway from the mean prediction while {Criteo}\ has around 20\% of prediction sway. \vspace{0.1cm} \noindent {\bf Randomness Source Correlations} --- Under each randomness setting, we are able to obtain the prediction variation for each example. Figure~\ref{fig:randomness_correlation} shows the Pearson correlation of the prediction variations of all the examples between each pair of the randomness settings. The randomness setting can be found at Table~\ref{tab:randomness_control}. We do not consider R0 because it eliminates all the randomness in the model and PV is always 0. As we can see from Figures~\ref{fig:randomness_correlation}, the prediction variation correlation patterns on {MovieLens}\ is quite different from {Criteo}. For example, while the lowest Pearson correlation score on {MovieLens}\ is around 0.7, all the randomness settings on {Criteo}\ are quite correlated with the lowest Pearson correlation score to be around 0.92. \vspace{0.1cm} \noindent {\bf Regression vs Classification} --- On the {MovieLens}\ dataset, we are able to predict ratings as regression or classification. Table~\ref{tab:randomness_control} shows that the prediction accuracy is higher when we predict ratings as a classification task than as a regression task almost for all the randomness settings, as classification optimizes for the accuracy metric directly. We also compare the prediction variations obtained through regression and classification, and Figure~\ref{fig:correlation_movielens_tasks} shows the Pearson correlation of prediction variations for the two tasks on various randomness settings for all the testing examples. We find that whether the variations are strongly correlated depends on the randomness settings. As shown in the figure, the prediction variations are highly correlated (with Pearson correlation more than 0.8) when we add the RandInit randomness source, otherwise the two tasks are less correlated. we think the reason is that RandInit controls model parameters and the loss function plays an important role, while underlying data properties affect Shuffle and Jackknife more. \section{Prediction Variation Estimation} \label{sec:variation_estimation} In this section, we study the problem of using neuron activation strength to infer prediction variation. We first discuss the prediction variation estimation task setup in Section~\ref{sec:variation_estimation_setup}, and then show the experiment results on using neuron activation strength to estimate prediction variation in Section~\ref{sec:variation_estimation_results}. \begin{figure} \centering \includegraphics[width=.85\linewidth]{pic/movielens_tasks_correlation.pdf} \vspace{-0.4cm} \caption{Pearson correlation of prediction variations between {MovieLens-R}\ and {MovieLens-C}.} \label{fig:correlation_movielens_tasks} \end{figure} \subsection{Variation Estimation Task Setup} \label{sec:variation_estimation_setup} As shown in Figure~\ref{fig:framework}, the variation estimation task takes in the neuron activation information collected during the target task inference time. We use the prediction variation estimated by the ensemble model for training, and then during inference time, the variation estimation model is able to infer the prediction variation as a cheap auxiliary task. We set up the variation estimation task as follow. \vspace{0.1cm} \noindent {\bf Ground-truth Labels} --- We first obtain the prediction variation ground-truth from the ensemble. On both {MovieLens}\ or {Criteo}, we first split the data into training $D_{t}$ and testing $D_{e}$ for the target task. On {MovieLens}, we split the 1M data into 60\% for training and 40\% for testing; on {Criteo}, we use the same setting as in~\cite{ovadia2019can}, 37M data for training and 4.4M for testing. We train an ensemble of 100 models to obtain $PV(x)$ for each $x \in D_{e}$. \vspace{0.1cm} \noindent {\bf Evaluation Procedure} --- We further split $D_e$ into 2 sets: 50\% as $D_{e1} = (x_{e1}, PV(x_{e1}))$ for training the variation estimation model; and another 50\% as $D_{e2} = (x_{e2}, PV(x_{e2}))$ for testing. Given a trained target task model $m_t$, we build a neural network model $m_v$ to estimate prediction variations. $m_v$ collects the activation strength information from $m_t$'s neurons during $m_t$'s inference time. $m_v$ trains on $D_{e1}$ and tests on $D_{e2}$ with fully connected layers of size $[100, 50]$, batch size 256, Adam optimizer with learning rate 0.001, and 150 training epochs with early stopping. We find that $m_v$ takes less than one epoch to converge on {Criteo}, but takes longer to converge on {MovieLens}\ due to its much smaller data size. Now we explain $m_v$'s input features and objective in detail. \vspace{0.1cm} \noindent {\bf Input Features} --- We consider two types of input features collected from neuron activation strength. We use ReLU~\cite{nair2010rectified} as the activation function. We believe our activation strength feature is general and can be applied to other activation functions, such as Softplus~\cite{glorot2011deep}, ELU~\cite{clevert2015fast}, GELUs~\cite{hendrycks2016gaussian}, and Swish~\cite{ramachandran2017searching}. Due to space limitations, we only experiment with ReLU. {\em Binary} --- On ReLU neurons, we consider whether a neuron is activated as the input feature. This binary feature represents whether the neuron output is greater than 0. {\em Value} --- The raw value of a neuron's output directly represents the strength of an activated neuron. Therefore, we experiment with normalized activation value as the input feature. We normalize the neuron outputs according to the neuron output mean and standard deviation collected from the training data. \vspace{0.1cm} \noindent {\bf Objective} --- We estimate the prediction variation in two ways. {\em Regression} --- In this setting, the model directly estimates the prediction variation as a regression task. We use Mean Squared Error (MSE) as the loss function. However, by directly optimizing for MSE, this regression task's output range could be huge. As a result, we limit the minimum output of the model to be 0 as prediction variation is always positive, and limit the maximum output to be $mean + 3*std$ where the mean and std are estimated on the training data's prediction variations. $mean + 3*std$ should be able to cover 99.7\% of the data in a Guassian distribution.\footnote{ \url{https://en.wikipedia.org/wiki/68-95-99.7_rule}} {\em Classification} --- In this setting, we divide prediction variation into multiple buckets according to the percentile, and then predict which variation bucket it belongs to. We set the bucket number to be 5, and use cross entropy as the loss function for the prediction variation classification model. \begin{table}[t!] \begin{tabular}{l|cc|cc|cc} \toprule & \multicolumn{2}{c|}{MovieLens-R} & \multicolumn{2}{c|}{MovieLens-C} & \multicolumn{2}{c}{Criteo} \\ \cline{2-7} & MSE & $R^2$ & MSE & $R^2$ & MSE & $R^2$ \\ \hline (R1) R & 0.0022 & 0.5416 & 3.6159 & 0.4586 & 0.0063 & 0.7617 \\ (R2) S & 0.0011 & 0.5636 & 1.5015 & 0.4683 & 0.0068 & 0.7863 \\ (R3) R+S & 0.0019 & 0.5514 & 3.4288 & 0.4569 & 0.0062 & 0.8100 \\ \hline (R4) J & 0.0025 & 0.3885 & 2.5986 & 0.3386 & 0.0086 & 0.7817 \\ (R5) R+J & 0.0024 & 0.5219 & 3.7727 & 0.4646 & 0.0085 & 0.7868 \\ (R6) S+J & 0.0017 & 0.4938 & 2.3175 & 0.4125 & 0.0091 & 0.7739 \\ (R7) R+S+J & 0.0022 & 0.5123 & 4.0496 & 0.4368 & 0.0092 & 0.7761 \\ \hline Average &0.0020 &0.5104 &3.0407 &0.4338 &0.0078 &0.7824 \\ \bottomrule \end{tabular} \caption{Performance of variation estimation as regression on 7 randomness settings. } \label{tab:uncertainty_prediction_regression} \end{table} \subsection{Variation Estimation Performance} \label{sec:variation_estimation_results} In this section, we show the variation estimation performance using neuron activation strength on {MovieLens}\ and {Criteo}. \vspace{0.1cm} \noindent {\bf Regression Performance} --- When we run the prediction variation estimation as a regression task, we directly output a score as the estimated prediction variation. We use both binary and value input features. In Table~\ref{tab:uncertainty_prediction_regression}, we show the Mean Squared Error (MSE) and $R^2$ for the three target tasks on the 7 randomness control settings. From the table, on all the three target tasks and all the 7 randomness control settings, we observe strong prediction power of neuron activation strength for ensemble prediction variations. The average $R^2$ on {MovieLens-R}\ is 0.51, on {MovieLens-C}\ is 0.43, and on {Criteo}\ is 0.78. The variation estimation performance is the best on the {Criteo}\ data, while {MovieLens-R}\ is better than {MovieLens-C}. The reasons could be: First, {Criteo}\ has more training data than {MovieLens}. To train the variation estimation model, we have 2.2M (50\% of 4.4M) training data on {Criteo}, while only 0.2M (50\% of 0.4M) training data on {MovieLens}; Second, {Criteo}\ has a larger relative range of prediction variations, compared to {MovieLens}. As shown in Table~\ref{tab:randomness_control}, {Criteo}\ shows around 20\% of prediction variation sway from the mean prediction, which is much higher than ~4-6\% on {MovieLens}; Finally, the {Criteo}\ task is probably the easiest task among the three: it is a binary classification task, while {MovieLens-R}\ is a regression task and {MovieLens-C}\ is a multi-class classification task. \begin{figure} \centering \includegraphics[width=\linewidth]{pic/variation_estimation_auc.pdf} \caption{AUC for variation bucket prediction with the randomness setting R3.} \label{fig:classification_auc} \end{figure} \vspace{0.1cm} \noindent {\bf Classification Performance} --- We also run the prediction variation estimation as a classification task, by predicting which variation bucket it should be in. We use both binary and value input features. Due to the space limit, we only show the results on the R3 randomness setting, as R3 uses training data shuffling and parameter random initialization which is the most common setting in practice. Figure~\ref{fig:classification_auc} shows the AUC scores and Figure~\ref{fig:confusion_matrix} shows the confusion matrix for the 5-bucket prediction variation classification on both {MovieLens}\ and {Criteo}. The numbers in Figure~\ref{fig:confusion_matrix} are normalized by the actual example number in each bucket. Bucket 1 represents the lowest variation slice, while bucket 5 represents the highest. As we can see from Figure~\ref{fig:classification_auc}, our variation estimation model is fairly good at distinguishing examples at different variation buckets, especially for the lowest and highest buckets. The average AUC score for the three tasks on bucket 1 is about 0.92 and on bucket 5 is about 0.89. Figure~\ref{fig:confusion_matrix} shows that the classification errors mostly happen on adjacent buckets. For example, on {Criteo}, most of the mis-classifications assign bucket 1 examples to bucket 2. When we divide the prediction variation buckets on training data, we notice that the bucket thresholds are close. For example, under the randomness control setting R3, the thresholds of the 5 buckets for {MovieLens-R}\ are [0.1420, 0.1672, 0.1950, 0.2366], and the thresholds for {Criteo}\ is [0.0194, 0.0287, 0.0398, 0.0515]. As show in the figures, {Criteo}\ seems to have the best performance among the three tasks. Again the reasons could be that the {Criteo}\ task has more training data, is probably the easiest among the three tasks, and it has much larger relative prediction variation range. \begin{figure*} \includegraphics[width=.33\linewidth]{pic/movielens_activation_prediction_cm_regression.pdf} \includegraphics[width=.33\linewidth]{pic/movielens_activation_prediction_cm_classification.pdf} \includegraphics[width=.33\linewidth]{pic/criteo_activation_prediction_cm.pdf} \vspace{-0.8cm} \caption{Confusion matrix for variation estimation as classification for the randomness setting R3.} \label{fig:confusion_matrix} \end{figure*} \begin{table}[t!] \begin{tabular}{c|cc|cc|cc} \toprule & \multicolumn{2}{c|}{MovieLens-R} & \multicolumn{2}{c|}{MovieLens-C} & \multicolumn{2}{c}{Criteo} \\ \cline{2-7} & MSE & $R^2$ & MSE & $R^2$ & MSE & $R^2$ \\ \hline B & 0.0025 & 0.4196 & 4.1616 & 0.3408 & 0.0124 & 0.6210 \\ BV & 0.0019 & 0.5514 & 3.4288 & 0.4569 & 0.0062 & 0.8100 \\ \bottomrule \end{tabular} \caption{Activation feature study for variation estimation as regression with the randomness setting R3.} \label{tab:feature_ablation} \vspace{-0.4cm} \end{table} \begin{table}[t!] \begin{tabular}{c|cc|cc|cc} \toprule & \multicolumn{2}{c|}{MovieLens-R} & \multicolumn{2}{c|}{MovieLens-C} & \multicolumn{2}{c}{Criteo} \\ \cline{2-7} Run & MSE & $R^2$ & MSE & $R^2$ & MSE & $R^2$ \\ \hline 1 & 0.0019 & 0.5514 & 3.4288 & 0.4569 & 0.0062 & 0.8100 \\ 2 & 0.0020 & 0.5160 & 3.3243 & 0.4734 & 0.0061 & 0.8140 \\ 3 & 0.0019 & 0.5418 & 3.1825 & 0.4959 & 0.0064 & 0.8036 \\ 4 & 0.0019 & 0.5384 & 3.2375 & 0.4872 & 0.0070 & 0.7863 \\ 5 & 0.0021 & 0.4994 & 3.2631 & 0.4831 & 0.0066 & 0.7969 \\ \hline Std & 0.00008 & 0.0190 & 0.0842 & 0.0133 &0.0003 &0.0098 \\ \bottomrule \end{tabular} \caption{Reproducibility test for variation estimation as regression with the randomness setting R3.} \vspace{-0.4cm} \label{tab:reproducibility} \end{table} \vspace{0.1cm} \noindent {\bf Activation Feature Study} --- In Table~\ref{tab:feature_ablation}, we show the contribution of the two input activation strength features. We try two feature settings: {\em B} refers to using the binary feature only; and {\em BV} refers to using both the binary and value features. As shown in the table, each type of features makes a non-negligible contribution towards prediction variation estimation. Thus, it is beneficial to have both the binary and value features for prediction variation estimation. \vspace{0.1cm} \noindent {\bf Reproducibility} --- When we evaluate the variation estimation model, the performance is calculated based on one target task model. To check whether the performance is reproducible, we train 5 new target task models. To simplify the problem, we also use the randomness setting R3, which is the most commonly used setting in practice. Table~\ref{tab:reproducibility} shows the MSE and $R^2$ for each run on both {MovieLens}\ and {Criteo}. As shown in the table, the standard deviation of MSE and $R^2$ for the 5 runs is small for each of the three tasks. Thus, we conclude that activation strength is useful for estimating prediction variation and it is reproducible. \vspace{0.1cm} \noindent {\bf Comparison with Dropout~\cite{gal2016dropout}} --- Dropout is also a standard way to estimate model uncertainty. We estimate prediction variation using dropout as follows: We train one model by randomly dropping 20\% of the neurons on the ReLU layers using the randomness settings R3. During inference time, we keep the dropout turned on to obtain the predicted results for all the testing data. We run the inference 100 times, and obtained the prediction variation for each testing example. We find that the prediction variation estimated by dropout is not very correlated with the variation estimated by the ensemble method. On {MovieLens-R}, Pearson correlation of prediction variations for dropout and ensemble is 0.25, RMSE is 0.0798, and $R^2$ is -0.5010. On {Criteo}, Pearson correlation of prediction variations for dropout and ensemble is 0.37, RMSE is 0.0279, and $R^2$ is -1.3709. As a result, we did not conduct further comparison with our activation strength based method. \section{Prediction Variation Quantification} \label{sec:variation_definition} In this section, we formally quantify prediction variation in different problem settings. Ensemble is one state-of-the-art benchmark for prediction uncertainty estimation~\cite{breiman1996bagging, dietterich2000ensemble, lakshminarayanan2017simple, ovadia2019can}. We use ensemble to estimate model prediction variation, that is how much disagreement there is among ensemble model predictions. Given the same training data and model configuration, we train an ensemble of $N$ models $M = \{m\}$, where $M$ is the set of models, and $N$ is the ensemble size. Let $\{x\}$ be the testing data, and $x$ represents the feature vector. Each of the trained model $m \in M$ makes a prediction on an example $x \in \{x\}$ as $y^\prime_{m}(x)$. For {\em regression and binary classification} tasks, the model output is a float value, thus we define prediction variation as {\em value prediction variation} based on the standard deviation of the predicted float values across different models in the ensemble. For {\em multi-class classification} tasks, the model output is a probability distribution over different categories. Thus, we define prediction variation as {\em distribution prediction variation} based on the KL-disagreement or generalized Jensen-Shannon divergence~\cite{lakshminarayanan2017simple} on the predicted probability distributions. Now we define prediction variation formally. \begin{definition}{(Value Prediction Variation)} \label{def:regression_uncertainty} Given an example $x$ that represents the feature vector, we define its prediction variation $PV(x)$ to be the standard deviation of predictions from the set of models $M$ as $PV(x) = \sqrt{\frac{\sum_{m \in M}{(y^\prime_{m}(x) - \bar{y}(x))^2}}{|M|-1}}$, where $\bar{y}(x) = \frac{1}{|M|} \sum_{m \in M} y^\prime_{m}(x)$ \end{definition} \begin{definition}{(Distribution Prediction Variation~\cite{lakshminarayanan2017simple})} \label{def:classification_uncertainty} Given the example $x$ that represents the feature vector, let the prediction distribution for the example $x$ be $p(y|x)$. We define prediction variation $PV(x)$ to be the sum of the Kullback-Leibler (KL) divergence from the prediction distribution of each model $m \in M$ to the mean prediction distribution of the ensemble. $ PV(x) = \sum_{m=1}^{M} KL(p_m(y|x) || p_E(y|x))$ where $p_E(y|x) = M^{-1} \sum_{m} p(y|x)$ is the mean prediction of the ensemble. \end{definition}
{'timestamp': '2020-08-18T02:21:31', 'yymm': '2008', 'arxiv_id': '2008.07032', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07032'}
arxiv
\section{Introduction} \IEEEPARstart{W}{ith} the inevitable dominance of video traffic on the Internet, it is becoming a challenging task to provide perceptually good video quality. This is partly due to the bursty nature of video traffic, changing network conditions and limitations of network transport protocols. Cisco predicts that ``The sum of all forms of video (TV, video on demand [VoD], Internet, and P2P) will be in the range of 80 to 90 percent of global consumer traffic by 2018'' \cite{Cisco2014a}. Over the last decade, efforts have been made to provide Quality of Service (QoS) within the core network by considering objective parameters at the network layer such as bandwidth, delay and jitter. Diffserv \cite{BlakeS.1998} is an example of these paradigms that can support QoS. The research community and Internet Service Providers (ISP)s have made subjective quality, as perceived by the end user, a main research target. The International Telecommunication Union (ITU) defines this parameter as ``Quality of Experience'' (QoE) \cite{ITU-T2007}. The current design of the Internet has to be enhanced to extend the scope of QoS to consider end-to-end quality, be content-aware and user centric. Admission control is a well known technique to keep traffic load at acceptable levels and guarantee quality for admitted sessions via resource reservation. This idea has been adopted in the past in QoS architectures such as in Diffserv. Thus, some sort of explicit admission control is required to provide per-session QoE by which the network has the right to deny sessions to ensure that the QoE of active sessions is not affected by new sessions. ISP are concerned about maximizing revenue by accepting as many sessions as possible. Measurement-Based Admission Control (MBAC) has been proposed as a solution. In contrast to parameter-based admission control, it is better suited to video traffic. MBAC relies on the measurement of video characteristics such as current load and peak rate. Different algorithms have been proposed to estimate network load \cite{Breslau2000}; however there are algorithms which rely on the Instantaneous Aggregate Arrival Rate (\emph{IAAR}) for their operations. Despite all the efforts, there is no entirely satisfactory admission algorithm for variable rate flows \cite{Auge2011}. Admission control algorithms must not rely on worst-case bounds or instantaneous video arrival rate, as they do not reflect the bursty characteristic of video traffic. This is due to the fact that the burstiness of video flows can be compensated by the silence of other flows. The Internet Engineering Task Force (IETF) has standardized the Pre-Congestion Notification (PCN) based admission control for the Internet \cite{Menth2012} which merely relies on the calculated rate for a measurement period. The perceived QoE-Session relationship can be greatly optimized by exploiting the bursty nature of video traffic. This paper contributes to the measurement mechanism for QoE-aware admission control. It proposes a novel traffic rate measuring algorithm for video admission control mechanisms. The relationship between \emph{IAAR} and the proposed rate is established mathematically. We call the proposed measured rate ``Proposed Instantaneous Aggregate Arrival Rate'' (\emph{Pro-IAAR}) and proposed admission control procedure based on \emph{Pro-IAAR} ``\emph{Pro-IAAR}-Based Measurement Admission Control'' (\emph{Pro-IBMAC}). We also call the admission control procedures which are based on the Calculated Rate (\emph{CalR}) such as PCN ``\emph{CalR}-Based Admission Control'' (\emph{CBAC}). Whereas traffic measurement algorithms and MBAC have been widely covered by the research community, to the best of our knowledge this is the first work that includes QoE in the area of the QoE-Session optimization. The main contributions of this paper are twofold: \begin{enumerate} \item A novel algorithm for traffic measurement supported by the mathematical model is proposed. The algorithm measures the exceedable video aggregate rate that is able to keep the video quality unimpaired. The exceedable rate is the total bitrate of enrolled video traffic that can exceed the available link capacity without degradation to the user's perception of quality. \item Operation of the proposed measurement algorithm is demonstrated with an implementation in a QoE-aware admission control procedure for video admission. \end{enumerate} The remainder of the paper is organized as follows. Section \ref{sec:relatedWork} presents related work. Assumptions made by this paper are detailed in Section \ref{sec:assumption}. Section \ref{sec:QoE} provides a theoretical background of QoE. Section \ref{sec:model} presents the mathematical model for the proposed algorithm. The simulation setup is explained and results are presented and discussed in Section \ref{sec:resultANDdiscuttion}. Section \ref{sec:subjectiveTest} describes the environment of the subjective tests and analysis of the collected data. The proposed model is validated in Section \ref{sec:validation}. The paper concludes with Section \ref{sec:conclusion}. \section{Related Work} \label{sec:relatedWork} MBAC is not a new topic as work has been undertaken since video traffic has emerged on the Internet. It includes two main components: measurements of network load and admission policies. Four MBAC algorithms are presented in \cite{Gibbens1997} based on Chernoff bounds. A MBAC scheme based on measured mean and variance of load offered to the cross-protect priority queue is proposed in \cite{Auge2011}. As traffic flow rate is only meaningful if it is associated with a corresponding interval length. Network traffic over some interval has been studied as an essential part of the MBAC functionality. The admission control scheme proposed in \cite{Floyd1996} estimates the equivalent capacity of a class of aggregated traffic based on Hoeffding bounds for controlled-load services. The suitability of the average instead of the instantaneous arrival rate for video streaming admission decisions has been investigated in \cite{Qadir2013a}. An algorithm for MBAC has been introduced in \cite{Qiu2001} that employs adaptive and measured peak rate envelopes of the aggregate traffic flow to allocate resources for multiclass networks with link sharing. The flow behavior as a function of interval length can be described by the proposed rate envelope which characterizes the extreme values (maximal rates) of the aggregate flow that can avoid packet loss. As a supporting mechanism in flow and admission control, techniques have been developed for estimating available bandwidth \cite{Nam2012}, \cite{Guerrero2010}, \cite{Nam2013}, \cite{Lubben2014} and \cite{Cavusoglu2014}. Other studies have compared the performance of MBAC algorithms. The simple sum; a parameter-based admission control algorithm has been compared to three measurement-based algorithms; the measured sum, acceptance region and equivalent bandwidth based on the link utilization and adherence to service commitment \cite{Jamin1997}. The robustness of \cite{Floyd1996}, \cite{Jamin1997} and \cite{Qiu2001} in meeting the QoS target have been compared in \cite{Nevin2008}. They have been further evaluated based on maximum tolerable packet loss rate and maximum packet queuing delay without assuming any explicit knowledge on incoming flows and on-going traffic \cite{Ammar2011}. All of the three studied algorithms were found to meet the first target of maximum tolerable packet loss rate while only \cite{Qiu2001} was able to always meet the second target of maximum packet queuing delay. The knowledge-base admission control scheme introduced in \cite{Ammar2012} determines whether to accept a flow based on QoS performance parameters such as maximum tolerable delay or packet loss rate. The scheme achieves a good trade-off between flow performance and resource utilization compared to \cite{Jamin1997} and \cite{Qiu2001}. In \cite{Lima2007} the architecture of centralized, distributed, hybrid, class-based and active/passive MBAC and their limitations on the quality control of network services have been compared. The efficiency of MBAC algorithms depends on interactions between several time-scales, ranging from the very short time scales to the entire session. Work in \cite{Nevin2010} has studied how uncertainty in the measurements of MBAC varies with the length of the observation window and described a methodology for analyzing measurement errors and performance. The concept of similar flows and adding slack in bandwidth have been introduced to minimize the probability of false acceptance. In \cite{Moore2002} an implementation-based comparison of MBAC algorithms has been made using a purpose built test environment. It has revealed that there is no single ideal MBAC algorithm due to computation overheads, multiple timescales present in both traffic and management and error resulting from random properties of measurements. These features dramatically impact the MBAC algorithm's performance. Work presented in \cite{Nam2008} has proposed a delay-aware admission control to guarantee delay bounds for delay sensitive applications. The video quality model presented in \cite{Zhang2013} targets Skype video calls based on measurement and can be used for user QoE-aware network provisioning. The model can find the minimum bandwidth needed to accommodate \emph{N} concurrent Skype video calls with satisfactory Mean Opinion Score (MOS). The study conducted in \cite{Xu2014} has investigated the system architecture, video generation and adaptation, packet loss recovery and QoE of video-conferencing solutions. Google+, iChat and Skype were all covered in the study. The delivered quality was measured in terms of end-to-end delay in a wide range of real and emulated network scenarios. The study has found that the layered video coding and server architecture (used by Google+ and Skype) can significantly improve user conferencing experiences. Most recently, \cite{ChendebTaher2014} has proposed a model-based admission control algorithm to predict the QoS metrics based on which and the QoS constraints of the flows, appropriate decision for new flow is taken. The average number of satisfied users was maximized through a QoE-aware scheduling framework by sending a single bit feedback to indicate the satisfaction level \cite{Lee2014}. As a cutting edge proposed admission control mechanism for multimedia network, the PCN-based admission control \cite{EardleyP.2009} has attracted the attention of researchers. Several modifications to the PCN algorithm have been proposed in \cite{Latre2011b}. An extension to the PCN-based admission control system has been proposed in \cite{Latre2011a}. A novel metering algorithm based on a sliding-window, to cope with the bursty nature of video sessions and another adaptive algorithm to facilitate the configuration of PCN were proposed in that work. Admission control has also been proposed to better support applications with QoS requirements in wireless networks. The appropriate thresholds for admission decisions were studied by \cite{Xu2013}. A flow-level mechanism for multiple antenna equipped nodes to maximize flow acceptance and improve network throughput has been developed in \cite{Hamdaoui2007}. A QoE-based admission control for wireless has been proposed in \cite{Piamrat2008} in which the access point controls video sessions based on the MOS scores computed by pseudo-subjective quality assessment tool run on the access point. Most of the MBAC algorithms that have been discussed in the literature are per-aggregate MBAC algorithms. The per-flow MBAC algorithm presented in \cite{Jiang2005} targets the flow-aware network by adopting dynamic priority scheduling for flow aggregation. A newly admitted flow is given a lower priority by the proposed algorithm, however its priority is improved when an existing flow leaves the network. Finally, an enhancement to the MBAC has been proposed to mitigate the impact of fair rate degradation and ensure better quality in flow-aware network by \cite{Wojcik2013}. \section{Assumptions} \label{sec:assumption} \noindent This paper makes the following assumptions: \begin{itemize} \item Video traffic is the dominant Internet traffic \cite{Cisco2014a}. It is the only traffic that is subject to admission control. Other traffic volumes are small in comparison and therefore only video traffic is considered. \item Video traffic is bursty in nature as video applications in reality send traffic at a very variable rate \cite{Nevin2010}. \item An explicit admission control is required to provide an acceptable level of QoE \cite{Nevin2010} on bottleneck links. \item There is no danger of a ``flash crowd'', in which many admission requests arrive within the reaction time of admission mechanisms, because then they all might get admitted and so overload the network \cite{EardleyP.2009}. \end{itemize} \section{QoE; A New Quality Paradigm} \label{sec:QoE} QoE is the quality as experienced by end users. The purpose of introducing QoE is to include all aspects of multimedia systems that are related to media quality. Addressing quality from end user experience or perceived QoE is a relatively new approach which requires more research in all directions such as optimization, assessment, monitoring, management and prediction. This is due to the emergence of massive video services and development of huge number of video capable devices such as smart phones \cite{Cisco2014a}. Various layers (from video encoding to decoding) and across the access and/or core networks are involved in providing an end-to-end QoE to end users. Technically, perceived video quality is affected by the trade-off relationship between encoding redundancy and network impairments. In addition to network parameters such as bandwidth, delay, packet loss ration, other technical and non-technical parameters may affect quality \cite{Brooks2010}. There are different approaches to measure and estimate QoE. Subjective, objective or hybrid approaches are mainly used for that purpose. Since people have different perceptions of the same video content, groups of people carry out subjective tests by grading the shown sequence. This is time-consuming and costly; however it is worthwhile as real users are involved in the tests. Objective video quality metrics are often proposed because none of the QoS parameters can precisely define the QoE of multimedia services \cite{Latre2009}. These objective approaches are carried out by the use of algorithms and formulas. Peak Signal to Noise Ratio (PSNR) and Structural Similarity (SSIM) are two full reference objective video quality metrics. They compare the original video with received (possibly distorted) video and calculate the MOS value. PSNR is mostly used for its simplicity and good correlation with the subjective video test result. PSNR tools are available to calculate the PSNR value. A possible mapping of PSNR to MOS is shown in Table \ref{tab:psnr_mos_mapping} \cite{Ohm2004}. However, this is a problematic approach as PSNR does not directly correspond to MOS \cite{Gross2004}. On the other hand, SSIM estimates the perceived quality frame by frame and is considered to have a higher correlation with subjective quality ratings \cite{Group2008}. The SSIM index assumes that the human visual system is more oriented towards the identification of structural information in video sequences. It produces a score between 0 and 1 from original and received signals \cite{Wang2004a}. The third approach is a hybrid between subjective and objective methods in which both the technical parameters as well as human rating are taken into account \cite{Cherif2011} \cite{Piamrat2009a}. ITU recommends objective modeling of measurable technical performance and subjective testing with people \cite{Brooks2010}. \begin{table}[!th] \centering \caption{Possible PSNR to MOS mapping} \label{tab:psnr_mos_mapping} \begin{tabular}{|l|c|c|} \hline PSNR & MOS & Quality \\ \hline $>$37 & 5 & Excellent \\ \hline 31-37 & 4 & Good \\ \hline 25-31 & 3 & Fair \\ \hline 20-25 & 2 & Poor \\ \hline $<$20 & 1 & Bad \\ \hline \end{tabular} \end{table} \section{Modeling} \label{sec:model} \subsection{Measurement Algorithm} \label{sec:measurmentAlgorithm} In this section, we describe a new approach to measure traffic rate that suits video traffic. For the benefit of comparison, we introduce the traditional approach of traffic measurement \emph{IAAR} then present our proposed measurement algorithm \emph{Pro-IAAR}. Since, the measurement mechanism is proposed for video admission procedures, it will be modeled into an admission control scheme \emph{Pro-IBMAC}; Equation (\ref{eq:9}). \emph{IAAR} at any time \emph{t}$>$0 and \emph{i}$>$0 can be expressed by Equation (\ref{eq:1}): \begin{equation} \label{eq:1} IAAR(t) = \sum_{i=1}^n x_{i}(t) \end{equation} \noindent where \emph{$x_i(t)$} is the instantaneous arrival rate (throughput) of session \emph{i} at time \emph{t}, and \emph{n} is the number of sessions. Let \emph{$x_i(t)$} be an independent random variable with minimum rate \emph{$x_i^{min}(t)$}, peak rate \emph{$x_i^{max}(t)$} and \emph{$x_i^{min}(t)$} $\le$ \emph{$x_i(t)$} $\le$ \emph{$x_i^{max}(t)$}. Further assuming that \emph{$x_i(t)$} is a discrete random variable that takes any set of values from a finite data set \emph{$x_1(t)$}, \emph{$x_2(t)$}, .... \emph{$x_n(t)$} each of probability \emph{$p_1(t)$}, \emph{$p_2(t)$}, .... \emph{$p_n(t)$} respectively. A new session will be accepted by \emph{CBAC}, if the sum of \emph{CalR($\tau$)} for the time window ($\tau$) plus the peak rate of the new session \emph{$x_{new}$} is less or equal to the link's capacity \emph{$C_{l}$} as given by Equation (\ref{eq:2}): \begin{equation} \label{eq:2}\ CalR(\tau) + x_{new} \le C_{l} \end{equation} In our proposed scheme we consider \emph{Pro-IAAR(t)} as an admission parameter instead of \emph{CalR($\tau$)}. Now we find how \emph{Pro-IAAR(t)} is related to \emph{IAAR(t)}. We utilize the Hoeffding inequality theorem \cite{Hoeffding1963} to develop a model for \emph{Pro-IAAR(t)}. The reason behind this approach is that the Hoeffding theorem relates \emph{IAAR(t)} and the average of \emph{IAAR(t)}; $\mu_S(t)$. It defines the upper bound of the probability that the sum of \emph{n} independent random variables will be greater than the average by \emph{n}$\epsilon$ or more for $\epsilon$ $>$ \emph{0}. Equation (\ref{eq:3}) quantifies this probability relationship between \emph{IAAR(t)} and $\mu_S(t)$. We then develop a relationship between \emph{Pro-IAAR(t)} and \emph{IAAR(t)}. Hoeffding bounds were first used for admission control algorithms in \cite{Floyd1996}. \begin{equation} \label{eq:3} Pr\{IAAR(t) \ge \mu_S(t)+n\epsilon\} \le \gamma \end{equation} \noindent where $\gamma$ is given by Equation (\ref{eq:4}): \begin{equation} \label{eq:4}\ \gamma = exp \left( \frac{-2n^2\epsilon^2} { \sum_{i=1}^n (x_{i}^{max}(t)-x_{i}^{min}(t))^2} \right) \end{equation} \noindent $\mu_S(t)$ is the expectation value of \emph{IAAR(t)} which is given by Equation (\ref{eq:5}) in which \emph{$p_{i}$} represents the probability the session \emph{i} is active: \begin{equation} \label{eq:5}\ \mu_S(t) = EIAAR(t) = \sum_{i=1}^n x_{i}(t)\ p_{i}(t) \end{equation} The term $\mu_S(t)+n\epsilon$ in Equation (\ref{eq:3}) represents the proposed \emph{Pro-IAAR(t)} at time \emph{t} which is given by Equation (\ref{eq:6}) and $\epsilon$ is given by Equation (\ref{eq:7}): \begin{equation} \label{eq:6} Pro\textit{-}IAAR(t) = \mu_S(t)+n\epsilon \end{equation} \begin{equation} \label{eq:7}\ \epsilon = \beta \mu_S(t) \frac{n-1}{n} \ \ \ \ \ \ \ \ \ \ \ \ \ \ 0<\beta\le1 \end{equation} Parameter $\beta$ represents how much the total bitrate of enrolled video traffic can exceed the available link capacity without degradation to the user perception quality. It governs the degree of the efficiency of \emph{Pro-IBMAC}. Therefore, choosing a proper value for $\beta$ controls the degree of risk of the admission decision as it balances the QoE-Session trade-off relationship. The value of $\beta$ that optimizes this relationship is referred to as ``proposed value'' in this paper. The condition $\epsilon$$>$0 of Equation (\ref{eq:3}) is satisfied by setting $\beta>$0 in Equation (\ref{eq:7}) (assuming that \emph{n}$>$1). Although Equation (\ref{eq:7}) is also valid for $\beta>$1, the scope of the proposed scheme is only for 0$<\beta\le$1. High values of $\beta$ within this range lets \emph{Pro-IBMAC} function similar to traditional admission control mechanisms, while a smaller value leads to accepting more sessions and compromising QoE. We propose a model for $\beta$ in Section \ref{sec:beta}. A new requested session will be accepted by \emph{Pro-IBMAC} if the condition in Equation (\ref{eq:8}) meets: \begin{equation} \label{eq:8} Pro\textit{-}IAAR(t) + x_{new} \le C_{l} % \end{equation} Substituting Equations (\ref{eq:5}) and (\ref{eq:7}) in Equation (\ref{eq:6}), then Equation (\ref{eq:6}) in Equation (\ref{eq:8}), we get: \begin{equation} \label{eq:9} \sum_{i=1}^n x_{i}(t)\ p_{i}(t) \{ 1 + \beta (n-1) \} + x_{new} \le C_{l} % \end{equation} In Equation (\ref{eq:9}), \emph{x}$_{new}$ is the required rate of new session and \emph{C}$_{\emph{l}}$ is the link capacity. Studies recommend that peak rate be measured for \emph{x}$_{new}$ using techniques such as token buckets and traffic envelopes \cite{Floyd1996} and \cite{Qiu2001}. Others compute the peak rate of a new incoming flow by tracking the first \emph{A} packets of the flow and using sliding window \cite{Ammar2012}. In summary, \emph{Pro-IBMAC} in Equation (\ref{eq:9}) employs \emph{Pro-IAAR(t)} in Equation (\ref{eq:6}) which is based on the Hoeffding inequality theorem. The value of $\gamma$ in Equation (\ref{eq:4}) specifies the level of optimization achieved by considering \emph{Pro-IAAR(t)} in terms of number of sessions that can be fitted on a particular link compared to the \emph{CalR($\tau$)} in Equation (\ref{eq:2}). \subsection{Proposed Model for $\beta$} \label{sec:beta} The tuning parameter $\beta$ affects the operation of the proposed algorithm. The value can be set to optimize the trade-off relationship between QoE of enrolled sessions and number of sessions. In this section, we develop a model for $\beta$. We estimate the value of $\beta$ using two publicly available video sequences; a 30-seconds clip called Mother And Daughter (\emph{MAD}) and a 35-seconds clip called \emph{Paris}. These two video sequences are used to validate the proposed $\beta$ model for various video content. Similar short sequences have also been used for video streaming service and subjective tests \cite{Khan2012}. While choosing the videos, the following points were taken into consideration: firstly, long video is not practical for subjective tests in which subjects evaluate a numbers of videos. Secondly, the aim was to evaluate the admission control-specifically the acceptance/rejection of sessions-and evaluate the admission rate. Thus the duration of video is not expected to have effect on the evaluation of the proposed algorithm. The \emph{MAD} sequence was taken as a slow moving content due to low motion of its video scenes and \emph{Paris} as a fast moving content due to fast motion of its video scenes. The considered contents were classified into slow and fast based on common conventions and the size of their encoded frames, as faster content has larger frame size. Other studies have classified video contents in a similar way, e.g. \cite{Khan2012}. Details about the video sequences are shown in Table \ref{tab:video}. Other simulation settings including the coding and network parameters are explained in Section \ref{sec:simulationSetup}. \begin{table}[!th] \centering \caption{Video sequence description} \label{tab:video} \begin{tabular}{ |l|l|l| } \hline Description & Video sequence 1 & Video sequence 2 \\ \hline Name & \emph{MAD} & \emph{Paris} \\ \hline Description & A mother and daughter & A woman playing with a \\ & speaking, low motion. & ball and a man spinning a \\ & & pen continuously, high \\ & & motion. \\ \hline Frame Size & CIF (352x288) & CIF (352x288) \\ \hline Duration(second) & 30 & 35 \\ \hline Number of frames & 900 & 1065 \\ \hline \end{tabular} \end{table} We run extensive simulation to find parameters that potentially affect $\beta$. \emph{$C_{l}$}, \emph{n} and \emph{QoE} were found to have impact on $\beta$. \emph{QoE} was measured by simulation which will be explained in Section \ref{sec:simulationSetup}. To understand the impact of any of these parameters on $\beta$, the values of the other two parameters (controlling parameter) were kept fixed. The values of the controlling parameters for both sequences are shown in Fig. \ref{beta_bw}, \ref{beta_sessions} and \ref{beta_mos}. These figures also show the relationship between $\beta$ and each of \emph{$C_{l}$}, \emph{n} and \emph{QoE} respectively. Equation (\ref{eq:10}) shows the mathematical relationship between the four parameters. However, in this paper we focus on a value of $\beta$ that produces excellent quality (MOS=5) only. Thus \emph{QoE} was not considered as a variable in the proposed model of $\beta$. The exponential relationship between $\beta$ and QoE shown in Fig. \ref{beta_mos} will be included to the model of $\beta$ in future studies to provide multi-class MOS. \begin{equation} \label{eq:10} \beta \propto \frac{QoE,C_{l}}{n} \end{equation} The simulation data was analyzed with 2-way repeated analysis of variance (ANOVA) \cite{Miller1997} to confirm the significance of \emph{$C_{l}$} and \emph{n} in modeling of $\beta$. Also, it can find the difference between means given by the remaining two parameters \emph{$C_{l}$} and \emph{n}. ANOVA let us understand the effect of parameters and their interaction on $\beta$ which will later be used in the regression modeling. The ANOVA results are shown in Table \ref{table:anova} for F and p-values: the Cumulative Distribution Function (CDF) of F. Parameter with (p$<$0.05) is considered to have significant impact on $\beta$. The analysis results indicate that $\beta$ is affected by each of \emph{$C_{l}$} and \emph{n} as p-values are 0 and 0.0023 respectively. The result also shows that the combined parameters have no interaction effect on $\beta$ because the p-value is 0.6249. This can be justified by the fact that \emph{n} is determined by \emph{$C_{l}$}; the higher capacity of the link, the more sessions are accepted. Based on the value of p in the table, we can conclude that $\beta$ is affected more by \emph{$C_{l}$} than by \emph{n}. The relationship between $\beta$, \emph{n} and \emph{C}$_{l}$ can be established from ANOVA analysis and Fig. \ref{beta_bw} and \ref{beta_sessions}. We found that there is a linear relationship between $\beta$ and \emph{C}$_{l}$ and a polynomial relationship between $\beta$ and \emph{n}. Finally, the rational model shown in Equation (\ref{eq:11}) was formulated to estimate the value of $\beta$ from the nonlinear regression analysis of the simulation data using MATLAB. The values of the coefficients of Equation (\ref{eq:11}) are listed in Table \ref{table:beta_validation_coefficient_slowMovingContents} and \ref{table:beta_validation_coefficient_fastMovingContents}. As \emph{n} is determined by the size of video frames (content dependent), different values for the model coefficients were found for slow (\emph{MAD} sequence) and fast (\emph{Paris} sequence) moving contents. The table also shows the correlation coefficient (R$^2$) and Root Mean Squared Error (RMSE) of the proposed model for both contents. \begin{figure}[!th] \centering \includegraphics[width=\columnwidth, height=6.5cm]{Qadir1.eps} \caption{$\beta$ - Link capacity relationship} \label{beta_bw} \end{figure} \begin{figure}[!th] \centering \includegraphics[width=\columnwidth, height=6.5cm]{Qadir2.eps} \caption{$\beta$ - Number of sessions relationship} \label{beta_sessions} \end{figure} \begin{figure}[!th] \centering \includegraphics[width=\columnwidth, height=6.5cm]{Qadir3.eps} \caption{$\beta$ - \emph{QoE} relationship} \label{beta_mos} \end{figure} \begin{table}[!th] \centering \caption{ANOVA Results for Main and Interaction Effects} \label{table:anova} \begin{tabular}{|c|c|c|c|c|c|} \hline Source & Sum of & Degree of & Mean & F & p-Value \\ & squares & freedom & Squares & & \\ \hline C$_{l}$ & 0.33001 & 1 & 0.33001 & 720.02 & 0 \\\hline n & 0.01807 & 2 & 0.00903 & 19.71 & 0.0023 \\ \hline C$_{l}$*n & 0.00047 & 2 & 0.00023 & 0.51 & 0.6249 \\ \hline \end{tabular} \end{table} \begin{equation} \label{eq:11}\ \beta = \alpha + ( \frac{ C_{l} }{\delta * n} ) \end{equation} \begin{table}[!th] \centering \caption{Coefficients of $\beta$ prediction model and model validation correlation coefficients - slow moving content (\emph{MAD} video sequence)} \label{table:beta_validation_coefficient_slowMovingContents} \begin{tabular}{c|c|c} \hline \multicolumn{2}{|c|}{$\alpha$} & \multicolumn{1}{c|}{$\delta$} \\ \hline \multicolumn{2}{|c|}{-0.5429} & \multicolumn{1}{c|}{0.9689} \\\hline \multicolumn{2}{c}{} & \\\hline \multicolumn{2}{|l|}{Adjusted R$^2$ (Validation)} & \multicolumn{1}{c|}{\%88.44} \\\hline \multicolumn{2}{|l|}{RMSE (Validation)} & \multicolumn{1}{c|}{0.0149} \\\hline \end{tabular} \end{table} \begin{table}[!th] \centering \caption{Coefficients of $\beta$ prediction model and model validation correlation coefficients - fast moving content (\emph{Paris} video sequence)} \label{table:beta_validation_coefficient_fastMovingContents} \begin{tabular}{c|c|c} \hline \multicolumn{2}{|c|}{$\alpha$} & \multicolumn{1}{c|}{$\delta$} \\ \hline \multicolumn{2}{|c|}{-0.1227} & \multicolumn{1}{c|}{1.952} \\\hline \multicolumn{2}{c}{} & \\\hline \multicolumn{2}{|l|}{Adjusted R$^2$ (Validation)} & \multicolumn{1}{c|}{\%90.54} \\\hline \multicolumn{2}{|l|}{RMSE (Validation)} & \multicolumn{1}{c|}{0.0124} \\\hline \end{tabular} \end{table} The model for $\beta$ was proposed based on two video sequences (\emph{MAD} and \emph{Paris}), however the methodology is similar and applies to faster moving content, such as sports, of the same format (CIF). Thus, the model is limited to the video format and coding parameters specified in Table \ref{tab:video}. The model can be applied to other formats and coding parameters with different coefficient values. This is because other formats and/or coding parameters generate different frame sizes and bit rates which control the number of sessions (parameter \emph{n} in the model) for a specific link capacity (parameter C$_{l}$ in the model). They only have impact on the value of the coefficients of the model. The model will be validated by CIF and QCIF video formats in Section \ref{sec:validation}. \section{Results and Analysis} \label{sec:resultANDdiscuttion} The simulation environment is explained in Section \ref{sec:simulationSetup}. Section \ref{sec:comparison} compares the proposed \emph{Pro-IBMAC} to \emph{CBAC} in terms of MOS and number of the sessions, packet drop ratio and delay. The impact of $\beta$ on the functionality of \emph{Pro-IBMAC} is discussed in Section \ref{sec:beta_Impact}. \subsection{Simulation Setup} \label{sec:simulationSetup} Since the number of admitted sessions for a specific link capacity is the target of this study, only acceptance/rejection policy of admission control was investigated. Queue size and simulation time were chosen so as not to cause drop due to insufficient queue length or time. The video format such as CIF or QCIF has impact on the number of admitted sessions due to the difference in the size of encoded frames. In this paper, CIF (352x288) is assumed for input video as an acceptable video format for most video capable devices such as handsets and mobiles \cite{Khan2012}. It is also suitable for videoconferencing systems delivered on telephone lines. While modern devices support much higher resolution, CIF makes packet level simulation practical. A bottleneck link of dumbbell topology over which the video sources send to their peer destinations was considered for the implementation of the proposed \emph{Pro-IBMAC} scheme. In addition to $\beta$, \emph{$C_{l}$} was the main variable in the simulation. Other parameters such as link delay, queue length, packet size were kept fixed. Lost packets were replaced with 0 by the etmp4 \cite{Gross2004} decoder as a way for coping with the losses. The values of the simulation parameters and settings are shown in Table \ref{tab:parameter_settings}. \begin{table}[!th] \centering \caption{Encoder and Network Settings} \label{tab:parameter_settings} \begin{tabular}{ |l|l|l| } \hline & Parameter & Value \\ \hline \multirow{3}{*}{Encoder} & Frame size & CIF(352x288) \\ & Frame rate & 30fps \\ & Group of picture & 30 \\ \hline \multirow{8}{*}{Network} & \emph{$C_{l}$}(Mbps) & 22, 24, 30, 36, 39, 40 \\ & Topology & Dumbbell \\ & Packet size(byte) & 1024 \\ & UDP header size(byte) & 8 \\ & IP Header Size(byte) & 20 \\ & Queue size(packet) & 5300 \\ & Queue management algorithm & Droptail \\ & Queue discipline & FIFO(First In First Out) \\ & Simulation time(second) & 500 \\ \hline \end{tabular} \end{table} New sessions were requested randomly and continuously every second. They were accepted as long as there was enough bandwidth on the bottleneck link i.e: Equation (\ref{eq:9}) was satisfied. NS-2 \cite{ns2} was used to measure \emph{CalR($\tau$)} and \emph{Pro-IAAR} and implement \emph{CBAC} and \emph{Pro-IBMAC}. The implementation of the proposed \emph{Pro-IBMAC} is summarized in Algorithm \ref{pro-ibmac}. \begin{algorithm}[h] \caption{Proposed \emph{Pro-IBMAC}} \label{pro-ibmac} \begin{algorithmic} \Statex $Given\ \emph{$C_{l}$},\ x_{new}\ and\ \emph{n}$ \For {$Every\ video\ session\ request$} \Statex $Compute\ \mu_S(t)\ from\ Equation\ (\ref{eq:5})$ \Statex $Compute\ \beta\ from\ Equation\ (\ref{eq:11})$ \Statex $Compute\ Pro\textit{-}IAAR(t)\ from\ Equation\ (\ref{eq:6})$ \If{ $Equation\ (\ref{eq:9}) = True$ } \State $Request\ accepted$ \Else \State $Request\ rejected$ \EndIf \EndFor \end{algorithmic} \end{algorithm} The time window $\tau$ has an impact on the operation of the admission control. The smaller the value of $\tau$, the more conservative the admission control and more sensitive to the traffic bursts. On the other hand, the larger the value of $\tau$, the smoother the measured rate and less reactive to the changes in the network load. In practice, $\tau$ will be a few seconds \cite{Latre2011}. In this paper, \emph{IAAR(t)} was averaged over 1-second. The \emph{MAD} video sequence described in Table \ref{tab:video} was fed to the NS-2 simulator using EvalVid \cite{Gross2004}. Evalvid provides a set of tools to analyze and evaluate video quality by means of PSNR and MOS metrics. The Evalvid MOS metric (We call it simulated MOS) was used in this paper which calculates the average MOS value of all frames for the entire video with a number between 1 and 5, instead of the frame-wise PSNR metric. The MOS metric represents the impression of the user for the entire received video and has been widely used by research community \cite{Li2010,Khan2010a,Kim2012,Khan2009a,Tommasi2014,Papadimitriou2007,Khan2009,Ma2012,Aguiar2008,Erdelj2013,Tan2013,Escuer2014}. Although the MOS metric does not map very well to the subjective impression for a long video sequence, it was used for short video sequences (30-35 seconds) in this paper. In addition to the MOS metric, we calculated the Distortion In Interval (DIV) metric \cite{Gross2004} to restrict the MOS metric within a fixed interval (30 frames in this paper). This stringent metric calculates the maximum percentage of received frames with a MOS smaller than that of the sent frame within a given interval. The efficiency of the proposed \emph{Pro-IBMAC} and \emph{CBAC} was evaluated based on MOS, number of sessions, packet drop ratio and mean delay. These performance metrics were chosen due to their impact on multimedia traffic. The performance of \emph{Pro-IBMAC} was tested to find the maximum number of video sessions on a bottleneck link while keeping the QoE of each session at acceptable or required levels. This was compared to other procedures such as \emph{CBAC}. The objective was to see how \emph{Pro-IBMAC} utilizes the available bandwidth compared to \emph{CBAC}. Further simulations were used to investigate the effect of parameter $\beta$ on the performance metrics. \subsection{\emph{Pro-IBMAC} vs \emph{CBAC}} \label{sec:comparison} It has been found that there is a considerable difference between the two schemes in terms of the number of accepted sessions. This is plotted in Fig. \ref{session_mos}. The number of admitted sessions is always higher for \emph{Pro-IBMAC}. The difference between the number of admitted sessions increases with increasing of the link capacity. For example, the number of admitted sessions to 22Mbps link is 15 against 14 for \emph{Pro-IBMAC} and \emph{CBAC} respectively, whereas it is 30 against 25 in the case of 40Mbps link. The main role of any admission control is to ensure that the acceptance of a new session does not violate the QoE of on-going sessions. We computed the MOS of every single accepted session for both schemes. We found that increase in \emph{n} does not come at the cost of QoE as all accepted sessions by \emph{Pro-IBMAC} and \emph{CBAC} were scored MOS 5. Note that the MOS of video sessions is labeled on the secondary y-axis in the figure. The value of $\beta$ that produces this increase in \emph{n} and guarantees the video quality is also shown in the figure. This will be further described in Section \ref{sec:beta_Impact}. However this simulation outcome can not be generalized. \emph{Pro-IBMAC} may not guarantee the same level of QoE as \emph{CBAC} in a real implementation. This is because our proposed scheme is based on a probabilistic approach therefore, there is a possibility of the upper bound to be lower than the bursty instantaneous rate, especially for small $\tau$. \begin{figure}[!th] \centering +-\includegraphics[width=\columnwidth, height=5cm]{Qadir4.eps} \caption{MOS of the \emph{CBAC} and \emph{Pro-IBMAC} admitted sessions} \label{session_mos} \end{figure} Table \ref{tab:packetdropratio_BW} shows mean MOS and DIV. The DIV values (0\%) indicate that all received frames have the same MOS as of the original frames. It also lists the packet drop ratio of the accepted sessions of \emph{Pro-IBMAC} and \emph{CBAC} for each link. Since we aim at a $\beta$ value that doesn't degrade the MOS of received videos, as mentioned in Section \ref{sec:beta}, no packet drop was expected. \begin{table}[!th] \centering \caption{Packet drop ratio and admitted sessions of \emph{Pro-IBMAC} and \emph{CBAC}} \label{tab:packetdropratio_BW} \begin{tabular}{|c|c|c|c|c|c|c|} \hline \multicolumn{4}{|c|}{{}} & \multicolumn{2}{c|}{{\emph{Pro-IBMAC}}} & \emph{CBAC} \\\hline \emph{$C_{l}$}(Mbps) & Packet & & & & & \\ & Drop & MOS & DIV & $\beta$ & \emph{n} & \emph{n}\\ & \% & & \% & & & \\ \hline 22 & 0 & 5 & 0 & 0.96 & 15 & 14 \\\hline 24 & 0 & 5 & 0 & 0.95 & 17 & 15 \\\hline 30 & 0 & 5 & 0 & 0.94 & 21 & 19 \\\hline 36 & 0 & 5 & 0 & 0.87 & 26 & 23 \\\hline 39 & 0 & 5 & 0 & 0.84 & 29 & 25 \\\hline 40 & 0 & 5 & 0 & 0.83 & 30 & 25 \\\hline \end{tabular} \end{table} As for the delay, we measured the mean delay using the ns-2 trace files for both schemes. Fig. \ref{meanDelay_both_CDF} illustrates the CDF of the mean delay for the \emph{Pro-IBMAC} and \emph{CBAC} sessions for 40Mbps link. As shown in Table \ref{tab:packetdropratio_BW}, 30 sessions are accepted by \emph{Pro-IBMAC} for $\beta$=0.83 and 25 by \emph{CBAC}. More sessions on the same link by \emph{Pro-IBMAC} caused higher delay due to more buffering. Therefore the \emph{Pro-IBMAC} sessions experienced higher delay compared to the lower delay of the \emph{CBAC} sessions. Nevertheless, increase in the delay that comes at the cost of the optimization of QoE-Session can not be tolerated by real-time video traffic. For \emph{Pro-IBMAC} to be applicable to realtime traffic, a proper value of $\beta$ must be selected. Video streaming services can tolerate a delay of 5-seconds \cite{Szigeti2004}, thus it can be used within this limit. In future work, we will further investigate this relationship and develop the model of $\beta$ to include delay as another variable. \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir5.eps} \caption{CDF of the mean delay of the \emph{CBAC} and \emph{Pro-IBMAC} sessions} \label{meanDelay_both_CDF} \end{figure} \subsection{The Impact of $\beta$ on \emph{Pro-IBMAC}} \label{sec:beta_Impact} As mentioned earlier, parameter $\beta$ controls the degree of risk between the admission decision and QoE of existing sessions. Fig. \ref{rate_all} shows \emph{IAAR(t)} (dash-dot line) and the upper limit of the exceedable aggregate rate (solid line) that allows more sessions (compared to sessions allowed by \emph{IAAR(t)}), without QoE degradation of enrolled video sessions. The proposed value of $\beta$ for four scenarios (22, 30, 36 and 40Mbps) is shown in the figure. It can be seen that the lower the value of $\beta$, the wider the gap between the two rates. Decreasing $\beta$ causes increase in the limit of the exceedable rate. This makes \emph{Pro-IBMAC} more flexible and it accepts more sessions. This can be better observed in Fig. \ref{session_bandwidth}. It depicts the number of admitted sessions for different link scenarios. The solid line shows the number of sessions admitted by \emph{CBAC}, while the other three lines show sessions admitted by \emph{Pro-IBMAC} for three different value of $\beta$ (0.9, 0.85 and 0.78). For the same link, the linear relationship between \emph{n} and \emph{$C_{l}$} allows more sessions to be accepted by lowering the value of $\beta$. For instance, for 39Mbps link, \emph{Pro-IBMAC} accommodates 27, 28 and 30 sessions for $\beta$=0.9, 0.85 and 0.78 respectively compared to 25 sessions of CBAC. Note that $\beta$ $\ge$ 0.84 guarantees accepted sessions with MOS 5 as shown in Table \ref{tab:packetdropratio_BW}. \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir6.eps} \caption{IAAR and upper limit of the exceedable rate for different link capacities} \label{rate_all} \end{figure} \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir7.eps} \caption{Admitted sessions of \emph{CBAC} and \emph{Pro-IBMAC} for different link capacities} \label{session_bandwidth} \end{figure} However, continuous decreasing of $\beta$ will degrade the QoE of admitted sessions as more sessions are accepted. Therefore, care is required to fine tune the value of $\beta$ that optimizes the operation of \emph{Pro-IBMAC}. The aim is to accept as many sessions as possible, while keeping the QoE of the sessions at required levels. As per the proposed model, the value of $\beta$ depends on \emph{$C_{l}$}, \emph{n} and required \emph{QoE}. We investigated this further for 22Mbps and 24Mbps links. Fig. \ref{beta_MOS_sessions_22Mbps} shows the number of MOS 2, 3, 4 and 5 sessions separately as well as total number of sessions for 22Mbps link. If we consider that the required class of QoE is MOS 5, then the proposed value of $\beta$ is 0.96, i.e. for $\beta$ less than 0.96, sessions with multi-MOS levels exist, while for $\beta$ $\ge$ 0.96 all sessions score a MOS of 5. It also can be seen in Fig. \ref{beta_MOS_sessions_22Mbps} that decreasing $\beta$ from 0.96 to 0.5 increases the total number of sessions and number of MOS 3 and 2 sessions while decreasing the number of MOS 5 and 4 sessions. \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir8.eps} \caption{Impact of $\beta$ on MOS and \emph{n}, \emph{$C_{l}$}=22Mbps} \label{beta_MOS_sessions_22Mbps} \end{figure} In another scenario, we found that the proposed value of $\beta$ is 0.95 for 24Mbps link as shown in Fig. \ref{beta_MOS_sessions_24Mbps}. $\beta$ of 0.95 or greater, maintains the MOS of accepted sessions at 5, while $\beta$ less than 0.95 produces sessions with multi-MOS classes which comes at the cost of the QoE of enrolled sessions. For instance, $\beta$ of 0.8 creates 18 sessions with MOS 4 and 1 session with MOS 3. Whilst $\beta$ of 0.6 changes the number of MOS 4 sessions to 5 and MOS 3 sessions to 19 . Note that there are 19 sessions in total for $\beta$=0.8 and 24 sessions for $\beta$=0.6. Fig. \ref{beta_MOS_sessions_22Mbps} and \ref{beta_MOS_sessions_24Mbps} also show the DIV values of accepted sessions at different $\beta$ values. As the DIV was 0\% for sessions with MOS 5 and between 0\% and 100\% for sessions with MOS\textless5, in the figures we simply labeled DIV=0 to denote all the accepted sessions are MOS 5 and 0\textless DIV\textless100 denote that MOS of sessions are less than 5. \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir9.eps} \caption{Impact of $\beta$ on MOS and \emph{n}, \emph{$C_{l}$}=24Mbps} \label{beta_MOS_sessions_24Mbps} \end{figure} Although most real-time applications can tolerate some packet loss, more than an acceptable level may degrade the quality of received video. As expected, fewer sessions of \emph{CBAC} will guarantee no packet loss, in contrast extra added sessions of \emph{Pro-IBMAC} cause packet drop when $\beta$ is set lower than the proposed value and increases slightly with the increase of the number of sessions. Table \ref{table:packetdropratio_C} presents the percentage of the packet drop ratio of the \emph{Pro-IBMAC} admitted sessions for different value of $\beta$ for 22Mbps link. The ratio increases with the decrease of $\beta$ due to fitting a higher number of sessions into the same link. The table shows 0.45\%, 4.06\% and 6.70\% drop of the total number of packets for $\beta$= 0.89, 0.85 and 0.78 respectively. The proposed value of $\beta$ (0.96) ensures that no packets are dropped as shown in the table. \begin{table}[!th] \centering \caption{Packet drop ratio and admitted session of \emph{Pro-IBMAC} for different $\beta$, \emph{C}$_{\emph{l}}$ = 22Mbps} \label{table:packetdropratio_C} \begin{tabular}{|c|c|c|} \hline $\beta$ & Packet Drop Ratio \% & \emph{n}\\ \hline 0.96 & 0 & 15 \\\hline 0.89 & 0.45 & 16 \\\hline 0.85 & 4.06 & 17 \\\hline 0.78 & 6.70 & 18 \\\hline \end{tabular} \end{table} Improper values of $\beta$ not only causes packet drop, but it also degrades the MOS levels (discussed earlier) and increases the delay. Fig. \ref{meanDelay_both_CDF} demonstrates how a high number of sessions caused by a low value of $\beta$ can contribute to the increase of the delay which can be substantial for a large number of sessions. The disadvantage of lowering the value of $\beta$ is not only that it causes degradation to the MOS level of video sessions, or increase in the delay and packet loss. We observed that the decoder takes longer to decode and play back the received video for low value of $\beta$, for instance when $\beta$=0.6 for 24Mbps link. The ISP can tune the value of $\beta$ to control the trade-off between providing the required level of QoE and increasing their revenue by accommodating as many user sessions as possible. \section{Subjective Tests} \label{sec:subjectiveTest} We performed subjective tests to involve human subjects in rating the quality of videos. The tests followed the ITU-R BT.500-13 recommendation \cite{ITU-R2012}. The five-grade scale from 1 to 5 of the Single Stimulus (SS) adjectival categorical judgment method was used in which 1 represents 'bad' and 5 represents 'excellent' quality. Each video was presented in random order and rated individually by 17 subjects one at a time. The number of participants exceeded the minimum recommended number (15 subjects). As the \emph{MAD} sequence was chosen, 48 videos delivered through different link capacities and different values of $\beta$ shown in Table \ref{tab:packetdropratio_BW}, Fig. \ref{beta_MOS_sessions_22Mbps} and Fig. \ref{beta_MOS_sessions_24Mbps} were used in the tests. They were decoded from the simulations and selected from Fig. \ref{session_mos} (MOS 5), Fig. \ref{beta_MOS_sessions_22Mbps} (MOS 2, 3, 4 and 5) and Fig. \ref{beta_MOS_sessions_24Mbps} (MOS 3, 4 and 5). The description of the testing video sequence, coding and network parameters were the same as described in Tables \ref{tab:video} and \ref{tab:parameter_settings}. Each video was identified by the MOS value calculated with Evalvid, regardless of the capacity of the link and/or value of $\beta$. The aim was to have variety of videos with different MOS values through changing the capacity of the link and value of $\beta$. The simulated $\beta$ and predicted $\beta$ of the testing videos will be plotted in Section \ref{sec:validation}. The videos were presented in their original size (352x288), embedded in a separate web page with grey background and rated on the same page. There were two sessions, each lasting up to 30 minutes with 10 minutes break in between. To stabilize the subjects' opinion, five dummy videos were displayed at the beginning of the session without considering their scores. Prior to the actual rating, the subjects were carefully introduced to the assessment method, likely quality artifacts that might be observed, rating scale and timing. They were given unrestricted time and the viewing distance was comfortable. The tests were conducted in a white background laboratory on 29 inch LCD monitor (Dell P2213) with 1680x1050 resolution and 32 bit true color. 5 female and 12 male non-expert observers participated in the tests. All participants were university students, 1 in the range of 18-25, 7 in the range of 26-30 and 9 over 30. At the end of the tests, subjects who were surveyed on the duration and comfortability of the tests did not express any concern. The subjects were screened for any possible outliers following the screening procedure of the SS method \cite{ITU-R2012}. Two subjects have been eliminated and their data were not considered in the analysis. The MOS was calculated by taking the mean score for each of the videos following the procedure described in \cite{ITU-R2012}. The bar chart in Fig. \ref{fig:scores_percentage_video} illustrates the subjective mean MOS of every presented video with the confidence interval. It shows the mean and range (the upper and lower limits) of MOS given to each video by the subjects. The analysis shows that around 40\% of the scores went for a MOS of 3.5. The distribution of the scores is plotted in Fig. \ref{fig:scores_percentage_mos}. \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir10.eps} \caption{Bar chart of the subjective MOS with confidence interval for individual video} \label{fig:scores_percentage_video} \end{figure} \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir11.eps} \caption{Bar chart of the percentage of scores of the subjective MOS} \label{fig:scores_percentage_mos} \end{figure} \section{Validation of the Proposed Model} \label{sec:validation} In this section, the validation of the proposed model of $\beta$ with simulation results is explained. It also demonstrates the validation of the simulated MOS with subjective MOS. The scatter plot in Fig. \ref{mos_validation} shows the simulated MOS against subjective MOS. Overall, the subjects were irritated by video impairments, their scores therefore underestimate the simulation scores. The majority of simulated MOS scores seen are higher than subjective MOS. However, both scores are getting closer for less impaired videos (subjective MOS between 4.78-5). These videos were delivered with the proposed values of $\beta$ for each value of \emph{$C_{l}$}. Note that as there are about 11 overlapping scores within this range, all can not be seen in the figure. Overlapping of the scores can be further noticed in Fig. \ref{fig:scores_percentage_video}, in which there are 11 scores in the range of 4.78-5. The relationship is nearly linear correlated for videos delivered with the proposed value of $\beta$ that have MOS close to 5. This indicates that the model can provide better quality for end users with the proposed value of $\beta$. \begin{figure}[!th] \centering \includegraphics[width=\linewidth]{Qadir12.eps} \caption{Validation of the simulated MOS with subjective MOS} \label{mos_validation} \end{figure} $\beta$ predicted by the model (Equation \ref{eq:11}) has been validated by the one found by simulations. Fig. \ref{beta_validation_without_MOS_Separate_cif} shows the resulting $\beta$'s scatter point plot of the predicted $\beta$ against simulated $\beta$ for slow and fast moving contents separately. As shown in Tables \ref{table:beta_validation_coefficient_slowMovingContents} and \ref{table:beta_validation_coefficient_fastMovingContents}, the model of $\beta$ suits fast moving content with a correlation coefficient of 90.54\% compared to 88.44\% for slow moving content. This can be also observed in Fig. \ref{beta_validation_without_MOS_Separate_cif}. Thus, the model best suits dynamic content with high variation in bitrate. Note that there were few videos for each value of $\beta$ plotted in the figure, therefore the number of plotted points is less than the number of the testing videos (48). \begin{figure}[!th] \centering \includegraphics[width=\columnwidth]{Qadir13.eps} \caption{Validation of the proposed model of $\beta$ with simulation results} \label{beta_validation_without_MOS_Separate_cif} \end{figure} As mentioned in Section \ref{sec:beta}, the model of $\beta$ can be applied to other video formats with different values of coefficients $\alpha$ and $\delta$. It has been validated by QCIF video format using the 45-seconds \emph{Deadline} video sequence of 1374 frames. The model achieved an adjusted R$^2$ of 83.59\% and RMSE of 0.0194. The values of $\alpha$ and $\delta$ were -0.1323 and 0.4991 respectively. \section{Conclusion} \label{sec:conclusion} We proposed a novel algorithm to find the upper limit of the video total rate that can exceed a specific link capacity without QoE degradation of ongoing video sessions. A mathematical model for the measurement algorithm was developed and implemented in an admission control system. Its performance has been validated by simulating publicly available video sequences and subjective tests. The exceedable limit has been defined by parameter $\beta$ in the algorithm. This parameter can be used by ISPs to balance the trade-off between QoE and the number of video sessions. The simulation results have shown that the proposed admission control compared to calculated rate-based admission control optimizes the trade-off relationship between QoE-Session through fine tuning the value of $\beta$. The proposed algorithm can be applied within the scope of the video format and coding parameters specified in this paper. In future work, we will further develop the model of $\beta$ to include delay as another variable. The calculated MOS will be compared with SSIM metric. Moreover, an implementation of the proposed scheme in a cross-layer architecture for optimizing the QoE of video session will be investigated. \section{Acknowledgment} The authors would also like to thank volunteers for their participation in the subjective tests and the anonymous reviewers for their constructive comments. \ifCLASSOPTIONcaptionsoff \newpage \fi \bibliographystyle{IEEEtran}
{'timestamp': '2020-08-18T02:20:55', 'yymm': '2008', 'arxiv_id': '2008.07011', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07011'}
arxiv
\section{Conclusions} \label{sec:conc} Successive cancellation (SC) decoding was introduced for the class of product codes obtained by iterating single parity-check (SPC) codes, namely SPC product codes. As a byproduct, \textcolor{black}{the relations between \ac{SPC} product and multi-kernel polar codes were studied, which enables us to use tools of the latter.} SPC product codes have been, then, analyzed under \ac{SC} \textcolor{black}{decoding} over the binary \textcolor{black}{memoryless symmetric channels, in particular, over the binary-input additive white Gaussian (B-AWGN) channel and the binary erasure channel (BEC)}. Successive cancellation list (SCL) decoding has been described for \ac{SPC} product codes as well, which outperforms belief propagation (BP) decoding even with a considerably small list sizes, e.g., $L=4$, for the demonstrated example \textcolor{black}{over the B-AWGN channel}. Larger gains are attained by concatenating an inner \ac{SPC} product code with a high-rate outer code. The \textcolor{black}{maximum-likelihood} performance \textcolor{black}{(with an outer code)} was analyzed via \textcolor{black}{(average)} distance spectrum by developing an efficient method to compute \textcolor{black}{the (input-output) weight enumerator} of short \ac{SPC} product codes, \textcolor{black}{which is shown to be achieved via \ac{SCL} decoding with moderate list sizes for the considered example.} \textcolor{black}{While the asymptotic analysis over the BEC under SC decoding has shown, for some specific product code sequences, a considerable gap to channel capacity, finite-length results on \ac{SPC} product codes show that they are well-suited for SC and SCL decoding, with performance gains over BP decoding that are especially visible when an outer error detection code is used in combination with the list decoder.} \subsection{Analysis over the Binary Erasure Channel} In the following, we analyze the \ac{SC} decoder of \ac{SPC} product codes over the \ac{BEC}. We do so to gain a deeper understanding on the behavior of the \ac{SC} decoder when applied to the code construction under investigation. We start by analyzing the behavior of \textcolor{black}{an $(n,n-1)$} \ac{SPC} code with generator matrix \textcolor{black}{$\boldsymbol{G}$ over the \ac{BEC}($\epsilon_{\mathrm{ch}}$)}. We denote by $\textcolor{black}{\epsilon^{(i)}_{\boldsymbol{G}}}$ the erasure probability for the $i$-th information bit after \ac{SC} decoding conditioned on the knowledge of the $i-1$ preceding information bits, $i=1,\ldots , n-1$. \textcolor{black}{When the knowledge of the $i-1$ preceding information bits is available, then the decoding of the $i$-th information bit is successful either when $y_{i+1} = ?$ or there is no erasure in the subvector $(y_1,y_{i+2}^{n})$. Hence,} the relationship between the input-output erasure probabilities is given by \textcolor{black}{\begin{equation} \textcolor{black}{\epsilon^{(i)}_{\boldsymbol{G}}}=\epsilon_{\mathrm{ch}}\left(1-\left(1-\epsilon_{\mathrm{ch}}\right)^{n-i}\right),\quad i\in [n-1]. \label{eq:erasure_SPC} \end{equation}} Based on the relation given in \eqref{eq:erasure_SPC}, we proceed by bounding the performance of an $(n,k)$ \ac{SPC} product code $\mathcal{C}$, via \eqref{eq:SC_bound}. In particular, we can derive the erasure probability associated with the information bit $u_i$ of an \ac{SPC} product code under the genie-aided \ac{SC} decoding by iterating \eqref{eq:erasure_SPC}. \textcolor{black}{More precisely, for $i \in [k]$, we have the recursion in $m$ as \begin{equation} \epsilon^{(i)}_{\boldsymbol{G}^{[m]}}=\epsilon^{(j +1)}_{\boldsymbol{G}^{[m-1]}}\left(1-\left(1-\epsilon^{(j +1)}_{\boldsymbol{G}^{[m-1]}}\right)^{n_m-t}\right) \label{eq:erasure_SPC_PC} \end{equation} with $j = \lfloor\nicefrac{(i-1)}{k_m}\rfloor$ and $t = [(i-1)\!\!\mod k_m] +1$ where $k$ information bits are divided into $k^{[m-1]}$ blocks $\boldsymbol{u}_{j}^{[m]}$, $j\in[k^{[m-1]}]$, of size $k_m$ (see Fig. \ref{fig:transmission_recursive}).} Let $\epsilon_i$ be a shorthand for $\textcolor{black}{\epsilon^{(i)}_{\boldsymbol{G}^{[m]}}}$, i.e., $\epsilon_i\triangleq\textcolor{black}{\epsilon^{(i)}_{\boldsymbol{G}^{[m]}}}$ $i=1,\ldots,k$.\footnote{If the blocklength and the rate of an \ac{SPC} product code is given, then there exists a unique sequence of component codes satisfying the parameters \textcolor{black}{\eqref{eq:parameters}}. For such a sequence, when the blocklengths of component codes are not equal, then a question is what decoding order should be adopted. The natural approach is to start the decoding from the lowest rate \ac{SPC} component code, i.e., to treat it as the component code in the first level as in Fig. \ref{fig:size9_polar_construction_PC}(b), because a code with a lower rate has a higher error-correction capability. \textcolor{black}{This ordering has also been verified via numerical computation for an exemplary construction provided as Example \ref{sec:asymptotic1}, where a larger threshold is obtained if the decoding is performed in the reverse order of the component code rates.}} \textcolor{black}{Since the \ac{RHS} of \eqref{eq:erasure_SPC_PC} is monotonically increasing in the input erasure probability $\epsilon^{(j +1)}_{\boldsymbol{G}^{[m-1]}}$ and monotonically decreasing in $t$,} the largest bit erasure probability is equal to that of the first decoded information bit, i.e., \begin{equation} \epsilon_{\mathrm{max}}\triangleq \max_{i=1,\ldots,k} \epsilon_i = \epsilon_1. \end{equation} By rewriting \eqref{eq:SC_bound} in terms of $\textcolor{black}{\epsilon}_i$, we obtain \begin{equation} \textcolor{black}{\epsilon}_{\mathrm{max}}\leq P_{\mathrm{SC}} \leq \sum_{i=1}^k \textcolor{black}{\epsilon}_i \label{eq:UB_Product}. \end{equation} A loose upper bound can be obtained by tracking only the largest erasure probability \textcolor{black}{for $i=1$}, i.e., \begin{equation} P_{\mathrm{SC}} \leq k\textcolor{black}{\epsilon}_{\mathrm{max}}. \label{eq:LooseUB_Product} \end{equation} \subsubsection{\textcolor{black}{Comparison with Elias' Decoder}} Remarkably, \eqref{eq:erasure_SPC_PC} also describes the evolution of the bit erasure probabilities under Elias' decoder \cite{Elias:errorfreecoding54} by setting $i=1$. The following lemma, together with Theorem \ref{theorem:comparison}, formalizes the relation between the error probability of \ac{SC} decoding and the one of the decoding algorithm proposed by Elias. \begin{lemma} For an \ac{SPC} product code, the erasure probability of the first decoded information bit under \ac{SC} decoding is equal to the erasure probability of each information bit under Elias' decoding. \label{lem:worst_channel} \end{lemma} \begin{proof} \textcolor{black}{Consider the input-output relation \eqref{eq:erasure_SPC} for an $(n,n-1)$ \ac{SPC} code under \ac{SC} decoding. In the case of Elias' decoding each bit is decoded in parallel without any knowledge of the information bits; therefore, each bit has the same erasure probability. This probability is obtained by setting $i=1$ in \eqref{eq:erasure_SPC} since the decoder does not have access to the knowledge of any information bit in this case. The same applies for the other decoding levels; hence,} the recursion \eqref{eq:erasure_SPC_PC} for $i=1$ also provides the erasure probability of any information bit under Elias' decoding. \end{proof} As a result \textcolor{black}{of Lemma \ref{lem:worst_channel}}, the bound \eqref{eq:LooseUB_Product} holds also for \textcolor{black}{the block error probability $P_{\mathrm{E}}$ under} Elias' decoding\textcolor{black}{, i.e., we have} \begin{equation} \label{eq:bounds_ED} \textcolor{black}{\epsilon}_{\mathrm{max}} < P_{\mathrm{E}} \leq k \textcolor{black}{\epsilon}_{\mathrm{max}}. \end{equation} By comparing \eqref{eq:LooseUB_Product} with the \ac{RHS} of \eqref{eq:bounds_ED}, the question on whether the two algorithms provide the same block error probability may arise. In the following, it is shown that the \textcolor{black}{block error probability under \ac{SC} decoding is upper bounded by the block error probability under Elias' decoding}. \begin{theorem} For an \textcolor{black}{$(n,k)$} \ac{SPC} product code, the block error probabilities under \ac{SC} and Elias' decoding over the \ac{BEC}($ \epsilon $) satisfy \begin{equation} \textcolor{black}{P_{\mathrm{SC}} \leq P_{\mathrm{E}}}. \end{equation} \label{theorem:comparison} \end{theorem} \begin{proof} The $i$-th bit error event under Elias' decoder is \begin{equation*}\label{eq:elias_bit_error_event} \mathcal{B}_{\mathrm{E},i} \triangleq \{(\boldsymbol{u}, \boldsymbol{y})\in\mathcal{X}^k\times\mathcal{Y}^n: \hat{u}_i^{(\mathrm{E})}(\boldsymbol{y}) \neq u_i\} \end{equation*} with $ \hat{u}_i^{(\mathrm{E})}(\boldsymbol{y}) $ being the output of Elias' decoder for $u_i$. \textcolor{black}{First, we} show that \textcolor{black}{over the \ac{BEC}} $\mathcal{B}_{\mathrm{SC},i}^{\mathrm{GA}}\subseteq\mathcal{B}_{\mathrm{E},i}$. \textcolor{black}{To this end, we write \begin{align} &\mathcal{B}_{\mathrm{SC},i}^{\mathrm{GA}} = \{(\boldsymbol{u}, \boldsymbol{y})\in\mathcal{X}^k\times\mathcal{Y}^n: \hat{u}_i^{(\mathrm{SC})}(\boldsymbol{y},u_1^{i-1}) = ?\} \\ &= \!\{\!(\boldsymbol{u}, \boldsymbol{y})\!\in\!\mathcal{X}^k\times\mathcal{Y}^n\!:\! \hat{u}_i^{(\mathrm{SC})}(\boldsymbol{y},u_1^{i-1}) = ?, \hat{u}_i^{(\mathrm{E})}(\boldsymbol{y}) = ?\}\label{eq:equality}\\ &\subseteq \!\{\!(\boldsymbol{u}, \boldsymbol{y})\!\in\!\mathcal{X}^k\times\mathcal{Y}^n\!:\! \hat{u}_i^{(\mathrm{E})}(\boldsymbol{y}) = ?\} = \mathcal{B}_{\mathrm{E},i}\label{eq:equality2} \end{align} where \eqref{eq:equality} follows from the fact that an erasure at the output of genie-aided SC decoding of the $i$-th bit implies an erasure for its Elias' decoding. Combining \eqref{eq:equality2} with Lemma~\ref{lem:block_error} concludes the proof.} \end{proof} \textcolor{black}{Fig. \ref{fig:sc_125_64_SPC_bec} illustrates the simulation results for the $3$-dimensional $(125,64)$ \ac{SPC} product code, obtained by iterating $(5,4)$ \ac{SPC} codes, over the \ac{BEC}. The results are provided in terms of \ac{BLER} vs. channel erasure probability $\epsilon_{\mathrm{ch}}$. The \ac{SC} decoding performance is compared to the performance under Elias' decoding. The former outperforms the latter. The tight upper bound on the \ac{SC} decoding, computed via the \ac{RHS} of \eqref{eq:UB_Product}, is also provided.} \begin{figure}[t] \begin{center} \includegraphics[width=1\columnwidth]{./figures/125_64_SPC_document_1_bec.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{BLER} vs. $\epsilon_{\mathrm{ch}}$ under \ac{SC} decoding for the $(125,64)$ product code, compared to Elias' decoding.}}\label{fig:sc_125_64_SPC_bec} \end{figure} \textcolor{black}{\begin{remark} The inequality in Theorem \ref{theorem:comparison} can be made strict for an $m$-dimensional product code with $m>1$ and for which $\exists\ell\in\{1,\dots,m\}$ such that $n_\ell>2$. The proof is tedious as it requires the definition of erasure patterns that are resolvable by the \ac{SC} decoder while Elias' decoder fails. The general expression of such erasure patterns yields a complicated expression that we omit. In the following, we provide an example of such a pattern for the $(9,4)$ \ac{SPC} product code. \end{remark}} \begin{example}\label{example:comparison} Consider transmission \textcolor{black}{over the \ac{BEC}} using the $ (9,4) $ product code with the received vector $ \boldsymbol{y} = \{0,?,?,?,0,?,0,0,0\}$, where $\mathcal{E}=\{2,3,4,6\}$. Under \ac{SC} decoding, the message is decoded correctly while Elias' decoding would fail to decode the $3$rd information bit \textcolor{black}{as provided in Fig. \ref{fig:size9_polar_PC_ex}}. \begin{figure} \centering \begin{subfigure}{0.5\textwidth} \includegraphics[width=1\textwidth]{./figures/size9_spc_polar_construction_PC2_example2} \vspace{-0.5cm} \caption{} \end{subfigure} \begin{subfigure}{0.5\textwidth} \includegraphics[width=1\textwidth]{./figures/size9_spc_polar_construction_PC2_example2_SC} \vspace{-0.5cm} \caption{} \end{subfigure} \caption{\textcolor{black}{(a) illustrates the output of Elias' decoding and (b) shows that $u_3$ indeed is correctly decoded by \ac{SC} decoding for this erasure pattern. Note that the blue labeled values denote the hard-decisions propagating from left to right in SC decoding.}} \label{fig:size9_polar_PC_ex} \end{figure} \end{example} \subsubsection{Asymptotic Performance Analysis}\label{subsec:asymptotic} We consider now the asymptotic performance of \ac{SPC} product codes. More specifically, we analyze the error probability of a \emph{product code sequence}, defined by \textcolor{black}{an ordered} sequence of component code sets \[ \mathscr{C}^{\textcolor{black}{[m]}}=\left\{\mathcal{C}_1, \mathcal{C}_2, \ldots, \mathcal{C}_m\right\} \] where we constrain $\left|\mathscr{C}^{\textcolor{black}{[m]}}\right|=m$, i.e., where the number of component codes for the $m$-th product code in the sequence is set to $m$\textcolor{black}{, and the component code rates satisfy $R_i\leq R_j$ for $i<j$}. \textcolor{black}{We denote by $\mathcal{C}^{\textcolor{black}{[m]}}$ the $m$-th product code in the sequence corresponding to the set $\mathscr{C}^{\textcolor{black}{[m]}}$.} We aim at studying the behavior of the error probability as the dimension $m$ tends to infinity \textcolor{black}{when the \ac{SC} decoding starts from $\mathcal{C}_1$ up to $\mathcal{C}_m$}. We remark that, as $m$ changes, the component codes used to construct the product code are allowed to change, i.e., the sequence of product codes is defined by the set of component codes employed for each value of $m$. Observe that the rate of $\mathcal{C}^{\textcolor{black}{[m]}}$ may vanish as $m$ grows large, if the choice of the component codes forming the sets $\mathscr{C}^{\textcolor{black}{[m]}}$ is not performed carefully. We proceed by analyzing the limiting behavior in terms of \emph{block erasure thresholds} for different product code sequences \textcolor{black}{with positive rates} under \ac{SC} decoding. Recall that we consider $m$-dimensional systematic \ac{SPC} product code constructions, where component code generator matrices $\boldsymbol{G}_{\textcolor{black}{1}},\dots,\boldsymbol{G}_{\textcolor{black}{m}}$ are obtained by removing the first rows of the kernels $\boldsymbol{\mathsf{K}}_{n_1},\dots,\boldsymbol{\mathsf{K}}_{n_m}$ of the form \eqref{eq:kernel}. \begin{definition}\label{def:threshold} The \ac{SC} decoding block erasure threshold of a \ac{SPC} product code sequence defined by the component code \textcolor{black}{sets $\mathscr{C}^{[1]},\ldots,\mathscr{C}^{[m]}$} is the largest channel erasure probability $\epsilon^\star$ for which the block error probability $P_{\mathrm{SC}}\left(\mathcal{C}^{\textcolor{black}{[m]}}\right)$ converges to $0$ asymptotically in $m$ \textcolor{black}{if the limit exists}, i.e., \begin{equation} \epsilon^\star = \sup_{\epsilon_{\mathrm{ch}}\in[0,1)} \{\epsilon_{\mathrm{ch}}:\lim_{m\rightarrow\infty} P_{\mathrm{SC}}\left(\mathcal{C}^{\textcolor{black}{[m]}}\right) = 0\}. \end{equation} \end{definition} As it is not possible to evaluate $P_{\mathrm{SC}}\left(\mathcal{C}^{\textcolor{black}{[m]}}\right)$ exactly, we rely on the upper bound \eqref{eq:LooseUB_Product} to obtain a lower bound $\epsilon^\star_{\mathrm{LB}}$ on the block erasure threshold in the form \begin{equation} \epsilon^\star_{\mathrm{LB}} = \hspace{-1mm}\sup_{\epsilon_{\mathrm{ch}}\in[0,1)} \hspace{-1mm}\{\epsilon_{\mathrm{ch}}:\lim_{m\rightarrow\infty} k\left(\mathcal{C}^{\textcolor{black}{[m]}}\right)\epsilon_{\mathrm{max}}\left(\mathcal{C}^{\textcolor{black}{[m]}}\right)\hspace{-1mm}=\hspace{-1mm}0\} \end{equation} where the dependence of the code dimension $k$ and of the maximum information bit erasure probability $\epsilon_{\mathrm{max}}$ on the sequence of product codes has been made explicit. We provide next two examples of product code sequences, whose rates converge to a positive value. The first sequence exhibits a positive block erasure threshold (lower bound), which is however arguably far from the Shannon limit. We then analyze a product code sequence that is known to achieve the \ac{BEC} capacity under bit-wise \ac{MAP} decoding \cite{kumar16,pfister17}. \medskip \begin{example}[Euler's infinite-product representation of the sine function as an \ac{SPC} product code] \label{sec:asymptotic1} Consider an \ac{SPC} product code \textcolor{black}{sequence} with an $(a^2 \ell^2, a^2 \ell^2-1)$ \textcolor{black}{\ac{SPC} component code at the $\ell$-th dimension, yielding $R_\ell = \left(1- (a\ell)^{-2}\right)$, with $\ell=1,\ldots,m$.} \textcolor{black}{The asymptotic} rate is computed easily \textcolor{black}{via} the Euler's infinite-product representation of the sine \textcolor{black}{function}, i.e., \[\sin\left(\frac{\pi}{a}\right)=\frac{\pi}{a} \prod_{\ell=1}^{\infty}\left(1-\frac{1}{a^2\ell^2}\right)\] yielding an \textcolor{black}{asymptotic} rate $R = \frac{a}{\pi}\sin\left(\frac{\pi}{a}\right)$. \textcolor{black}{Different product code sequences can be obtained for various choices of the parameter $a$.} \textcolor{black}{The} lower bounds \textcolor{black}{on the} block erasure thresholds are provided in Table \ref{table:asymptotic} \textcolor{black}{for several values of $a$.} The second column \textcolor{black}{in Table \ref{table:asymptotic} provides the asymptotic rate of the \ac{SPC} product code sequence defined by the parameter $a$ (whose squared value is reported in the first column). The third column reports the lower bound on the block erasure threshold. The fourth column gives the \textcolor{black}{Shannon limit} for the given asymptotic rate, while the last one shows \textcolor{black}{the fraction of the Shannon limit achieved by each construction.} The thresholds achieved by the different product code sequences lie relatively far from the Shannon limit. In relative terms, the lowest-rate construction (obtained for $a^2=2$) achieves the largest fraction (above $1/2$) of the limit, while the efficiency of the sequences decreases as the rate grows.} {\renewcommand{\arraystretch}{1.2} \begin{table} \caption{Lower bounds on the \textcolor{black}{block} erasure thresholds for some \ac{SPC} product code \textcolor{black}{sequences based on Euler's infinite-product representation of the sine function}} \begin{center} \vspace*{-3mm} \begin{tabular}{c|cc|c|c} \hline\hline $a^2$ & $R$ & $\epsilon^\star_{\textcolor{black}{\mathrm{LB}}}$ & Limit, $\epsilon=1-R$ & $\epsilon^\star_{\textcolor{black}{\mathrm{LB}}} /\epsilon$\\ \hline $2$ & $0.3582$ & $0.3308$ & $0.6418$ & $0.5154$\\ $4$ & $0.6366$ & $0.1440$ & $0.3634$ & $0.3963$\\ $8$ & $0.8067$ & $0.0681$ & $0.1933$ & $0.3523$ \\ $16$ & $0.9003$ & $0.0332$ & $0.0997$ & $0.3331$ \\ $32$ & $0.9494$ & $0.0164$ & $0.0506$ & $0.3241$ \\ $64$ & $0.9745$ & $0.0081$ & $0.0255$ & $0.3176$ \\ \hline\hline \end{tabular} \end{center} \label{table:asymptotic} \end{table} } \end{example} \medskip \begin{example}[Product of $(m,m-1)$ \ac{SPC} product codes in $m$ dimensions] \label{sec:asymptotic2} We consider now the product code obtained by iterating $(m,m-1)$ \ac{SPC} codes in $m$ dimensions\textcolor{black}{, i.e., the resulting code is an $(m^m,(m-1)^m,2^m)$ code. Hence, the} rate of the $m$th product code in the sequence is \begin{equation*} R\left(\mathcal{C}^{\textcolor{black}{[m]}}\right) = \left(1-\frac{1}{m}\right)^{m} \end{equation*} and it converges, for $m\rightarrow \infty$, to $\texttt{e}^{-1}$. As presented in \cite{pfister17}, this product code sequence is remarkable: It is capacity-achieving over the \textcolor{black}{BEC} under bit-wise \ac{MAP} decoding. \textcolor{black}{This} observation follows from results derived in \cite{kumar16}. Disappointingly, the block-wise erasure threshold under \ac{SC} decoding turns out to be zero. This (negative) result is provided by the following theorem. \begin{theorem} \label{theorem:threshold} \textcolor{black}{Under \ac{SC} decoding, the block erasure threshold of the product code sequence defined by the component code sets $\mathscr{C}^{\textcolor{black}{[m]}}=\left\{\mathcal{C}_1, \mathcal{C}_2, \ldots, \mathcal{C}_m\right\}$, where $\mathcal{C}_i$, $i=1,\dots,m$, are $(m,m-1)$ \ac{SPC} codes, is zero.} \end{theorem} \begin{proof} The proof revolves around the following idea: For the product code with $(m,m-1)$ \ac{SPC} component codes in $m$ dimensions over the \ac{BEC}, the largest information bit erasure probability $\epsilon_{\mathrm{max}}$ under \ac{SC} decoding is equal to the channel erasure probability $\epsilon_{\mathrm{ch}}\in(0,1)$, i.e., $\epsilon_{\mathrm{max}} = \epsilon_{\mathrm{ch}}$ as $m\rightarrow\infty$\textcolor{black}{, which is proved below after this paragraph}. Since the largest information bit erasure probability $\textcolor{black}{\epsilon}_{\mathrm{max}}$ is a lower bound on the block error probability under \ac{SC} decoding (see \eqref{eq:UB_Product}), we have that $\epsilon^\star = 0$. \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{./figures/henry_example.pdf} \end{center} \vspace{-0.5cm} \caption{Decoding trajectory for the bit $u_1$ of the $10$-dimensional SPC product code, where the component codes are $(10,9)$ SPC codes, over the BEC$\left(0.37\right)$.}\label{fig:decoding_trajectory} \end{figure} We rewrite the recursion \eqref{eq:erasure_SPC_PC}, for $i=1$ and $j=1$, in mutual information as \begin{equation} \textcolor{black}{I^{(1)}_{\boldsymbol{G}^{[m]}}}=1-\left[1-\textcolor{black}{I^{(1)}_{\boldsymbol{G}^{[m-1]}}}\right]\left[1-\textcolor{black}{\left(I^{(1)}_{\boldsymbol{G}^{[m-1]}}\right)}^{n_m-1}\right] \label{eq:mi_SPC_PC} \end{equation} by \textcolor{black}{noting that} $\textcolor{black}{I^{(i)}_{\boldsymbol{G}^{[m]}}} = 1-\textcolor{black}{\epsilon^{(i)}_{\boldsymbol{G}^{[m]}}}$ \textcolor{black}{where $I^{(i)}_{\boldsymbol{G}^{[m]}}$ denotes the mutual information of the \ac{BEC} with an erasure probability of $\epsilon^{(i)}_{\boldsymbol{G}^{[m]}}$ with uniform inputs}. We are interested in $\mathrm{I}_\mathrm{min} \triangleq 1-\epsilon_\mathrm{max}$ for a given \ac{BEC}$(\epsilon_\mathrm{ch})$, with $\epsilon_\mathrm{ch}\in[0,1)$, which can be calculated recursively via \eqref{eq:mi_SPC_PC}. This recursion is illustrated \textcolor{black}{in Fig. \ref{fig:decoding_trajectory}} for the case \textcolor{black}{$m=10$ and $\epsilon_{\mathrm{ch}}=0.37$} as an example. Note that, for the considered construction, we have $n_\ell = m$, $\ell = 1,\dots,m$. \textcolor{black}{This means \textcolor{black}{that} the top curve in the figure shifts down for a larger $m$, resulting in a narrower tunnel between the two curves, although the number of recursions, equal to $m$, increases. Note that it is necessary to have $\mathrm{I}_\mathrm{min}\rightarrow 1$, i.e., one reaches \textcolor{black}{the} $(1,1)$ point, with $m$ recursions in the figure for $P_{\mathrm{SC}}\rightarrow 0$. In the following, we provide an answer for the question on the dominating effect (narrower tunnel or more recursions) with increasing $m$.} The first (and single) recursion is simplified, using \textcolor{black}{the \ac{RHS} of \eqref{eq:mi_SPC_PC} by setting the input} $\mathrm{I}_{\mathrm{ch}}\triangleq 1-\epsilon_{\mathrm{ch}}$, as the following input-output relationship \begin{align} \textcolor{black}{f}(\mathrm{I}_\mathrm{ch}) &\triangleq 1-\left(1-\mathrm{I}_\mathrm{ch}\right)\left(1-\mathrm{I}_\mathrm{ch}^{m-1}\right)\nonumber\\ &=\mathrm{I}_{\mathrm{ch}}+\mathrm{I}_{\mathrm{ch}}^{m-1}-\mathrm{I}_{\mathrm{ch}}^m. \label{eq:mi_evol} \end{align} Hence, we know that the mutual information after $m$ iterations is $\mathrm{I}_\mathrm{min} = \textcolor{black}{f}^{\circ m}\left(\mathrm{I}_\mathrm{ch}\right)$ where $\textcolor{black}{f}^{\circ m}\left(\mathrm{I}_\mathrm{ch}\right) = \textcolor{black}{f}\left(\textcolor{black}{f}^{\circ m-1}\left(\mathrm{I}_\mathrm{ch}\right)\right)$ denotes the $m$-th iteration of function $\textcolor{black}{f}$ with $\textcolor{black}{f}^{\circ 1}\left(\mathrm{I}_\mathrm{ch}\right)\triangleq \textcolor{black}{f}\left(\mathrm{I}_\mathrm{ch}\right)$. We are interested in the lowest channel mutual information for which the block error rate converges to zero asymptotically in $m$, i.e., \[\mathrm{I}^\star = \inf_{\mathrm{I}_\mathrm{ch}\in(0,1]}\{\mathrm{I}_\mathrm{ch}:\lim_{m\rightarrow\infty} P_{\mathrm{SC}} \rightarrow 0 \}.\] Consider now \textcolor{black}{an arbitrary $\delta>0$. For any} positive $\gamma<1$, there exists a sufficiently large $m$ such that $m\gamma^{m-2}\leq\delta$. Then, for any \textcolor{black}{non-negative $\mathrm{I}\leq\gamma$, we write \begin{align} \textcolor{black}{f}(\mathrm{I}) &= \mathrm{I}+\mathrm{I}^{m-1}-\mathrm{I}^{m} \label{eq:upper_bound_mi1}\\ &\leq \mathrm{I}\left(1+\mathrm{I}^{m-2}\right)\label{eq:upper_bound_mi2} \\ &\leq \mathrm{I}\left(1+\frac{\delta}{m}\right) \label{eq:upper_bound_mi} \end{align} where \eqref{eq:upper_bound_mi2} follows from the fact that $\mathrm{I}\geq0$ and \eqref{eq:upper_bound_mi} from the fact that $\mathrm{I}\leq\gamma$, which, combined with $m\gamma^{m-2}\leq\delta$, leads to $\mathrm{I}^{m-2}\leq\frac{\delta}{m}$.} For any \textcolor{black}{initial} $\mathrm{I}_{\mathrm{ch}}\leq\texttt{e}^{-\delta}\gamma$ and any $m'\leq m$, we have \begin{equation} \textcolor{black}{f}^{\circ m'}(\mathrm{I}_\mathrm{ch}) \leq \texttt{e}^{-\delta}\gamma \left(1+\frac{\delta}{m}\right)^{m'} \leq\gamma \end{equation} which makes sure that the condition \textcolor{black}{$\mathrm{I}\leq\gamma$} for \eqref{eq:upper_bound_mi} is not violated with $m'$ iterations. Therefore, for any positive $\gamma < 1$, any $\delta>0$ and any $\mathrm{I}_{\mathrm{ch}}\leq\texttt{e}^{-\delta}\gamma$, we write \begin{equation} \lim_{m\rightarrow\infty} \textcolor{black}{f}^{\circ m}(\mathrm{I}_\mathrm{ch}) \leq \mathrm{I}_\mathrm{ch}\texttt{e}^{\delta}. \end{equation} The result follows by choosing $\delta$ arbitrarily small \textcolor{black}{and $\gamma$ arbitrarily close to $1$}. \end{proof} \end{example} \subsection{Analysis over Binary Memoryless Symmetric Channels} \label{sec:DE} \textcolor{black}{It is well-known that the block error probability of polar codes under \ac{SC} decoding can be analyzed using density evolution, when the transmission takes place over a \ac{BMS} channel\cite{Mori:2009SIT}. In the following, the same method is used to provide a tight upper bound on the block error probability of \ac{SPC} product codes over \ac{BMS} channels.} \textcolor{black}{Due to the channel symmetry and the linearity of the codes, we assume that the all-zero codeword is transmitted. We write $L^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\boldsymbol{0})$ to denote the the log-likelihood ratio for $u_i$ based on \eqref{eq:recurs_metric} where all the previous bit-values are provided as zeros to the decoder, i.e., \begin{equation*} L^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\boldsymbol{0}) \triangleq \log\frac{\mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},U_1^{i-1} = \boldsymbol{0}|U_i=0)}{\mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},U_1^{i-1} =\boldsymbol{0}|U_i=1)}. \end{equation*} Accordingly, we use $l^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}$ to denote the \ac{p.d.f.} of the \ac{RV} $L^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(Y_1^n,\boldsymbol{0})$. Extending the equations \eqref{eq:erasure_SPC} and \eqref{eq:erasure_SPC_PC} to general \ac{BMS} channels, the densities can be computed recursively as \begin{equation} l^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}} = l^{(j +1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}} \varoast (l^{(j +1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}})^{\boxast (n_m-t)} \label{eq:de_awgn} \end{equation} \own{with $j = \lfloor\nicefrac{(i-1)}{k_m}\rfloor$ and $ t \triangleq [(i-1)\!\!\mod k_m] +1$} where $\varoast$ denotes the variable node convolution and $(l^{(j +1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}})^{\boxast (a)}$ the $a$-fold check node convolution with $(l^{(j +1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}})^{\boxast (1)} \triangleq l^{(j +1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}$ as defined in \cite[Ch. 4]{Richardson:2008:MCT:1795974}. Then, the \ac{RHS} of \eqref{eq:SC_bound} can be computed via $l^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}$ with $i = 1,\dots,k$, i.e., as \begin{equation} \sum_{i=1}^{k}\lim\limits_{z\rightarrow 0} \left(\int_{-\infty}^{-z}l^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(x)dx+\frac{1}{2}\int_{-z}^{+z}l^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(x)dx\right).\label{eq:UB_AWGN} \end{equation} The computation of \eqref{eq:de_awgn} and \eqref{eq:UB_AWGN} can be carried out, for instance, via quantized density evolution \cite{chung_urbanke2001}, yielding an accurate estimate of the \ac{RHS} of \eqref{eq:SC_bound}.} \textcolor{black}{In Fig. \ref{fig:sc_125_64_SPC}, we provide simulation results for the $(125,64)$ \ac{SPC} product code over the \ac{B-AWGN} channel. The results are provided in terms of \ac{BLER} vs. \ac{SNR}, where the \ac{SNR} is expressed as $E_b/N_0$ ($E_b$ is here the energy per information bit and $N_0$ the single-sided noise power spectral density). The \ac{SC} decoding performance is compared to the performance under Elias' and \ac{BP} decoding. While it was only proven for the case of \ac{BEC} in Theorem \ref{theorem:comparison}, the results illustrate that the \ac{SC} decoding outperforms Elias' decoding also over the \ac{B-AWGN} channel for the simulated code. \ac{BP} decoding with a maximum number of iterations set to $100$ outperforms the \ac{SC} decoding significantly, which motivates us to introduce \ac{SCL} decoding in the next section. The tight upper bound on the \ac{SC} decoding, computed via \eqref{eq:UB_AWGN}, is also provided. \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{./figures/125_64_SPC_document_1.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{BLER} vs. \ac{SNR} over the B-AWGN channel for a $(125,64)$ product code under \ac{SC} decoding, compared to Elias' decoding as well as a \ac{BP} decoding with $100$ iterations.}}\label{fig:sc_125_64_SPC} \end{figure}} \subsection{Analysis over \textcolor{black}{the B-}AWGN Channel} \label{sec:DE} \textcolor{black}{Consider now transmission over \ac{B-AWGN} channel. Note that the \ac{B-AWGN} channel is symmetric, i.e.,$\mathrm{W}(y|0) = \mathrm{W}(-y|1)$\footnote{\textcolor{black}{A reader might assume \ac{BPSK} is adopted, where $0$ is mapped to $+1$ and $1$ to $-1$.}}, $\forall y\in\mathcal{Y}$. For symmetric channels, the error probability is independent of the codeword transmitted if linear codes are used\cite{Richardson:2008:MCT:1795974}. Then, w}e assume that all-zero codeword is transmitted for simplicity of the analysis. We write $L^{(i)}_{\boldsymbol{G}^{(m)}}(\boldsymbol{y},\boldsymbol{0})$ to denote the the log-likelihood ratio of $u_i$ based on \eqref{eq:recurs_metric} where all the previous decisions are provided as zeros to the decoder, i.e., \begin{equation*} L^{(i)}_{\boldsymbol{G}^{(m)}}(\boldsymbol{y},\boldsymbol{0}) \triangleq \log\frac{\mathrm{W}^{(i)}_{\boldsymbol{G}^{(m)}}(\boldsymbol{y},\boldsymbol{0}|0)}{\mathrm{W}^{(i)}_{\boldsymbol{G}^{(m)}}(\boldsymbol{y},\boldsymbol{0}|1)}. \end{equation*} Accordingly, we use $\ell^{(i)}_{\boldsymbol{G}^{(m)}}$ to denote the \ac{pdf} of \ac{RV} $L^{(i)}_{\boldsymbol{G}^{(m)}}(Y_1^n,\boldsymbol{0})$. The equation to compute the denisities are \begin{equation} \ell^{(i)}_{\boldsymbol{G}^{(m)}} = \ell^{(j)}_{\boldsymbol{G}^{(m-1)}} \odot \left(\overset{t}{\textcolor{black}{\otimes}}\,\, \ell^{(j)}_{\boldsymbol{G}^{(m-1)}}\right) \end{equation} where $j = \lfloor\frac{i-1}{k_m}\rfloor +1$, $t\triangleq i\mod k_m$, $\odot$ denotes the variable node convolution and $\overset{t}{\textcolor{black}{\otimes}}$ denotes the $t$-fold check node convolution with $\overset{1}{\textcolor{black}{\otimes}}\,\, \ell^{(j)}_{\boldsymbol{G}^{(m-1)}} \triangleq \ell^{(j)}_{\boldsymbol{G}^{(m-1)}}$. Then, the \ac{RHS} of \eqref{eq:SC_bound} can be computed via $\ell^{(i)}_{\boldsymbol{G}^{(m)}}$ with $i = 1,\dots,k$, i.e., as \[\sum_{i=1}^{k}\lim\limits_{z\rightarrow 0} \left(\int_{-\infty}^{-z}\ell^{(i)}_{\boldsymbol{G}^{(m)}}(x)dx+\frac{1}{2}\int_{-z}^{+z}\ell^{(i)}_{\boldsymbol{G}^{(m)}}(x)dx\right).\] An efficient method to compute such an expression is quantized density evolution \cite{chung_urbanke2001} \subsection{Proof of Lemma 2}\label{sec:appendix} \textcolor{black}{Let $U_1^{n_\ell}$ be a-priori uniform on $\mathcal{X}^{n_\ell}$ that is mapped onto $X_1^{n_\ell}$ as $X_1^{n_\ell} = U_1^{n_\ell}\boldsymbol{\mathsf{K}}_{n_\ell}$. It is sufficient to show that\cite[Theorem 1]{benammar_land} there exists $\alpha,\beta>0$ for all $i\in[n_\ell]$ such that \begin{equation} \left|I\left(\mathrm{W}^{(i)}_{\boldsymbol{\mathsf{K}}_{n_\ell}}\right)-I\left(\mathrm{W}\right)\right|\geq I\left(\mathrm{W}\right)^\alpha\left(1-I\left(\mathrm{W}\right)\right)^\beta \end{equation} which can be equivalently translated into \begin{align} \!\!\!\!\!\!\!\!\left|H\left(U_i\big|Y_1^{n_\ell},U_1^{i-1}\right)-H(\mathrm{W})\right|\geq\left(1-H(\mathrm{W})\right)^\alpha H^\beta(\mathrm{W}). \label{eq:second_condition} \end{align} } \textcolor{black}{Note that $H\left(U_i\big|Y_1^{n_\ell}, U_1^{i-1}\right)$ is decreasing in $i$ for $i\geq 2$ due to the kernel structure. This means, for $i\in\{2,\ldots,n_\ell\}$, we have \begin{equation} H\left(U_i\big|Y_1^{n_\ell},U_1^{i-1}\right) \leq H\left(U_2\big|Y_1^{n_\ell},U_1\right).\label{eq:monotone} \end{equation} In the following, we focus on the \ac{RHS} of \eqref{eq:monotone}. By noting $U_1 = X_1\oplus\ldots\oplus X_{n_\ell}$ and $U_2 = X_2$ and setting $S = U_1\oplus X_2 = X_1\oplus X_3\ldots\oplus X_{n_\ell}$, we re-write the \ac{RHS} of \eqref{eq:monotone} as \begin{align} H&\left(X_2\big|Y_1^{n_\ell},S\oplus X_{2}\right) = H(X_2|Y_1^{n_\ell})\!+\!H(S\oplus X_{2}|Y_1^{n_\ell},X_2)\\ &\qquad\qquad\quad\qquad\qquad\qquad\qquad-H(S\oplus X_{2}|Y_1^{n_\ell})\label{eq:separation23}\\ &\qquad\,= H(X_2|Y_2) + H(S|Y_{\sim 2}) - H(S\oplus X_2|Y_1^{n_\ell}) \label{eq:separation24} \end{align} where \eqref{eq:separation23} follows from the chain rule of entropy and \eqref{eq:separation24} from the fact that $X_2-Y_2-Y_{\sim 2}$ and $T-Y_{\sim 2}-Y_2$ form Markov chains with $Y_{\sim i}$ being the random vector where the $i$-th element is removed. An upper-bound on the last term in the \ac{RHS} of \eqref{eq:separation24} can be found as \begin{align} &\!\!\!\!\!\!\!\!\!\!H(S\!\oplus \!X_2|Y_1^{n_\ell}) \!\geq\! H_2\!\left(\!H_2^{-1}\!\left(H(S|Y_{\sim 2})\right) \!*\! H_2^{-1}\!\left(\!H(X_2|Y_2)\right)\right)\label{eq:separation31}\\ &\qquad\qquad\geq H(S|Y_{\sim 2}) + [1-H(S|Y_{\sim 2})]H^2\!\left(X_2|Y_2\right)\label{eq:separation32} \end{align} where \own{$H_2: [0,\nicefrac{1}{2}] \rightarrow [0,1]$ is the binary entropy function. Then,} \eqref{eq:separation31} and \eqref{eq:separation32} are due to Mrs. Gerber's Lemma \cite{WZ73} and $H_2(a*b) \geq H_2(a) + [1-H_2(a)]H_2^2(b)$,\footnote{\textcolor{black}{Note that this inequality is very similar to the one given in \cite[Eq. (38)]{benammar_land} without proof. Its validity can be easily verified numerically.}} respectively. \own{W}e subtract $H(\mathrm{W})$ from the both sides of \eqref{eq:separation24} to have \begin{align} \!\!H&\!\left(\!X_2\big|Y_1^{n_\ell},S\oplus X_{2}\right) \!-\! H(\mathrm{W})\!\leq\! H(S|Y_{\sim 2}) \!-\! H(S\!\oplus\! X_2|Y_1^{n_\ell})\label{eq:separation41}\\ &\qquad\,\,\leq -[1-H(S|Y_{\sim 2})]H^2(\mathrm{W})\label{eq:separation42}\\ &\qquad\,\,= -[1-H(X_1\oplus X_3\oplus\ldots\oplus X_{n_\ell}|Y_{\sim 2})]H^2(\mathrm{W})\label{eq:separation43} \end{align} where \eqref{eq:separation42} follows from \eqref{eq:separation32} For an upper-bound on \eqref{eq:separation43}, we write \begin{align} &H(\own{S}|Y_{\sim 2}) = \sum_{\boldsymbol{y}_{\sim 2}}p(\boldsymbol{y}_{\sim 2})H(\own{S}|Y_{\sim 2} = \boldsymbol{y}_{\sim 2})\label{eq:separation51} \\ &\!= \!\sum_{\own{\boldsymbol{y}_{\sim 2}}} p(y_1)p(y_3^{n_\ell})H_2\left(p_{X_1\oplus X_3\oplus\ldots\oplus X_{n_\ell}|Y_{\sim 2} = \boldsymbol{y}_{\sim 2}}\right)\label{eq:separation52} \\ &\!= \!\sum_{\own{\boldsymbol{y}_{\sim 2}}} p(y_1)p(y_3^{n_\ell})H_2\!\left(p_{X_1|Y_1=y_1}\!*\!p_{X_3\oplus\ldots\oplus X_{n_\ell}|Y_3^{n_\ell} = y_3^{n_\ell}}\!\right)\label{eq:separation53} \\ &\leq H(X_1|Y_1) \!+\! [1\!-\!H(X_1|Y_1)]H(X_3\!\oplus\!\ldots\!\oplus\! X_{n_\ell}|Y_3^{n_\ell})\label{eq:separation54} \\ &= H(\mathrm{W}) + [1-H(\mathrm{W})]H(X_3\oplus\ldots\oplus X_{n_\ell}|Y_3^{n_\ell})\label{eq:separation55} \end{align} where \eqref{eq:separation52} \own{follows by recalling $ S = X_1\oplus X_3\oplus\ldots\oplus X_{n_\ell}$ and defining $p_{S|Y_{\sim 2} = \boldsymbol{y}_{\sim 2}}\triangleq H_2^{-1}(H(S|Y_{\sim 2} = \boldsymbol{y}_{\sim 2}))$,} \eqref{eq:separation53} follows \own{from} the independence of $\{Y_i\}$, $i\in[n_\ell]$, and \eqref{eq:separation54} from the inequality $H_2(a*b)\leq H_2(a)+[1-H_2(a)]H_2(b)$.\footnote{\textcolor{black}{This inequality can also be found in\cite[Eq. (45)]{benammar_land} and verified numerically.}} By recalling $X_2 = U_2$ and $U_1 = S\oplus X_2$, combining \eqref{eq:separation55} and \eqref{eq:separation43} results in \begin{align} &H\left(U_2\big|Y_1^{n_\ell},U_1\right) - H(\mathrm{W}) \leq\\ &\!-\!\!\left[\!1\!-\!\left(\!H(\mathrm{W}) \!+\! [1\!-\!H(\mathrm{W})]H(X_3\!\oplus\!\ldots\!\oplus\! X_{n_\ell}|Y_3^{n_\ell})\right)\!\right]\!H^2(\mathrm{W}) \\ &\!= -\!\left(1-H(X_3\oplus\ldots\oplus X_{n_\ell}|Y_3^{n_\ell})\right)[1-H(\mathrm{W})]H^2(\mathrm{W})\label{eq:separation56} \end{align} where \eqref{eq:separation56} follows from algebraic manipulation. Now recall \eqref{eq:monotone}. By recursively applying the steps to reach \eqref{eq:separation56}, one obtains \begin{equation} H\left(U_i\big|Y_1^{n_\ell},U_1^{i-1}\right)-H(\mathrm{W}) \leq -[1-H(\mathrm{W})]^{n_\ell - 1} H^2(\mathrm{W})\label{eq:separation61} \end{equation} for $i = 2,\ldots,n_\ell$.} \textcolor{black}{Using the chain rule for conditional entropy, we write \begin{align} \sum_{i=1}^{n_\ell} \left[H(U_i|Y_1^{n_\ell},U_1^{i-1})\!-\!H(\mathrm{W})\right] &= H(U_1^{n_\ell}|Y_1^{n_\ell}) \!-\! n_\ell H(\mathrm{W})\\ &= 0. \label{eq:separation71} \end{align} Combining \eqref{eq:separation61} and \eqref{eq:separation71} provides \begin{align} H\left(U_1\big|Y_1^{n_\ell}\right)-H(\mathrm{W}) &\geq (n_\ell-1)[1-H(\mathrm{W})]^{n_\ell - 1} H^2(\mathrm{W}) \\ &\geq [1-H(\mathrm{W})]^{n_\ell - 1} H^2(\mathrm{W}) \label{eq:separation81} \end{align} where \eqref{eq:separation81} follows from the fact that $n_\ell\geq 2$. We obtain \eqref{eq:second_condition} by setting $\alpha = n_\ell - 1$ and $\beta = 2$, which concludes the proof.} \section{Introduction}\label{sec:intro} \IEEEPARstart{P}{roduct} codes were introduced in 1954 by Elias\cite{Elias:errorfreecoding54} \textcolor{black}{with} extended Hamming \textcolor{black}{component} codes over an infinite number of dimensions. \textcolor{black}{Elias} showed that \textcolor{black}{this code has positive rate and its} bit error probability can be made arbitrarily small over the \ac{BSC}. \textcolor{black}{His decoder treats} the product code as a serially concatenated code and applies independent decoding to the component codes \textcolor{black}{sequentially} across its dimensions. \textcolor{black}{Much later, t}he suitability of product code constructions for iterative decoding algorithms\cite{Berrou93} led to a very powerful class of codes\cite{Pyndiah98,Tanner,Li04,Feltstrom09,Pfister15}. \textcolor{black}{For} an overview of product codes and their variants\textcolor{black}{, we refer the reader to} \cite{Berrou05,hager17}. Usually, product codes are constructed with high-rate algebraic component codes, for which low-complexity \ac{SISO}\cite{Pyndiah98} or algebraic (e.g., bounded distance) \cite{Abramson,KoetterPC,Haeger2018} decoders are available. Specifically, product codes with \ac{SPC} component codes are considered in \cite{caire,rankin1,rankin2}, where the interest was mainly their performance and \textcolor{black}{their} weight enumerators. In \cite{6125399}, \textcolor{black}{a} bridge between generalized concatenated codes and polar codes\cite{arikan2009channel,stolte2002rekursive} was established. In \cite{Coskun19:RM-Product}, the standard polar \ac{SCL} decoder is proposed for a class of product codes with Reed-Muller component codes, e.g., SPC \textcolor{black}{codes whose length is a power of $2$} and/or extended Hamming component codes, \textcolor{black}{with non-systematic encoders}. Sizeable gains were observed with moderate list sizes over \ac{BP} decoding for short \textcolor{black}{blocklengths} when the product codes were modified by \textcolor{black}{introducing} a high-rate outer code. In this paper, we show that \ac{SPC} product codes can be \textcolor{black}{described using the tools} of polar codes based on generalized kernels \textcolor{black}{\cite{PSL16,gabry_land,BGL20,benammar_land}}, where the frozen bit indices are chosen according to the constraints imposed by the product code construction. \textcolor{black}{Following this observation}, \ac{SC} decoding of \ac{SPC} product codes is introduced. A bridge between the original decoding algorithm of product codes, which is referred to as Elias' decoder\cite{Elias:errorfreecoding54},\footnote{By Elias' decoder, we refer to \textcolor{black}{the} decoding algorithm that treats the product code as a serially concatenated block code, where the decoding is performed starting from the component codes of the first dimension, up to those of the last dimension, in a one-sweep fashion.} and the \ac{SC} decoding algorithm is established for \ac{SPC} product codes over \textcolor{black}{the} \ac{BEC}. \textcolor{black}{Further,} the block error probability of \ac{SPC} product codes is upper bounded \textcolor{black}{via} the union bound under both decoding algorithms. A comparison between Elias' decoding and \ac{SC} decoding of \ac{SPC} product codes is \textcolor{black}{also} provided in terms of block error probability, proving that \ac{SC} decoding yields a \textcolor{black}{probability of error that does not exceed the one of} Elias' decoding. \textcolor{black}{The analysis of \ac{SC} decoding is extended to general \ac{BMS} channels.} Finally, \ac{SCL} decoding \cite{tal15} of \textcolor{black}{product} codes is introduced to overcome the significant performance gap of \ac{SC} decoding to \textcolor{black}{the block error probability under \ac{ML} decoding (estimated through Poltyrev's \ac{TSB}\cite{poltyrev94})}. The performance improvement is significant, i.e., \ac{SCL} decoding \textcolor{black}{yields a block error probability that is} below \textcolor{black}{the} \ac{TSB}\textcolor{black}{,} even for small list sizes\textcolor{black}{,} for the analyzed code, \textcolor{black}{delivering} a lower error probability compared to \ac{BP} decoding (especially at low error rates). In addition to the potential coding gain over \ac{BP} decoding, \ac{SCL} decoding enables a low-complexity decoding of the concatenation of the product code with a high-rate outer code as for polar codes \cite{tal15}. It is shown \textcolor{black}{via simulations} that the concatenation provides remarkable gains over the product code alone. \textcolor{black}{The gains would} not be possible under a \ac{BP} decoder which jointly decodes the outer code and the inner product code \cite{Coskun19:RM-Product}. \textcolor{black}{We show examples where t}he resulting construction operates within \textcolor{black}{$0.7$} dB of the \ac{RCU} bound\cite{Polyanskiy10:BOUNDS} with a moderate list size. \textcolor{black}{From an application viewpoint, the performance gain with respect to BP decoding may be especially relevant for systems employing \ac{SPC} product codes with an outer error detection code (see, e.g., the IEEE~802.16 standard \cite{IEEE80216}). Moreover, we show that short \ac{SPC} product codes, concatenated with an outer \ac{CRC} code can outperform (under \ac{SCL} decoding) 5G-NR \ac{LDPC} code with similar blocklength and dimension.} \textcolor{black}{By noticing that, for medium to short blocklengths, the \ac{SCL} decoder can approach the \ac{ML} decoder performance with a moderate list size, t}he analysis of the concatenated construction is addressed from a distance spectrum viewpoint. In \cite{caire}, a closed form expression is provided to compute the weight enumerator of $2$-dimensional \ac{SPC} product codes, relying on the MacWilliams identity for joint weight enumerators\cite{MacWilliams72}. In \cite{rankin1}, the closed form solution is extended to compute the input-output weight enumerator of $2$-dimensional \ac{SPC} product codes by converting the dual code into a systematic form. This method does not seem applicable for higher-dimensional constructions, as it is not trivial how to get to a systematic form of the dual code in such cases. In this work, the method in \cite{caire} is presented \textcolor{black}{using} a different approach, that avoids \textcolor{black}{the use of} joint weight enumerators. This approach is \textcolor{black}{then} extended to accommodate the input-output weight enumerator of $2$-dimensional product codes, where one component code is an \ac{SPC} code. The method is used to compute the input-output weight enumerator of the exemplary short $3$-dimensional \ac{SPC} product code \textcolor{black}{as it can be seen as a $2$-dimensional product code, where one component code is an \ac{SPC} code}. By combining this result with the uniform interleaver approach, the average input-output weight enumerator of the concatenated code ensemble is computed, which is, then, used to compute some tight bounds on the block error probability \cite{di02,poltyrev94}, e.g., \textcolor{black}{via} Poltyrev's \ac{TSB}. The work is organized as follows. In Section \ref{sec:prelim}, we provide the preliminaries needed for the rest of the work. In Section \ref{sec:spcpc_as_pc}, we establish a bridge between \ac{SPC} product codes and the multi-kernel polar construction \cite{gabry_land,benammar_land}. The \ac{SC} decoding algorithm for \ac{SPC} product codes is described and analyzed over \textcolor{black}{\ac{BMS} channels, with a particular focus on the \ac{BEC} and the \ac{B-AWGN} channel, in Section \ref{sec:sc}.} In Section \ref{sec:scl}, the \ac{SCL} decoding algorithm is described and the codes are analyzed from a \ac{ML} decoding point of view through their distance spectrum. Conclusions follow in Section \ref{sec:conc}. \section*{Acknowledgement} The authors would like to thank the associate editor and the anonymous reviewers for their valuable comments, which improved the presentation of the work significantly. \input{appendix.tex} \section{Numerical Results} \iffalse \begin{figure}[t] \begin{center} \includegraphics[width=0.75\columnwidth]{./figures/125_64_SPC_document_polar_BEC.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{CER} vs. \ac{SNR} under \ac{SCL} decoding for a $(125,64)$ product code with various list sizes, compared to a $(125,64)$ polar code with various list sizes.} }\label{fig:scl_125_64_SPC_vs_polar} \end{figure} \textcolor{black}{Next, we provide simulation results for the $3$-dimensional $(125,64)$ \ac{SPC} product code under \ac{SCL} decoding with various list sizes in Fig. \ref{fig:scl_125_64_SPC_vs_polar}. As reference, simulation results for a $(125,64)$ punctured polar code~\cite{WR14:polar_punc} is also provided. Note that the design follows the guidelines of 5G standard~\cite{BCL21:5g_polar}. In addition, the \ac{TSB} (a tight upper bound on the error probability for a given code under \ac{ML} decoding~\cite{poltyrev94}) is also provided.} Remarkably, \textcolor{black}{\ac{SCL}} decoding with $L=4$ is sufficient to operate on top of the \ac{TSB} and outperform \ac{BP} decoding. With $L=8$, the \ac{SCL} decoder tightly matches the \ac{ML} lower bound, which is not the case for \ac{BP} decoding. The gap to the \ac{RCU} bound reaches to \textcolor{black}{$1.7$} dB at \ac{CER} of $10^{-3}$. \textcolor{black}{When $L=4$ is considered, the gap to the performance of polar code is around $0.3$ dB at \ac{CER} of $10^{-3}$ and note also that the polar code performs significantly better under \ac{SC} decoding since its set $\mathcal{A}$ is chosen to minimize the \ac{CER} under \ac{SC} decoding.} \begin{figure}[t] \begin{center} \includegraphics[width=0.75\columnwidth]{./figures/125_64_SPC_document_polar.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{CER} vs. \ac{SNR} under \ac{SCL} decoding for a $(125,64)$ product code with various list sizes, compared to a $(125,64)$ polar code with various list sizes.} }\label{fig:scl_125_64_SPC_vs_polar} \end{figure} \iffalse \textcolor{black}{Fig. \ref{fig:scl_125_58_SPC} shows the performance of concatenating the $(125,64)$ product code with \textcolor{black}{a $6$-bit} outer \ac{CRC} code with generator polynomial $g(x)=x^6+x+1$, where the interleaver between the codes is the trivial one defined by an identity matrix. This concatenation leads to a $(125,58)$ code. Since the code distance properties are improved (observed directly via the \ac{TSB} on the average performance of the code ensemble), the performance improvement under \ac{ML} decoding is expected to be significant. The gain achieved by \ac{SCL} decoding is remarkably large, operating below the \ac{TSB}. At a \ac{CER} range of $10^{-2}$-$10^{-4}$, \ac{SCL} decoding of the concatenated code achieves gains up to $1.25$ dB over the original product code. The gap to the \ac{RCU} bound is approximately $0.7$ dB at the \ac{CER} of $10^{-3}$ and reaching up to $1$ dB at the \ac{CER} of $10^{-4}$. Note that it is not always possible to attain the performance close to the \ac{ML} performance of concatenated codes using \ac{BP} decoding\cite{Coskun19:RM-Product,geiselhart2020crcaided}. In that sense, \ac{SCL} decoding provides a low-complexity solution to reach the \ac{ML} performance of the concatenated scheme.} \begin{figure}[t] \begin{center} \includegraphics[width=0.75\columnwidth]{./figures/125_64_bestCRC6_SPC_document.pdf} \end{center} \vspace{-0.5cm} \caption{\ac{CER} vs. \ac{SNR} under \ac{SCL} decoding for a $(125,64)$ product code concatenated with a $(64,58)$ \ac{CRC} code, with various list sizes. It is compared to a $(125,56)$ CRC-concatenated polar code with various list sizes, where the generator polynomial of the outer code is optimized for \ac{SCL} decoding\cite{Yuan19}. }\label{fig:scl_125_58_SPC} \end{figure} \fi Fig. \ref{fig:scl_125_56_SPC} shows the performance of concatenating the $(125,64)$ product code with \textcolor{black}{a $8$-bit} outer \ac{CRC} code with generator polynomial \textcolor{black}{$g(x)=x^8+x^6+x^5+x^4+x^2+x+1$}, where the interleaver between the codes is the trivial one defined by an identity matrix. This concatenation leads to a $(125,56)$ code. Since the code distance properties are improved (observed directly via the \ac{TSB} on the average performance of the code ensemble), the performance improvement under \ac{ML} decoding is expected to be significant. The gain achieved by \ac{SCL} decoding is remarkably large, operating below the \ac{TSB} \textcolor{black}{obtained for the average weight enumerator of a concatenated ensemble with the uniform distribution assumption over all possible interleavers.}. At a \ac{CER} of $10^{-2}$, \ac{SCL} decoding of the concatenated code achieves gains up to $1.25$ dB over the original product code, reaching up to \textcolor{black}{$1.5$} dB at a \ac{CER} $\approx 10^{-4}$. The gap to the \ac{RCU} bound is approximately \textcolor{black}{$0.7$} dB at the \ac{CER} of \textcolor{black}{$10^{-4}$ and less for lower \acp{CER}, providing a competitive performance for similar parameters\cite{Coskun18:Survey}}. Note that it is not always possible to attain the performance close to the \ac{ML} performance of concatenated codes using \ac{BP} decoding\cite{Coskun19:RM-Product,geiselhart2020crcaided}. In that sense, \ac{SCL} decoding provides a low-complexity solution to reach the \ac{ML} performance of the concatenated scheme. \textcolor{black}{As a reference, a (125, 56) CRC-concatenated polar code is constructed by using the $(125,64)$ polar code of Fig. \ref{fig:scl_125_56_SPC} with an $8$-bit outer \ac{CRC} code optimized using the guidelines of \cite{Yuan19}. The generator polynomial for the CRC code is $f(x)=x^8+x^7+x^6+x^5+1$. Note that the gap to the \ac{ML} performance of two codes is less than $0.5$ dB in the considered regime.\footnote{\textcolor{black}{A careful optimization of the interleaver for the CRC-concatenated \ac{SPC} product code might provide further gains, but it is not in the scope of this work.}}} \begin{figure}[t] \begin{center} \includegraphics[width=0.75\columnwidth]{./figures/125_64_bestCRC8_SPC_document.pdf} \end{center} \vspace{-0.5cm} \caption{\ac{CER} vs. \ac{SNR} under \ac{SCL} decoding for a $(125,64)$ product code concatened with a $(64,56)$ \ac{CRC} code, with various list sizes. \textcolor{black}{It is compared to a $(125,56)$ CRC-concatenated polar code with various list sizes, where the generator polynomial of the outer code is optimized for \ac{SCL} decoding\cite{Yuan19}.} }\label{fig:scl_125_56_SPC} \end{figure} \fi \section{Preliminaries}\label{sec:prelim} \subsection{Notation} In the following, lower-case bold letters are used for vectors, e.g., $\boldsymbol{x} = (x_1,x_2,\dots,x_n)$. The Hamming weight of $\boldsymbol{x}$ is $w_{\mathrm{H}}(\boldsymbol{x})$. \textcolor{black}{When required, we} use $ x_a^b $ to denote the vector $ (x_a, x_{a+1}, \dots, x_b) $ where $ b > a $. Furthermore, we write $x_{a,m}^{b}$ to denote the subvector with indices $\{i\in[b]:a = i\mod m\}$, where $[b]$ denotes the set $\{1,2,\dots,b\}$. For instance, $x_{1,3}^9 = (x_1, x_4, x_7)$. In addition, $\boldsymbol{x}_{\sim i}$ refers to the vector where the \textcolor{black}{element with index $i$} is removed, i.e., $ \boldsymbol{x}_{\sim i} = (x_1,x_2,\dots,x_{i-1},x_{i+1},\dots,x_{n})$. Component-wise \textcolor{black}{addition} of two binary vectors \textcolor{black}{in $\mathbbm{F}_2$} is denoted as $\boldsymbol{x}\oplus \boldsymbol{y}$. The $m$-digit multibase representation of a decimal number $a$ is denoted by $(a_1a_2\dots a_m)_{b_1b_2\dots b_m}$ and the conversion is done according to \begin{equation}\label{eq:multibase} a = \sum_{i=1}^{m} a_i\prod_{j=i+1}^{m}b_j \end{equation} where $b_j$ is the base of the $j$-th digit $a_j$ with left-most digit being the most significant one with $0\leq a_j<b_j$. \textcolor{black}{For example, the binary representation of a number is obtained by setting $b_j=2$, $j=1,\ldots,m$.} Capital bold letters, e.g., $\boldsymbol{X}_{a\times b} = [x_{i,j}]$, are used for $a\times b$ matrices. \textcolor{black}{The subscript} showing the dimensions is omitted whenever the dimensions are clear from the context. Similarly, $\boldsymbol{I}_a$ refers to the $a\times a$ identity matrix. The Kronecker product of two matrices $\boldsymbol{X}$ and $\boldsymbol{Y}$ is \begin{equation*} \boldsymbol{X}\otimes \boldsymbol{Y} \triangleq \begin{bmatrix} x_{1,1}\boldsymbol{Y} & x_{1,2}\boldsymbol{Y} & \dots \\ x_{2,1}\boldsymbol{Y} & x_{2,2}\boldsymbol{Y} & \dots \\ \vdots & \vdots &\ddots \end{bmatrix}. \label{eq:Kronecker} \end{equation*} We define an $ab\times ab$ \emph{perfect shuffle} matrix \textcolor{black}{\cite{R80}}, denoted as $\boldsymbol{\Pi}_{a,b}$, by the following operation \begin{equation} (x_1,x_2,\dots,x_{ab})\boldsymbol{\Pi}_{a,b} = (x_{1,b}^{ab},x_{2,b}^{ab},\dots,x_{b-1,b}^{ab},x_{b,b}^{ab}). \label{def:permutation} \end{equation} We use capital letters, e.g., $X$, for \acp{RV} and lower-case counterparts, e.g., $x$, for their realizations. \textcolor{black}{For random vectors, similar notation above is used, e.g., we use $X_a^b$ to denote the random vector $(X_a, X_{a+1},\ldots X_{b})$.} We denote a \ac{BMS} channel with input alphabet $ \mathcal{X} = \{0,1\} $, output alphabet $ \mathcal{Y} $, and transition probabilities \textcolor{black}{(densities)} $ \mathrm{W}(y|x) $, $ x \in \mathcal{X} $, $ y \in \mathcal{Y} $ by $ \mathrm{W} : \mathcal{X} \rightarrow \mathcal{Y} $. \textcolor{black}{For a given channel $\mathrm{W}$, let $I\left(\mathrm{W}\right)$ denote its mutual information with uniform inputs, which amounts to the capacity for any \ac{BMS} channel \cite{arikan2009channel}. Then}, $n$ independent uses of channel $\mathrm{W}$ are denoted as $\mathrm{W}^n : \mathcal{X}^n \rightarrow \mathcal{Y}^n$, with transition probabilites \textcolor{black}{(densities)} $\mathrm{W}^n(\boldsymbol{y}|\boldsymbol{x}) = \prod_{i=1}^{n} \mathrm{W}(y_i|x_i)$. In addition, we define $\mathrm{W}_{\boldsymbol{G}} : \mathcal{X}^k \rightarrow \mathcal{Y}^n$ as the channel seen by the $k$-bit message, e.g., $\boldsymbol{u}$, to be encoded into $n$-bit $\boldsymbol{x}$ by a generator matrix $\boldsymbol{G}$\textcolor{black}{, i.e., $\boldsymbol{x} = \boldsymbol{u}\boldsymbol{G}$}. In other words, the likelihood of message $\boldsymbol{u}$, encoded via $\boldsymbol{G}$, upon observing the channel output $\boldsymbol{y}$ is defined as \begin{align} \mathrm{W}_{\boldsymbol{G}}(\boldsymbol{y}|\boldsymbol{u})&\triangleq \mathrm{W}^n(\boldsymbol{y}|\boldsymbol{u}\boldsymbol{G}) \\ &= \mathrm{W}^n(\boldsymbol{y}|\boldsymbol{x}). \end{align} We write \ac{BEC}($ \epsilon_{\textcolor{black}{\mathrm{ch}}} $) to denote the \ac{BEC} with erasure probability $ \epsilon_{\mathrm{ch}} $. \textcolor{black}{Here, the output alphabet is $\mathcal{Y} = \{0,1,?\}$, where $?$ denotes an erasure. The output of the \ac{BEC}($\epsilon_{\mathrm{ch}}$) is equal to the input (i.e., $y=x$) with probability $1-\epsilon_{\mathrm{ch}}$ and it is erased (i.e., $y=?$) with probability $\epsilon_{\mathrm{ch}}$.} We denote an \ac{SPC} code with blocklength $n$ by $\mathcal{S}_n$. For a given $(n,k)$ binary linear block code $\mathcal{C}$, its complete \ac{WEF} is \begin{equation} \mathrm{A}_{\mathcal{C}}(\boldsymbol{z}) \triangleq \sum_{\boldsymbol{x}\in\mathcal{C}} \boldsymbol{z}^{\boldsymbol{x}}\label{eq:cwef} \end{equation} where $\boldsymbol{z}^{\boldsymbol{x}} \triangleq \textcolor{black}{\prod_{i=1}^n z_i^{x_i}}$. \textcolor{black}{Let $w_{\mathrm{H}}(\boldsymbol{x})$ denote the Hamming weight of vector $\boldsymbol{x}$.} One sets $z_i = z$, $i=1,\dots,n$, to get \textcolor{black}{(with slight abuse of notation)} the resulting \ac{WEF} of $\mathcal{C}$ as \begin{equation*} \mathrm{A}_{\mathcal{C}}(z) \triangleq \mathrm{A}_{\mathcal{C}}\left(z,z,\dots,z\right) = \sum_{i=0}^{n} A_iz^i \end{equation*} where $A_i$ is the number of codewords $\boldsymbol{x}\in\mathcal{C}$ of $w_{\mathrm{H}}(\boldsymbol{x})=i$ (the sequence $A_0, A_1,\ldots,A_n$ is instead referred to as the weight enumerator of the code). The distinction between complete \acp{WEF} and \acp{WEF} should be clear from the different arguments. \textcolor{black}{Finally,} we write $A_{\mathcal{C}}^{\mathrm{IO}}(x,z)$ as the \ac{IOWEF}, defined as \begin{align} \mathrm{A}_{\mathcal{C}}^{\mathrm{IO}}(x,z) \triangleq \sum_{i=0}^{k}\sum_{w=0}^{n} A_{i,w}^{\mathrm{IO}}x^iz^w \end{align} \textcolor{black}{where} $A_{i,w}^{\mathrm{IO}}$ is the number of codewords $\boldsymbol{x}\in\mathcal{C}$ of $w_{\mathrm{H}}(\boldsymbol{u})=i$ and $w_{\mathrm{H}}(\boldsymbol{x})=w$. \subsection{Product Codes} An $m$-dimensional $(n,k,d)$ product code $\mathcal{C}$ is obtained by requiring that an $m$-dimensional array of bits satisfies a \textcolor{black}{linear} code constraint along each axis \cite{Elias:errorfreecoding54}. \textcolor{black}{More precisely, the information bits are arranged in an $m$-dimensional hypercube, where the length of dimension $i\in[m]$ is $k_i$. Then, the vectors in the $\ell$-th dimension are encoded via a linear (systematic) component code $\mathcal{C}_\ell$ with parameters $(n_\ell,k_\ell,d_\ell)$, where $n_\ell$, $k_\ell$, and $ d_\ell $ are its blocklength, dimension, and minimum Hamming distance, respectively.} The parameters of the resulting product code are \textcolor{black}{\cite[Ch. 18, Sec. 2]{macwilliams}} \begin{equation} n=\prod_{\ell=1}^m n_\ell, \quad k=\prod_{\ell=1}^m k_\ell, \quad \text{and} \quad \textcolor{black}{d=\prod_{\ell=1}^m d_\ell}. \label{eq:parameters} \end{equation} \textcolor{black}{The rate of the product code is \[R\triangleq\frac{k}{n}=\prod_{\ell=1}^m R_\ell\]} where $R_\ell$ is the rate of the $\ell$-th component code. \subsubsection{Encoding} A generator matrix of the $ m $-dimensional product code is \textcolor{black}{\cite[Ch. 18, Sec. 2]{macwilliams} \begin{equation} \boldsymbol{G} = \boldsymbol{G}_{1} \otimes \boldsymbol{G}_{2} \otimes \ldots \otimes \boldsymbol{G}_{m}\label{eq:generator_product_base} \end{equation} where $\boldsymbol{G}_{\ell}$} is the generator matrix of the $\ell$-th component code. Alternatively, we can define a generator matrix recursively as follows. Let binary vectors $ \boldsymbol{u} $ and $ \boldsymbol{x} $ be the $k$-bit message to be encoded and the corresponding $n$-bit codeword, respectively, where the relation between them is given as $\boldsymbol{x} = \boldsymbol{u}\textcolor{black}{\boldsymbol{G}^{[m]}}$, $\textcolor{black}{\boldsymbol{G}^{[m]}}$ being the generator matrix of the product code with $m$ dimensions. We obtain $\textcolor{black}{\boldsymbol{G}^{[m]}}$ recursively as \begin{equation} \textcolor{black}{\boldsymbol{G}^{[m]}} = \left(\boldsymbol{I}_{\textcolor{black}{k^{[m-1]}}}\otimes\boldsymbol{G}_{\textcolor{black}{m}}\right)\boldsymbol{\Pi}_{\textcolor{black}{k^{[m-1]}},n_m}\left(\boldsymbol{I}_{n_m}\otimes\textcolor{black}{\boldsymbol{G}^{[m-1]}}\right) \label{eq:generator_product} \end{equation} where $\textcolor{black}{\boldsymbol{G}^{[0]}} \triangleq 1$ and $\textcolor{black}{k^{[m-1]}} \triangleq \prod_{i=1}^{m-1}k_i$ with $\textcolor{black}{k^{[0]}} = 1$ (observe that $\textcolor{black}{k^{[m]}} = k$). \textcolor{black}{We note also that $n = n^{[m]} \triangleq \prod_{i=1}^{m}n_i$ with $n^{[0]} = 1$. Fig. \ref{fig:transmission_recursive} depicts the encoding with \ac{SPC} product codes, where the encoding recursion is based on \eqref{eq:generator_product}.} \begin{figure*} \begin{center} \includegraphics[width=\textwidth]{./figures/prodal_recursive_enc_transmission.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{Encoding using an $(n,k,d)$ \ac{SPC} product code with $m$ dimensions.}} \label{fig:transmission_recursive} \end{figure*} \textcolor{black}{To see the relation between $\boldsymbol{G}$ and $\boldsymbol{G}^{[m]}$, we write \begin{align} \textcolor{black}{\boldsymbol{G}^{[m]}} &= \left(\boldsymbol{I}_{\textcolor{black}{k^{[m-1]}}}\otimes\boldsymbol{G}_{m}\right)\left(\textcolor{black}{\boldsymbol{G}^{[m-1]}}\otimes\boldsymbol{I}_{n_{m}}\right)\boldsymbol{\Pi}_{\textcolor{black}{n^{[m-1]}},n_{m}}\label{eq:generator_equivalence1}\\ &\!\!\!\!\!\!\!\!\!\!= \left(\textcolor{black}{\boldsymbol{G}^{[m-1]}}\otimes\boldsymbol{G}_{m}\right)\boldsymbol{\Pi}_{\textcolor{black}{n^{[m-1]}},n_{m}}\label{eq:generator_equivalence2} \\ &\!\!\!\!\!\!\!\!\!\!= \left(\boldsymbol{G}_{1}\otimes\boldsymbol{G}_{2}\otimes\ldots\otimes\boldsymbol{G}_{m}\right)\prod_{i=1}^{m}\left(\boldsymbol{\Pi}_{\textcolor{black}{n^{[i-1]}},n_{i}}\otimes\boldsymbol{I}_{\nicefrac{\textcolor{black}{n^{[m]}}}{\textcolor{black}{n^{[i]}}}}\right)\label{eq:generator_equivalence5} \end{align} where \eqref{eq:generator_equivalence1} follows from applying the identity \[\boldsymbol{\Pi}_{\textcolor{black}{k^{[m-1]}},n_m}\left(\boldsymbol{I}_{n_m}\otimes\textcolor{black}{\boldsymbol{G}^{[m-1]}}\right) = \left(\textcolor{black}{\boldsymbol{G}^{[m-1]}}\otimes\boldsymbol{I}_{n_{m}}\right)\boldsymbol{\Pi}_{\textcolor{black}{n^{[m-1]}},n_{m}}\] \own{and \eqref{eq:generator_equivalence2} from the mixed-product identity. Then, \eqref{eq:generator_equivalence5} follows by re-writing $\boldsymbol{G}^{[m-1]}$ through \eqref{eq:generator_product} and by applying similar steps, recursively}. By noting the fact that the product of an arbitrary number of permutation matrices yields another permutation matrix, we can conclude that $\boldsymbol{G}$ and $\boldsymbol{G}^{[m]}$ are equivalent up to a column permutation for all $m\geq 1$.} \subsubsection{Distance Spectrum} Although the characterization of the complete distance spectrum of a product code is still an open problem even for the case where the distance spectrum of its component codes is known\textcolor{black}{\cite{Tolhuizen02,El-Khamy05:conf,El-Khamy05}}, the minimum distance multiplicity is known~\textcolor{black}{\cite[Theorem 3]{TOLHUIZEN92}} and equal to \[ A_{\textcolor{black}{d^{[m]}}}=\prod_{\ell=1}^m A^{(\ell)}_{d_\ell}. \] \textcolor{black}{Here, $ A^{(\ell)}_{d_\ell} $ is the minimum distance multiplicity of the $ \ell $-th component code.} As a final remark, note that product codes can be \textcolor{black}{seen as a special class of generalized \ac{LDPC} codes} \cite{Tanner}. \ac{SPC} product codes, in particular, are a special class of (left-regular) \ac{LDPC} \cite{ldpc}, whose bipartite graph representation has girth $8$. \subsection{Polar Codes} \label{sec:polar} Polar codes were \textcolor{black}{shown to be} the first class of provably capacity-achieving codes with low encoding and decoding complexity over any \ac{BMS} channel under \textcolor{black}{low-complexity} \ac{SC} decoding \cite{arikan2009channel}. In addition to the theoretical interest, polar codes concatenated with an outer \ac{CRC} code are very attractive from a practical viewpoint\textcolor{black}{\cite[Ch. 5]{5G20}} thanks to their \textcolor{black}{excellent} performance \textcolor{black}{under} \ac{SCL} decoding \cite{tal15} in \textcolor{black}{the} short and moderate blocklength regime \cite{Coskun18:Survey}. \textcolor{black}{A transform matrix for a length $n = 2^m$ polar code is defined as $\boldsymbol{\mathsf{K}}_2^{\otimes m}$, where $\boldsymbol{\mathsf{K}}_2^{\otimes m}$ is the $m$-fold Kronecker product with $\boldsymbol{\mathsf{K}}_2^{\otimes 0}\triangleq 1$. Similar to the generator matrix \eqref{eq:generator_product} of product codes, an alternative construction of the transformation is possible. In this case, the $n \times n$ transform matrix $\boldsymbol{\mathsf{G}}^{[m]}$ is constructed recursively as \begin{equation} \label{eq:generator_polar} \boldsymbol{\mathsf{G}}^{[m]} = \left(\boldsymbol{I}_{n/2}\otimes\boldsymbol{\mathsf{K}}_{2}\right)\boldsymbol{\Pi}_{n/2,2}\left(\boldsymbol{I}_2\otimes\boldsymbol{\mathsf{G}}^{[m-1]}\right) \end{equation} where the kernel at each recursion is fixed and it is defined as \[ \boldsymbol{\mathsf{K}}_{2}\triangleq\begin{bmatrix} 1 & 0 \\ 1 & 1 \end{bmatrix} \] and $\boldsymbol{\mathsf{G}}^{[0]} \triangleq 1$. Let $\boldsymbol{w}$ be any vector in $\mathcal{X}^n$ and it is mapped onto $\boldsymbol{x}$ as $\boldsymbol{x} = \boldsymbol{w}\boldsymbol{\mathsf{G}}^{[m]}$. Transition probabilities of the $i$-th bit-channel, a \emph{synthesized} channel with the input $w_i$ and the output $(\boldsymbol{y}, w_1^{i-1})$, are defined by \begin{equation} \mathrm{W}^{(i)}_{\boldsymbol{\mathsf{G}}^{[m]}}(\boldsymbol{y},w_1^{i-1}|w_i) \triangleq \sum_{w_{i+1}^n\in\mathcal{X}^{n-i}} \frac{1}{2^{n-1}}\mathrm{W}_{\boldsymbol{\mathsf{G}}^{[m]}}(\boldsymbol{y}|\boldsymbol{w}). \label{eq:bit_ML_polar} \end{equation} The channels $\mathrm{W}^{(i)}_{\boldsymbol{\mathsf{G}}^{[m]}}$, $i\in[n]$, polarize, i.e, the fraction of channels with $I\left(\mathrm{W}^{(i)}_{\boldsymbol{\mathsf{G}}^{[m]}}\right)>1-\delta$ goes to $I\left(\mathrm{W}\right)$ and the fraction of channels with $I\left(\mathrm{W}^{(i)}_{\boldsymbol{\mathsf{G}}^{[m]}}\right)<\delta$ to $1-I\left(\mathrm{W}\right)$ for any $\delta\in(0,1)$ as $n\rightarrow\infty$\cite[Theorem 1]{arikan2009channel}.} \textcolor{black}{A generator matrix $\boldsymbol{G}$} is obtained by removing the rows of \textcolor{black}{$\boldsymbol{\mathsf{G}}^{[m]}$} with indices in $\mathcal A$, where $\mathcal A$ is the set containing the indices of the frozen bits. We refer to the matrix \textcolor{black}{$\boldsymbol{\mathsf{G}}^{[m]}$} as the \textcolor{black}{polar transform}, from which the desired polar code is derived. Encoding can be performed by multiplying the $k$-bit message $\boldsymbol{u}$ by $\boldsymbol{G}$, i.e., $\boldsymbol{x} = \boldsymbol{u}\boldsymbol{G}$. Equivalently, the encoding process can be described via matrix \textcolor{black}{$\boldsymbol{\mathsf{G}}^{[m]}$}. In this case, an $n$-bit vector \textcolor{black}{$\boldsymbol{w}$} has to be defined, where $\textcolor{black}{w_i}=0$ for all $i\in \mathcal A$ and the remaining $k$ elements of \textcolor{black}{$\boldsymbol{w}$} carry information. Encoding is then performed as $\boldsymbol{x}=\textcolor{black}{\boldsymbol{w}\boldsymbol{\mathsf{G}}^{[m]}}$. It was already mentioned in \cite{arikan2009channel} that generalizations of polar codes \textcolor{black}{are} possible by choosing different kernels than $\boldsymbol{\mathsf{K}}_{2}$ \textcolor{black}{and those kernels can even} be mixed. Later, the conditions for polarizing kernels \textcolor{black}{were} provided in \cite{KSU10} and corresponding error exponents \textcolor{black}{were} derived. Then, \cite{benammar_land} extended the error exponent derivation \textcolor{black}{to} the constructions mixing kernels as \cite{arikan2009channel} suggested\textcolor{black}{, while} \cite{gabry_land} provided \textcolor{black}{examples of} constructions using this approach, namely multi-kernel polar codes. In the following, we \textcolor{black}{study the relations between \ac{SPC} product codes and multi-kernel polar codes. In particular, we show how the kernels and the frozen bits can be chosen so that the tools of multi-kernel polar codes can be used in the description of \ac{SPC} product codes.} \section{Successive Cancellation Decoding of Single Parity-Check Product Codes} \label{sec:sc} Consider transmission over a \ac{BMS} channel $ \mathrm{W} $ using \textcolor{black}{an} $m$-dimensional $(n,k)$ \textcolor{black}{systematic} \ac{SPC} product code $\mathcal{C}$ with generator matrix $\textcolor{black}{\boldsymbol{G}^{[m]}}$ \textcolor{black}{as in \eqref{eq:generator_product}, with component code generator matrices $\boldsymbol{G}_{\textcolor{black}{m}}$ obtained by removing the first row of the kernels of the form \eqref{eq:kernel} (see Example \ref{ex:construction})}. Assume now that one is interested in the likelihood of $u_i$ upon observing \textcolor{black}{the channel output $ \boldsymbol{y} \in \mathcal{Y}^n$} and given the knowledge of $u_1^{i-1}$ \begin{equation} \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},u_1^{i-1}|u_i) \triangleq \sum_{u_{i+1}^k\in\mathcal{X}^{k-i}} \frac{1}{2^{k-1}}\mathrm{W}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|\boldsymbol{u}). \label{eq:bit_ML} \end{equation} \textcolor{black}{Assume further that we interpret the \ac{SPC} product code by the multi-kernel polar code perspective discussed in Sec. \ref{sec:spcpc_as_pc} as depicted in Fig. \ref{fig:size9_polar_construction_PC}(a). The evaluation of \eqref{eq:bit_ML} entails the use of the knowledge of \emph{all} frozen bits, i.e., all $w_j$ with $j\in\mathcal{A}_{\mathrm{PC}}$, including the ones with indices larger than the bit index under consideration, e.g., the knowledge of $w_7 = 0$ to compute \eqref{eq:bit_ML} for $i=1$ or $i=2$.\footnote{\textcolor{black}{In fact, note that this suboptimality is encountered also in polar codes for the decoding of the $i$-th bit \textcolor{black}{$w_i$} because of the assumption that the future frozen bits $\{\textcolor{black}{w_j}: j\in\mathcal{A}, i<j\leq n\}$ are uniform \acp{RV} \textcolor{black}{(see Fig. \ref{fig:size9_polar_construction_PC}(b))} although they are deterministic and known.}} \ac{SC} decoding allows evaluating \eqref{eq:bit_ML} with good accuracy. The recursive operation of the \ac{SC} decoder can be easily described by means of the representation in Fig. \ref{fig:size9_polar_construction_PC}(b).} \ac{SC} decoding follows the schedule in \cite{arikan2009channel,stolte2002rekursive} for polar codes. Explicitly, decision $\hat{\boldsymbol{u}}$ is made successively as \begin{equation} \textcolor{black}{\hat{u}_i(\boldsymbol{y},\hat{u}_1^{i-1})} = \left\{\begin{array}{lll} 0 &\text{if}& \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\hat{u}_1^{i-1}|0) \geq \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\hat{u}_1^{i-1}|1) \\ 1 &\text{if}& \text{otherwise} \end{array} \right. \label{eq:decision2} \end{equation} for $i=1,\dots,k$ by approximating $\mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\textcolor{black}{u}_1^{i-1}|u_i)$ \textcolor{black}{recursively as follows: Let $\boldsymbol{y}^{[m]}\triangleq y_1^{n^{[m]}}$ be the channel output vector for the $m$-dimensional \ac{SPC} product code. Assume $\boldsymbol{y}^{[m]}$ to be partitioned into $n_m$ blocks of length-$n^{[m-1]}$, where the $j$-th block is denoted as $\boldsymbol{y}_j^{[m]}\triangleq y_{jn^{[m-1]}+1}^{(j+1)n^{[m-1]}}$, $j=0,1,\ldots,k_m$ (see Fig. \ref{fig:transmission_recursive}). Then, the recursion to compute the likelihoods is} \own{given as \eqref{eq:recurs_metric} at the top of the next page and it is} continued down to $\mathrm{W}_{1}^{(1)}(y_i|x_i) \triangleq \mathrm{W}(y_i|x_i)$. \begin{figure} \begin{center} \includegraphics[width=0.9\columnwidth]{./figures/SPC_dec_sc_generic.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{The decoding graph of a $(5,4)$ \ac{SPC} code illustrating the \ac{SC} decoding equation \eqref{eq:recurs_metric} for bit $u_3$ with $j = 0$ and $t = 3$. Note that the arrows denote the flow of the quantities on the graph. The filled circles denote the equality constraints while the summation sign in the circle denote a parity check constraint. The knowledge of the bits $u_{1}^{2} = (1,0)$ is available while the upcoming bit $u_{4}$ is assumed to be uniformly distributed, illustrated with a dashed line.}} \label{fig:local_dec_sc} \end{figure} \begin{figure*}[t] \footnotesize \begin{align} &\mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}\left(\textcolor{black}{\boldsymbol{y}^{[m]}},\textcolor{black}{u}_1^{i-1}|u_i\right) \approx \sum_{u_{i+1}^{(j+1)k_{m}}}\frac{1}{2^{k_{m}-1}}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\left(\textcolor{black}{\boldsymbol{y}_0^{[m]}},\bigoplus_{i^\prime = 1}^{k_m} \textcolor{black}{u}_{i^\prime,k_m}^{jk_m}\Big|\bigoplus_{i^\prime = 1}^{k_m} u_{jk_m+i^\prime}\right)\prod_{j^\prime=1}^{k_m}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\left(\textcolor{black}{\boldsymbol{y}_{j^\prime}^{[m]}},\textcolor{black}{u}_{j^\prime,k_m}^{jk_m}\Big|u_{jk_m+j^\prime}\right)\label{eq:recurs_metric1} \\ &= \!\prod_{j^\prime=1}^{t}\!\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\!\left(\boldsymbol{y}_{j^\prime}^{[m]},\textcolor{black}{u}_{j^\prime,k_m}^{jk_m}\Big|u_{jk_m+j^\prime}\right)\!\sum_{u_{i+1}^{(j+1)k_{m}}}\!\frac{1}{2^{k_{m}-1}}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\!\left(\boldsymbol{y}_{0}^{[m]},\bigoplus_{i^\prime = 1}^{k_m} \textcolor{black}{u}_{i^\prime,k_m}^{jk_m}\Big|\bigoplus_{i^\prime = 1}^{k_m} u_{jk_m+i^\prime}\!\right)\!\prod_{j^\prime= t+1 }^{k_m}\!\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\!\left(\boldsymbol{y}_{j^\prime}^{[m]},\textcolor{black}{u}_{j^\prime,k_m}^{jk_m}\Big|u_{jk_m+j^\prime}\!\right) \label{eq:recurs_metric} \end{align} where $j = \lfloor\frac{i-1}{k_m}\rfloor$ and $t = [(i-1)\!\!\mod k_m] +1$. \newline\rule{\textwidth}{.4pt} \end{figure*} \textcolor{black}{To gain insight on \eqref{eq:recurs_metric1} and \eqref{eq:recurs_metric}, let us consider the simple case of a length-$5$ \ac{SPC} code with generator matrix $\boldsymbol{G}$. As illustrated in Fig. \ref{fig:local_dec_sc}, suppose that we are interested in the likelihood $\mathrm{W}^{(3)}_{\boldsymbol{G}}(\boldsymbol{y},u_1^{2}|u_3)$, for every $u_3\in\{0,1\}$, by assuming that the previous bits are given as $u_1^2 = (1,0)$. Using \eqref{eq:recurs_metric}, the computation is performed as \begin{align} \mathrm{W}^{(3)}_{\boldsymbol{G}}(\boldsymbol{y},u_1^{2}|u_3) &= \prod_{j^\prime=1}^{3}\mathrm{W}_{1}^{(1)}\left(y_{j^\prime+1}|u_{j^\prime}\right)\cdot\\ &\sum_{u_{4}}\!\frac{1}{2^{3}}\mathrm{W}_{1}^{(1)}\!\left(y_{1}| u_1\!\oplus \!u_2\!\oplus\! u_3\!\oplus\! u_4\!\right)\!\mathrm{W}_{1}^{(1)}\!\left(y_{5}|u_{4}\!\right) \\ &=\mathrm{W}\left(y_{2}|1\right)\mathrm{W}\left(y_{3}|0\right)\mathrm{W}\left(y_4|u_3\right)\cdot\\ &\sum_{u_{4}}\frac{1}{2^{3}}\mathrm{W}\left(y_{1}| 1\oplus u_3\oplus u_4\right)\mathrm{W}\left(y_{5}|u_{4}\right) \label{eq:recurs_metric_SPC} \end{align} where \eqref{eq:recurs_metric_SPC} follows by plugging in the values of bits $u_1^2$ and noting that the recursion ends at $\mathrm{W}_{1}^{(1)}(y_i|x_i) = \mathrm{W}(y_i|x_i)$, where $x_1 = \bigoplus_{i=1}^4 u_i$ and $x_{i+1} = u_i$, $i=1,2$.\footnote{\textcolor{black}{Note also that \eqref{eq:recurs_metric_SPC} computes the desired probability exactly since there is no future frozen bit in the polar code representation of an \ac{SPC} code while decoding any information bit. This turns out to be an approximation for the case of an \ac{SPC} product code, i.e., when $m\geq 2$.}}} Over the \ac{BEC}, ties are not broken towards any decision by revising \eqref{eq:decision2} as \begin{equation} \textcolor{black}{\hat{u}_i(\boldsymbol{y},\hat{u}_1^{i-1})} = \left\{\begin{array}{lll}\vspace{1mm} 0 &\text{if}& \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\hat{u}_1^{i-1}|0) > \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\hat{u}_1^{i-1}|1) \\\vspace{1mm} \textcolor{black}{?} &\text{if}& \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\hat{u}_1^{i-1}|0) = \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y},\hat{u}_1^{i-1}|1) \\ 1 &\text{if}& \textcolor{black}{\text{otherwise.}} \end{array} \right. \label{eq:decision_BEC} \end{equation} \textcolor{black}{for $i=1,\dots,k$}. A block error event occurs if $ \hat{\boldsymbol{u}} \neq \boldsymbol{u} $\textcolor{black}{, where \[\hat{\boldsymbol{u}}\triangleq (\hat{u}_1(\boldsymbol{y}),\hat{u}_2(\boldsymbol{y},\hat{u}_1),\ldots,\hat{u}_k(\boldsymbol{y},\hat{u}_1^{k-1})).\]} The event that the decoding of $u_i$ is erroneous under \ac{SC} decoding, for which the knowledge of $u_1^{i-1}$ is available at the decoder via a genie, is defined as \begin{equation*} \mathcal{B}_{\mathrm{SC},i}^{\mathrm{GA}} \triangleq \{(\boldsymbol{u}, \boldsymbol{y})\in\mathcal{X}^k\times\mathcal{Y}^n: \hat{u}_i(\boldsymbol{y},u_1^{i-1}) \neq u_i\}. \end{equation*} Then, the block error event of the \ac{SC} decoding is equal to that of the genie-aided \ac{SC} decoding as stated in the following lemma. The proof is skipped as it can be easily \textcolor{black}{derived} from\textcolor{black}{\cite[Lemma 1]{Mori:2009SIT}}. \begin{lemma} \label{lem:block_error} The block error event for the \ac{SC} decoder satisfies \[\mathcal{E}_{\mathrm{SC}} = \bigcup_{i=1}^{k} \mathcal{B}_{\mathrm{SC},i}^{\mathrm{GA}}.\] \end{lemma} \textcolor{black}{The block error probability under \ac{SC} decoding, denoted by $P_{\mathrm{SC}}$, is defined as $P_{\mathrm{SC}}\triangleq P(\mathcal{E}_{\mathrm{SC}})$ and it is bounded as \begin{equation} \label{eq:SC_bound} \max_{i=1,\ldots,k} P(\mathcal{B}_{\mathrm{SC},i}^{\mathrm{GA}}) \leq P_{\mathrm{SC}} \leq\sum_{i=1}^{k} P(\mathcal{B}_{\mathrm{SC},i}^{\mathrm{GA}}) \end{equation} where the upper bound follows from the straightforward application of the union bound.} \begin{remark} Assume now that one is interested in the likelihood of $u_i$ upon observing $\boldsymbol{y}$ (by not imposing any order in the decoding) \begin{equation} \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|u_i) \triangleq \sum_{\boldsymbol{u}_{\sim i}\in\mathcal{X}^{k-1}} \frac{1}{2^{k-1}}\mathrm{W}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|\boldsymbol{u}). \label{eq:bit_ML_elias} \end{equation} Observe that \eqref{eq:bit_ML_elias} corresponds to the bit-wise \ac{ML} function of \textcolor{black}{the} information bit $u_i$. \textcolor{black}{Computing \eqref{eq:bit_ML_elias} is hard in general}. Elias' decoder \cite{Elias:errorfreecoding54} tackles the problem as follows: the likelihoods of \textcolor{black}{the} bits $u_i$ \eqref{eq:bit_ML_elias} are approximated starting from the first dimension up to the last one in a one-sweep fashion. \textcolor{black}{Let $\boldsymbol{u}^{[m]}\triangleq u_1^{k^{[m]}}$ be the $k$-bit information to be encoded via $m$-dimensional \ac{SPC} product code and it is divided into $k^{[m-1]}$ blocks of length $k_m$, where $j$-th block is denoted as $\boldsymbol{u}_{j}^{[m]}\triangleq u_{jk_m+1}^{(j+1)k_m}$, $j=0,\ldots,k^{[m-1]}-1$ (see Fig. \ref{fig:transmission_recursive}).} For the computation, \eqref{eq:recurs_metric} is revised as \begin{figure*}[t] \footnotesize \begin{align} \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}\left(\textcolor{black}{\boldsymbol{y}^{[m]}}|u_i\right) &\approx \sum_{\textcolor{black}{(\boldsymbol{u}_{j}^{[m]})_{\sim i}}}\frac{1}{2^{k_m-1}}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\left(\textcolor{black}{\boldsymbol{y}_0^{[m]}}\Big|\bigoplus_{i^\prime = 1}^{k_m} u_{jk_m+i^\prime}\right)\prod_{j^\prime=1}^{k_m}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\left(\textcolor{black}{\boldsymbol{y}_{j^\prime}^{[m]}}\Big|u_{jk_m+j^\prime}\right)\\ &\textcolor{black}{=\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\!\left(\textcolor{black}{\boldsymbol{y}_{t}^{[m]}}\Big|u_{jk_m+t}\right)\sum_{\textcolor{black}{(\boldsymbol{u}_{j}^{[m]})_{\sim i}}}\frac{1}{2^{k_m-1}}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\left(\textcolor{black}{\boldsymbol{y}_{0}^{[m]}}\Big|\bigoplus_{i^\prime = 1}^{k_m} u_{jk_m+i^\prime}\right)\prod_{j^\prime=1,j^\prime\neq t}^{k_m}\mathrm{W}^{(j+1)}_{\textcolor{black}{\boldsymbol{G}^{[m-1]}}}\!\left(\textcolor{black}{\boldsymbol{y}_{j^\prime}^{[m]}}\Big|u_{jk_m+j^\prime}\right)} \label{eq:recurs_elias_metric} \end{align} where $j = \lfloor\frac{i-1}{k_m}\rfloor$ and $t = [(i-1)\!\!\mod k_m] +1$. \newline\rule{\textwidth}{.4pt} \end{figure*} \own{\eqref{eq:recurs_elias_metric}}. On contrary to \ac{SC} decoding, the summation is over all information bits of the local SPC code in the $m$-th level except for $u_i$, i.e., over all $(\boldsymbol{u}_{j}^{[m]})_{\sim i}\in\{0,1\}^{k_m-1}$, which is computed for both values of $u_i$. In other words, the decoder does not make use of any decision on information bits to decode another one. This enables fully parallel computation of the likelihoods \eqref{eq:recurs_elias_metric} for each bit. \textcolor{black}{To better illustrate the difference to the \ac{SC} decoding, we consider the Elias' decoding of bit $u_3$ in Fig. \ref{fig:local_dec_ed} for the case of $(5,4)$ \ac{SPC} code. In particular, we are interested in the likelihoods $\mathrm{W}^{(3)}_{\boldsymbol{G}}(\boldsymbol{y}|u_3)$, for every $u_3\in\{0,1\}$. Using \eqref{eq:recurs_elias_metric}, we compute \begin{align} &\mathrm{W}^{(3)}_{\boldsymbol{G}}(\boldsymbol{y}|u_3) = \mathrm{W}_{1}^{(1)}\left(y_{4}|u_{3}\right)\cdot\\ &\,\,\,\,\sum_{\own{\boldsymbol{u}_{\sim 3}}}\frac{1}{2^{3}}\mathrm{W}_{1}^{(1)}\left(y_{1}| u_1\oplus u_2\oplus u_3\oplus u_4\right)\prod_{j^\prime = 1,\,j^\prime \neq 3}^{4}\mathrm{W}_{1}^{(1)}\left(y_{j^\prime+1}|u_{j^\prime}\right) \\ &=\!\mathrm{W}\!\left(y_4|u_3\!\right)\!\sum_{\own{\boldsymbol{u}_{\sim 3}}}\frac{1}{2^{3}}\mathrm{W}\!\left(y_{1}| 1\oplus u_3\oplus u_4\right)\!\own{\prod_{j^\prime = 1,\,j^\prime \neq 3}^{4}\!\mathrm{W}\left(y_{j^\prime+1}|u_{j^\prime}\right)}. \label{eq:recurs_metric_SPC_ed} \end{align}} \begin{figure} \begin{center} \includegraphics[width=0.9\columnwidth]{./figures/SPC_dec_ed_generic.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{The decoding graph of a $(5,4)$ \ac{SPC} code illustrating the Elias' decoding equation \eqref{eq:recurs_elias_metric} for bit $u_3$ with $j = 0$ and $t = 3$. Note that the arrows denote the flow of the quantities on the graph. The filled circles denote the equality constraints while the summation sign in the circle denote a parity check constraint. Unlike \ac{SC} decoding, bits $u_{\{1,2,4\}}$ are assumed to be uniformly distributed, illustrated with a dashed line. Hence, Elias' decoding of each bit $u_i$ can be run in parallel.}} \label{fig:local_dec_ed} \end{figure} Elias' decoder, then, makes a decision \textcolor{black}{as \begin{equation} \hat{u}_i^{(\mathrm{E})}(\boldsymbol{y}) = \left\{\begin{array}{lll} 0 &\text{if}& \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|0) \geq \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|1) \\ 1 &\text{if}& \text{otherwise} \end{array} \right. \label{eq:decision_elias} \end{equation} for $i\in[k]$. Over the BEC, the decision function is modified as \begin{equation} \hat{u}_i^{(\mathrm{E})}(\boldsymbol{y}) = \left\{\begin{array}{lll}\vspace{1mm} 0 &\text{if}& \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|0) > \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|1) \\\vspace{1mm} ? &\text{if}& \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|0) = \mathrm{W}^{(i)}_{\textcolor{black}{\boldsymbol{G}^{[m]}}}(\boldsymbol{y}|1) \\ 1 &\text{if}& \text{otherwise.} \end{array} \right. \label{eq:decision_Elias_BEC} \end{equation}} \textcolor{black}{A block error event occurs if $ \hat{\boldsymbol{u}}^{(\mathrm{E})} \neq \boldsymbol{u} $, where \[\hat{\boldsymbol{u}}^{(\mathrm{E})}\triangleq (\hat{u}_1^{(\mathrm{E})}(\boldsymbol{y}),\hat{u}_2^{(\mathrm{E})}(\boldsymbol{y}),\ldots,\hat{u}_k^{(\mathrm{E})}(\boldsymbol{y})).\]} \end{remark} \section{Successive Cancellation List Decoding of Single Parity-Check Product Codes} \label{sec:scl} While the asymptotic analysis provided in Section \ref{subsec:asymptotic} provides some insights on the \ac{SPC} product codes constructed over a large number of dimensions (yielding very large block lengths), we are ultimately interested in the performance of product codes in the practical setting where the number of dimensions is small, and the block length is moderate (or small). \textcolor{black}{Like} polar codes, \ac{SC} decoding of \ac{SPC} product codes \textcolor{black}{performs} poorly in this regime\textcolor{black}{, e.g., see Fig. \ref{fig:sc_125_64_SPC}}. Hence, following the footsteps of \cite{tal15}, \textcolor{black}{we} investigate the error probability of \ac{SPC} product codes under \ac{SCL} decoding. \textcolor{black}{The} \ac{SC} decoder decides on the value of $u_i$, $1\leq i\leq k$, after computing the corresponding likelihood. The \ac{SCL} decoder \textcolor{black}{does not make} a final decision on the bit value $u_i$ immediately. Instead, it \textcolor{black}{considers both options (i.e., $\hat{u}_i = 0$ and $\hat{u}_i = 1$) and runs several instances of \textcolor{black}{the} \ac{SC} decoder in parallel}. Each \textcolor{black}{\ac{SC} decoder} corresponds to a decoding \emph{path}, \textcolor{black}{defined by a given} different hypothesis on $i-1$ preceding \textcolor{black}{information} bits, namely $\hat{u}_1^{i-1}$, $1 < i < k$, at decoding stage $i$. After computing the likelihood for $u_i$, \textcolor{black}{a} path is split into two new paths, \textcolor{black}{that share the} same decisions $\hat{u}_1^{i-1}$ for the preceding $i-1$ bits. \textcolor{black}{But these} new paths consider \textcolor{black}{different} decisions \textcolor{black}{for $\hat{u}_i$ (i.e., $\hat{u}_i = 0$ and $\hat{u}_i = 1$),} respectively, which doubles the number of paths at each \textcolor{black}{decoding stage}. \textcolor{black}{In order to avoid an \textcolor{black}{excessive} growth in the number of paths, a maximum list size $L$ is imposed. The} \ac{SCL} decoder discards the paths \textcolor{black}{except for the most likely paths, according to metrics computed via \eqref{eq:recurs_metric},} whenever their number exceeds \textcolor{black}{the} list size $L$. After $k$ steps, among the surviving $L$ candidates, the \ac{SCL} decoder chooses as the final decision the candidate \textcolor{black}{path} maximizing the likelihood\textcolor{black}{, yielding a decision $\hat{\boldsymbol{u}}$}. Obviously, the block error rate decreases with an increasing $L$ at the expense of a higher complexity. \begin{remark}\label{remark:ML} For \textcolor{black}{short- and moderate-length} polar codes, it was shown in \cite{tal15} that \textcolor{black}{close-to-\ac{ML}} performance can be attained with a sufficiently large \textcolor{black}{(yet, manageable)} list size. This was demonstrated by computing a numerical lower bound on the \ac{ML} decoding error probability via Monte Carlo simulation, where the correct codeword is introduced artificially in the final list, prior to the final \textcolor{black}{decision}. If, for a specific list size $L$, the simulated error probability is close to the numerical \ac{ML} decoding lower bound, then increasing the list size $L$ would not yield any performance improvement. The same principle applies to \ac{SCL} decoding of \ac{SPC} product codes. \end{remark} Owing to this observation, we \textcolor{black}{first} study the performance of \ac{SPC} product codes under \ac{ML} decoding, by developing a weight enumerator analysis. Similarly, inspired by the concatenated polar code construction of \cite{tal15}, we \textcolor{black}{also} study the performance of a concatenation of a high-rate outer code with an inner \ac{SPC} product code under \ac{ML} decoding. \textcolor{black}{For both cases, t}he analysis is complemented by the \ac{SCL} decoding simulations\textcolor{black}{. We will see that (for some short product codes) the \ac{ML} decoding performance is indeed attainable by \ac{SCL} decoding with small list sizes, e.g., $L\leq 8$, while moderate list sizes, e.g., $128\leq L\leq 1024$, are required when \ac{SPC} product codes are concatenated with an outer code}. \textcolor{black}{\subsection{Finite-length Performance Analysis via Weight Distribution of SPC Product Codes} \label{sec:wef_SPC_PC} Computing the weight enumerator of \ac{SPC} product codes for small constructions is feasible using the method presented in \cite{caire}. First, we provide an alternative derivation to the \ac{WEF} of a $2$-dimensional product code $\mathcal{C}$ with systematic arbitrary binary linear component code $\mathcal{C}_1$ and systematic $(\nu,\nu-1)$ \ac{SPC} code $\mathcal{S}_\nu$ as the second component code. \begin{theorem} \label{theorem:wef_spc} Let $\mathcal{C}_1$ and $\mathcal{S}_\nu$ be an arbitrary $(n_1,k_1)$ systematic code with a generator matrix \textcolor{black}{$\boldsymbol{G}$} and a length-$\nu$ systematic \ac{SPC} code, respectively. Then, the \ac{WEF} of the product code $\mathcal{C}$ with component codes $\mathcal{C}_1$ and $\mathcal{S}_\nu$ is \begin{equation} A_{\mathcal{C}}(z) = 2^{-k_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{v}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}} \left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}(-1)^{\boldsymbol{u}\cdot\boldsymbol{v}^\mathrm{T}}z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\textcolor{black}{\boldsymbol{G}}\right)}\right)^\nu.\label{eq:theorem_wef} \end{equation} \end{theorem}} \begin{proof} \textcolor{black}{Let $f(\boldsymbol{Z}) = \prod_{i=1}^\nu f_i(z_{i,1},\ldots,z_{i,n})$ be a multinomial in the variables $\boldsymbol{Z} = \{z_{i,j}\}$, $1\leq i\leq \nu$, $1\leq j\leq \own{n}$, where each factor $f_i$ is a multinomial only in the variables $z_{i,1},\ldots,z_{i,n}$. Assume further that each variable $z_{i,j}$ appears with exponent either $0$ or $1$ in the multinomial $f_i(z_{i,1},\ldots,z_{i,n})$, and, hence, in $f(\boldsymbol{Z})$.} \textcolor{black}{Suppose now that we wish to remove from $f(\boldsymbol{Z})$ all the terms in the form \begin{equation} \prod_{i\in\mathcal{T}}z_{i,j} \end{equation} where $|\mathcal{T}|$ is odd. The remaining terms can be obtained by computing \begin{equation} \frac{1}{2}\sum_{y\in\{+1,-1\}}\prod_{i=1}^\nu f_i(z_{i,1},\ldots,z_{i,j-1},yz_{i,j},z_{i,j+1},\ldots,z_{i,n}). \end{equation} Similarly, to remove all the terms in the form \begin{equation} \prod_{i\in\mathcal{T}_j}z_{i,j},\quad j\in[n] \end{equation} where $|\mathcal{T}_j|$ is odd, it is sufficient to evaluate \begin{align} 2^{-n}\sum_{\boldsymbol{y}\in\{+1,-1\}^n}\prod_{i=1}^\nu f_i(y_1z_{i,1},\ldots,y_nz_{i,n}). \end{align} } \textcolor{black}{Consider first a product code composed of $\nu\times n_1$ arrays whose rows and columns are codewords of $\mathcal{C}_1$ and a trivial rate-$1$ code $\mathcal{I}$ with a generator matrix $\boldsymbol{I}_\nu$, respectively. Then, the complete \ac{WEF} $A_{\mathcal{C}_1\otimes\mathcal{I}}(\boldsymbol{Z})$ of the product code uses the dummy variables $\boldsymbol{Z} = \{z_{i,j}\}$, $1\leq i\leq \nu$, $1\leq j\leq n_1$, to track bits by their $(i,j)$ coordinate in the codeword. This is obtained simply by the multiplication of the complete \acp{WEF} for the codes corresponding to each row $i$, i.e., we have \begin{equation} \label{eq:comp_wef_prod_trivial} A_{\mathcal{C}_1\otimes\mathcal{I}}(\boldsymbol{Z}) = \prod_{i=1}^{\nu}A_{\mathcal{C}_{\scaleto{1}{3pt}}}(z_{i,1},\ldots,z_{i,n_{\scaleto{1}{3pt}}}). \end{equation} Recall now that the codewords of $\mathcal{C}$ are $\nu\times n_1$ arrays whose rows and columns are codewords of $\mathcal{C}_1$ and $\mathcal{S}_\nu$, respectively. Then, the complete \ac{WEF} $A_{\mathcal{C}}(\boldsymbol{Z})$ of the product code $\mathcal{C}$ is derived from $A_{\mathcal{C}_1\otimes\mathcal{I}}(\boldsymbol{Z})$ by imposing that each column word has an even weight, i.e., we have \begin{align} \!\!\!\!\!\!\!\!A_{\mathcal{C}}(\boldsymbol{Z}) = 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{+1,-1\}^{n_{\scaleto{1}{3pt}}}} \prod_{i=1}^{\nu}A_{\mathcal{C}_{\scaleto{1}{3pt}}}(y_1z_{i,1},\dots,y_{n_{\scaleto{1}{3pt}}}z_{i,n_{\scaleto{1}{3pt}}}).\label{eq:comp_wef_prod} \end{align} Then, the \ac{WEF} of the product code $\mathcal{C}$ is obtained by setting $z_{i,j} = z$, yielding \begin{align} &A_{\mathcal{C}}(z) = 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{1,-1\}^{n_{\scaleto{1}{3pt}}}} \left(A_{\mathcal{C}_{\scaleto{1}{3pt}}}(y_1z,\dots,y_{n_{\scaleto{1}{3pt}}}z)\right)^\nu \label{eq:wef_step1}\\ &= 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{1,-1\}^{n_{\scaleto{1}{3pt}}}}\left(\sum_{\boldsymbol{x}\in\mathcal{C}_1} z^{w_{\scaleto{\mathrm{H}}{3pt}}(\boldsymbol{x})}\prod_{i^\prime = 1}^{n_1}y_{i^\prime}^{x_{i^\prime}}\right)^{\nu} \label{eq:wef_step2}\\ &= 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{0,1\}^{n_{\scaleto{1}{3pt}}}}\left(\sum_{\boldsymbol{x}\in\mathcal{C}_1} z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{x}\right)}(-1)^{\boldsymbol{x}\cdot\boldsymbol{y}^{\mathrm{T}}} \right)^\nu \label{eq:wef_step4}\\ &= 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{0,1\}^{n_{\scaleto{1}{3pt}}}}\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\boldsymbol{G}\right)}(-1)^{\boldsymbol{u}\boldsymbol{G}\boldsymbol{y}^{\mathrm{T}}} \right)^{\nu} \label{eq:wef_step_rev1}\\ &= 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{0,1\}^{n_{\scaleto{1}{3pt}}}}\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\boldsymbol{G}\right)}(-1)^{\boldsymbol{u}\boldsymbol{G}\tilde{\boldsymbol{H}}\boldsymbol{y}^{\mathrm{T}}} \right)^{\nu} \label{eq:wef_step5}\\ &= 2^{-n_{\scaleto{1}{3pt}}}\!\sum_{y_1^{n_{\scaleto{1}{3pt}}-k_{\scaleto{1}{3pt}}}}\!\sum_{\boldsymbol{v}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}\!\!\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}\!\!z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\boldsymbol{G}\right)}(-1)^{\boldsymbol{u}\boldsymbol{G}\bar{\boldsymbol{H}}^{\mathrm{T}}\boldsymbol{v}^{\mathrm{T}}}\!\right)^{\nu} \label{eq:wef_step6} \end{align} with $\tilde{\boldsymbol{H}}\triangleq\left[\boldsymbol{H}^{\mathrm{T}},\bar{\boldsymbol{H}}^{\mathrm{T}}\right]$ where $\boldsymbol{H}$ and $\bar{\boldsymbol{H}}$ are the parity-check matrix of $\mathcal{C}_1$ and a complementary matrix such that $\tilde{\boldsymbol{H}}$ is non-singular, respectively, and $\boldsymbol{v}\triangleq y_{n_{\scaleto{1}{3pt}}-k_{\scaleto{1}{3pt}}+1}^{n_{\scaleto{1}{3pt}}}$. Note that \eqref{eq:wef_step2} follows from \eqref{eq:cwef} by noting that $(y_1z,\ldots,y_{n_{\scaleto{1}{3pt}}}z)^{\boldsymbol{x}} = z^{w_{\scaleto{\mathrm{H}}{3pt}}(\boldsymbol{x})}\boldsymbol{y}^{\boldsymbol{x}}$, \eqref{eq:wef_step4} from re-defining the dummy vector $\boldsymbol{y}$, \textcolor{black}{\eqref{eq:wef_step_rev1} from $\boldsymbol{x}=\boldsymbol{u}\boldsymbol{G}$ and performing the summation over $\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}$ instead of $\boldsymbol{x}\in\mathcal{C}_{\scaleto{1}{3pt}}$, \eqref{eq:wef_step5} from the nonsingularity of $\tilde{\boldsymbol{H}}$ and the summation being over all possible $\boldsymbol{y}\in\{0,1\}^{n_{\scaleto{1}{3pt}}}$}, and \eqref{eq:wef_step6} from dividing the outer summation into two parts, namely over $y_1^{n_{\scaleto{1}{3pt}}-k_{\scaleto{1}{3pt}}}\in\{0,1\}^{n_{\scaleto{1}{3pt}}-k_{\scaleto{1}{3pt}}}$ and $\boldsymbol{v}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}$, and the fact that the product $\boldsymbol{G}\boldsymbol{H}^{\mathrm{T}}$ results in the all-zero matrix. Finally, \eqref{eq:theorem_wef} follows from the fact that the outer summation can be removed by multiplying the remaining term by $2^{n_{\scaleto{1}{3pt}}-k_{\scaleto{1}{3pt}}}$ and the fact that the product $\boldsymbol{G}\bar{\boldsymbol{H}}^{\mathrm{T}}$ is non-singular.\footnote{\textcolor{black}{Note that the rows of $\bar{\boldsymbol{H}}^{\mathrm{T}}$ are linearly independent of the rows of $\boldsymbol{H}$ by definition.}}} \end{proof} \textcolor{black}{Thanks to Theorem~\ref{theorem:wef_spc}, one can compute the \ac{WEF} of short and moderate-length \ac{SPC} product codes iteratively, by simply choosing one component code to be a \ac{SPC} product code $\mathcal{C}_1$ and the other one to be a \ac{SPC} code $\mathcal{S}_\nu$. Given the weight enumerator of a product code, upper bounds on the \ac{ML} decoding error probability can be obtained. As an example, a tight bound on the block error probability over the \ac{B-AWGN} channel is provided by Poltyrev's \ac{TSB} \cite{poltyrev94}. Another example of a tight bound on the block error probability of a code based on its weight enumerator is Di's union bound over the \ac{BEC} \cite[Lemma B.2]{di02}. We refer the interested reader to \cite{sason2006performance} for an extensive survey on performance bounds under \ac{ML} decoding.} \textcolor{black}{Next, we provide simulation results for the $3$-dimensional $(125,64)$ \ac{SPC} product code under \ac{ML} decoding implemented over the \ac{BEC} via \ac{SCL} decoding with $L=\infty$. The results are provided in Fig. \ref{fig:ml_125_64_SPC_vs_polar_bec}. As reference, simulation results for a $(125,64)$ punctured polar code~\cite{WR14:polar_punc} are also provided, where the polar code design follows the guidelines of the 5G standard~\cite{BCL21:5g_polar}. The polar code slightly outperforms the considered \ac{SPC} product code. Note that Di's union bound tightly approaches the performance of the \ac{SPC} product code.} \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{./figures/125_64_SPC_document_polar_BEC.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{BLER} vs. $\epsilon_{\mathrm{ch}}$ over the \ac{BEC} for the $(125,64)$ product code under \ac{ML} decoding, implemented via \ac{SCL} decoding with $L=\infty$, compared to a $(125,64)$ punctured polar code.} }\label{fig:ml_125_64_SPC_vs_polar_bec} \end{figure} \textcolor{black}{The same $(125,64)$ \ac{SPC} product code is also simulated over the \ac{B-AWGN} channel under \ac{SCL} decoding with various list sizes. The results are given in Fig. \ref{fig:scl_125_64_SPC}. The \ac{TSB} is also provided, thanks to the weight enumerator analysis.} Remarkably, \textcolor{black}{\ac{SCL}} decoding with $L=4$ is sufficient to operate \textcolor{black}{very close to} the \ac{TSB} and \textcolor{black}{to} outperform \ac{BP} decoding. With $L=8$, the \ac{SCL} decoder tightly \textcolor{black}{approaches} the \ac{ML} lower bound, which is not the case for \ac{BP} decoding. \textcolor{black}{The \ac{RCU}~\cite[Thm.~16]{Polyanskiy10:BOUNDS} and the \ac{MC}~\cite[Thm.~26]{Polyanskiy10:BOUNDS} bounds, are here plotted as reference.} The gap to the \ac{RCU} bound reaches to \textcolor{black}{$1.7$} dB at \textcolor{black}{\ac{BLER}} of $10^{-3}$. \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{./figures/125_64_SPC_document.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{BLER} vs. \ac{SNR} under \ac{SCL} decoding for the $(125,64)$ product code with various list sizes, compared to a BP decoding with $100$ iterations.} }\label{fig:scl_125_64_SPC} \end{figure} \textcolor{black}{The performance of \ac{SPC} product codes is compared to that of the $(125,64)$ polar code in Fig. \ref{fig:scl_125_64_SPC_vs_polar}. When $L=4$ is considered, the performance of polar code tightly matches its \ac{ML} lower bound and outperforms the \ac{SPC} product code by around $0.3$ dB at \ac{BLER} of $10^{-3}$. The gap between their \ac{ML} performance is around $0.25$ dB. Note that the polar code requires a smaller list size to approach its \ac{ML} performance.} \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{./figures/125_64_SPC_document_polar.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{BLER} vs. \ac{SNR} over the \ac{B-AWGN} channel for the $(125,64)$ product code under \ac{SCL} decoding with various list sizes, compared to a $(125,64)$ punctured polar code.} }\label{fig:scl_125_64_SPC_vs_polar} \end{figure} \subsection{Finite-length \textcolor{black}{Performance} Analysis via Average Weight Distribution of Concatenated Ensembles} \label{sec:concatenation} Following \cite{tal15}, \textcolor{black}{\ac{SPC} product codes are concatenated with a high-rate outer code to improve the distance profile, aiming at an improved performance under \ac{SCL} (and \ac{ML}) decoding. At the receiver, an \ac{SCL} decoder with list size $L$ is employed for the inner code.} The outer code is used to \textcolor{black}{test the} $L$ codewords in the final list. Among those satisfying the outer code constraints, the most likely one is chosen as the final decision. \textcolor{black}{Our goal is to analyze the \ac{ML} decoding performance of the concatenated code, since for short and moderate blocklengths close-to-ML performance may be practically attained via \ac{SCL} decoding by choosing a sufficiently large list. To analyze the \ac{ML} decoding performance of such a concatenation, we first \textcolor{black}{derive} the weight enumerator of product codes in concatenation with an outer code. The weight enumerators will then be used to derive well-known tight upper bounds on the \ac{ML} decoding error probability \textcolor{black}{as before}. A reason to analyze such concatenation lies (besides in the expected performance improvement) in the fact that actual schemes employing product codes may make use of an error detection code to protect the product code information message (this is the case, for instance, of the IEEE~802.16 standard \cite{IEEE80216}). One may hence consider sacrificing (part of) the error detection capability introduced by the outer error detection code for a larger coding gain \cite{Coskun19:RM-Product}.} Consider the concatenation of an $(n_{\mathsf i},k_{\mathsf i})$ inner product code $\mathcal{C}_{\mathsf{i}}$ with an $(n_{\mathsf o},k_{\mathsf o})$ high-rate outer code $\mathcal{C}_{\mathsf{o}}$ with $k_{\mathsf i}=n_{\mathsf o}$. The generator matrices of $\mathcal{C}_{\mathsf{i}}$ and $\mathcal{C}_{\mathsf{o}}$ are $\boldsymbol{G}_{\mathsf{i}}$ and $\boldsymbol{G}_{\mathsf{o}}$, respectively. \begin{definition}[Concatenated Ensemble] The (serially) concateneted ensemble $\mathscr{C}\left(\mathcal{C}_{\mathsf{o}},\mathcal{C}_{\mathsf{i}}\right)$ is the set of all codes with generator matrix of the form \[ \boldsymbol{G}=\boldsymbol{G}_{\mathsf{o}}\bm{\Pi}\boldsymbol{G}_{\mathsf{i}} \] where $\bm{\Pi}$ is an $n_{\mathsf o}\times n_{\mathsf o}$ permutation matrix. \end{definition} Assume that the outer code weight enumerator $A^{\mathsf o}_j$ and the input-output weight enumerator of the inner product code $A^{\mathrm{IO},\mathsf i}_{j,w}$ are known. We are interested in the weight enumerator of the concatenated code for a given permutation matrix $\bm{\Pi}$ (e.g., $\bm{\Pi} = \boldsymbol{I}_{n_{\mathsf o}}$), which interleaves the output of the outer encoder. Given an interleaver, this requires the enumeration of all possible input vectors of length $k_{\mathsf o}$, which is not possible in practice. For this reason, the impact of the outer code is \textcolor{black}{typically} analyzed in a concatenated ensemble setting by assuming that the interleaver is distributed uniformly over all possible ${n_\text{out}\choose i}$ permutations\cite{BenMon96}. Then, the average weight enumerator of the ensemble is derived as \begin{equation}\label{eq:average_wef} \bar{A}_w = \sum_{j = 0}^{n_\text{out}} \frac{A_j^{\mathsf o}\cdot A_{j,w}^{\mathrm{IO},\mathsf i}}{{n_{\mathsf o}\choose j}} \end{equation} where $\bar{A}_w$ is the average multiplicity of codewords $\textcolor{black}{\boldsymbol{x}}$ with $w_{\mathrm{H}}(\textcolor{black}{\boldsymbol{x}}) = w$. \textcolor{black}{The computation of \eqref{eq:average_wef} requires the knowledge of the input-output weight enumerator of the inner \ac{SPC} product code. Therefore, we extend the result of Theorem \ref{theorem:wef_spc} to the derivation of the \ac{IOWEF}.} \begin{theorem}\label{theorem:iowef} \textcolor{black}{Let $\mathcal{C}_1$ and $\mathcal{S}_\nu$ be an arbitrary $(n_1,k_1)$ systematic code with a generator matrix $\textcolor{black}{\boldsymbol{G}}$ and a systematic \ac{SPC} code, respectively. Then, the \ac{IOWEF} of the product code $\mathcal{C}$ with component codes $\mathcal{C}_1$ and $\mathcal{S}_\nu$ is} \begin{align} A_{\mathcal{C}}^{\mathrm{IO}}(x,z) \!=\! 2^{-k_{\scaleto{1}{3pt}}}\!\sum_{\boldsymbol{v}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}\!\!&\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}\!\!(-1)^{\boldsymbol{u}\cdot\boldsymbol{v}^\mathrm{T}}x^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\right)}z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\textcolor{black}{\boldsymbol{G}}\right)}\!\right)^{\nu-1}\\ &\qquad\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}(-1)^{\boldsymbol{u}\cdot\boldsymbol{v}^\mathrm{T}}z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\textcolor{black}{\boldsymbol{G}}\right)}\right). \end{align} \end{theorem} \begin{proof} Recall \eqref{eq:comp_wef_prod} and assume, without loss of generality, that the component code generator matrices are of the form $[\boldsymbol{I}_{k_i} | \boldsymbol{P}_i]$. \textcolor{black}{In this case, we set $z_{i,j} = xz$, for $1\leq i\leq k_1$ and $1\leq j\leq k_2 = \nu-1$, and $z_{i,j} = z$, otherwise, to obtain} \textcolor{black}{\begin{align} A_{\mathcal{C}}(x,z) = 2^{-n_{\scaleto{1}{3pt}}}\sum_{\boldsymbol{y}\in\{1,-1\}^{n_{\scaleto{1}{3pt}}}}&\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}}x^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\boldsymbol{u}\right)}z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\textcolor{black}{\boldsymbol{u}\boldsymbol{G}}\right)}\textcolor{black}{\boldsymbol{y}^{\boldsymbol{u}\boldsymbol{G}}} \right)^{\nu-1}\\ &\qquad\left(\sum_{\boldsymbol{u}\in\{0,1\}^{k_{\scaleto{1}{3pt}}}} z^{w_{\scaleto{\mathrm{H}}{3pt}}\left(\textcolor{black}{\boldsymbol{u}\boldsymbol{G}}\right)}\textcolor{black}{\boldsymbol{y}^{\boldsymbol{u}\boldsymbol{G}}}\right) \label{eq:iowef_step3 \end{align} where the result follows by applying the similar steps in the proof of Theorem \ref{theorem:wef_spc}.} \end{proof} \textcolor{black}{Similar to the \ac{WEF}, one can compute the \ac{IOWEF} of short and moderate-length \ac{SPC} product codes iteratively, by choosing one component code to be a \ac{SPC} product code $\mathcal{C}_1$ and the other one to be a \ac{SPC} code $\mathcal{S}_\nu$. Given the average weight enumerator of a concatenated ensemble, upper bounds on the \ac{ML} decoding error probability can be obtained as in Section \ref{sec:wef_SPC_PC}.} Fig. \ref{fig:scl_125_56_SPC} shows the performance of concatenating the $(125,64)$ product code with \textcolor{black}{a $8$-bit} outer \ac{CRC} code with generator polynomial \textcolor{black}{$g(x)=x^8+x^6+x^5+x^4+x^2+x+1$}, where the interleaver between the codes is the trivial one defined by an identity matrix. This concatenation leads to a $(125,56)$ code. Since the code distance properties are improved (observed directly via the \ac{TSB} on the average performance of the code ensemble), the performance improvement under \ac{ML} decoding is expected to be significant. \textcolor{black}{The \ac{CRC} polynomial is selected as the one which provides the best \ac{TSB}, obtained for the average weight enumerator of a concatenated ensemble with the uniform interleaver assumption~\cite{BenMon96}.} The gain achieved by \ac{SCL} decoding is remarkably large, operating below the \ac{TSB}. At a \textcolor{black}{\ac{BLER}} of $10^{-2}$, \ac{SCL} decoding of the concatenated code achieves gains up to $1.25$ dB over the original product code, reaching up to \textcolor{black}{$1.5$} dB at a \textcolor{black}{\ac{BLER}} $\approx 10^{-4}$. The gap to the \ac{RCU} bound is approximately \textcolor{black}{$0.7$} dB at \textcolor{black}{a \ac{BLER}} of \textcolor{black}{$10^{-4}$ and less for higher \acp{BLER}, providing a competitive performance for similar parameters\cite{Coskun18:Survey}. For example, the performance of a $(128,64)$ \own{5G-NR} LDPC code (base graph 2, see \cite{Coskun18:Survey}) is reported. The code has been decoded with the BP algorithm by setting the maximum number of iterations to $100$. The concatenation of the outer CRC code with the inner SPC product code yields a remarkable gain of $\approx 0.6$ dB with respect to the \own{5G-NR} LDPC code (it shall be noted, however, that the concatenated SPC code possesses a slightly lower code rate)}. Note that it is not always possible to attain \textcolor{black}{a} performance close to the \ac{ML} performance of concatenated codes using \ac{BP} decoding\cite{Coskun19:RM-Product,geiselhart2020crcaided}. In that sense, \ac{SCL} decoding provides a low-complexity solution to \textcolor{black}{approach} the \ac{ML} performance of the concatenated \textcolor{black}{\ac{SPC} product code} scheme. \textcolor{black}{As another reference, a (125, 56) CRC-concatenated polar code is constructed by using the $(125,64)$ polar code with an $8$-bit outer \ac{CRC} code optimized using the guidelines of \cite{Yuan19}, which takes into account the exact code concatenation under \ac{SCL} decoding rather than an ensemble performance. The generator polynomial of the CRC code is $g(x)=x^8+x^7+x^6+x^5+1$. The gap between the \ac{ML} performance of two codes is less than $0.5$ dB in the considered regime. A careful optimization of the interleaver of the CRC-concatenated \ac{SPC} product code might provide further gains as for polar codes\cite{RBC18}, but it is not in the scope of this work.} \begin{figure}[t] \begin{center} \includegraphics[width=\columnwidth]{./figures/125_64_bestCRC8_SPC_document.pdf} \end{center} \vspace{-0.5cm} \caption{\textcolor{black}{\ac{BLER} vs. \ac{SNR} over the \ac{B-AWGN} channel for a $(125,64)$ product code concatenated with a $(64,56)$ \ac{CRC} code under \ac{SCL} decoding with various list sizes. The performance is compared to the one of a $(125,56)$ CRC-concatenated polar code with various list sizes, where the generator polynomial of the outer code is optimized for \ac{SCL} decoding\cite{Yuan19}, and the one of the $(128,64)$ \own{5G-NR} LDPC code (base graph 2, see \cite{Coskun18:Survey}) under BP decoding where the maximum number of iterations is set to $100$.} }\label{fig:scl_125_56_SPC} \end{figure} \section{\textcolor{black}{Relations Between Single Parity-Check Product Codes and Multi-Kernel Polar Codes}}\label{sec:spcpc_as_pc} \textcolor{black}{We consider $(n_\ell\times n_\ell)$ kernels $\boldsymbol{\mathsf{K}}_{n_\ell}$, where $n_\ell\geq 2$, $\ell\in[m]$,} of the form \begin{equation} \boldsymbol{\mathsf{K}}_{n_\ell} = \begin{bmatrix} 1 & 0 & \dots & 0 \\ 1 & & & \\ \vdots & & \boldsymbol{I}_{k_\ell} & \\ 1 & & & \end{bmatrix} \label{eq:kernel} \end{equation} \textcolor{black}{with $k_\ell = n_\ell - 1$.} Similar to \eqref{eq:generator_polar}, \textcolor{black}{an $n^{[m]} \times n^{[m]}$ transform matrix $\boldsymbol{\mathsf{G}}^{[m]}$ is obtained, recursively,} as \textcolor{black}{\begin{equation} \boldsymbol{\mathsf{G}}^{[m]} = \left(\boldsymbol{I}_{n^{[m-1]}}\otimes\boldsymbol{\mathsf{K}}_{n_{m}}\right)\boldsymbol{\Pi}_{n^{[m-1]},n_{m}}\left(\boldsymbol{I}_{n_{m}}\otimes\boldsymbol{\mathsf{G}}^{[m-1]}\right) \label{eq:bigGpolar} \end{equation} where $\boldsymbol{G}^{[0]} \triangleq 1$. The proof of the following lemma is given as appendix. \begin{lemma}\label{lemma:polarization} The multi-kernel construction \eqref{eq:bigGpolar}, with a sequence of kernels of the form \eqref{eq:kernel}, polarizes. More formally, the fraction of channels with $I\left(\mathrm{W}^{(i)}_{\boldsymbol{\mathsf{G}}^{[m]}}\right)>1-\delta$ goes to $I\left(\mathrm{W}\right)$ and the fraction of channels with $I\left(\mathrm{W}^{(i)}_{\boldsymbol{\mathsf{G}}^{[m]}}\right)<\delta$ goes to $1-I\left(\mathrm{W}\right)$ for any $\delta\in(0,1)$ as $m\rightarrow\infty$. This holds for any sequence $n_1, n_2,\ldots$ where each $n_i$ satisfies $2\leq n_i<\infty$. \end{lemma}} \textcolor{black}{Note that Lemma \ref{lemma:polarization}, upon proving that the rate of convergence is positive (which can be computed via \cite[Theorem 2]{benammar_land} after fixing the kernels), implies that a multi-kernel polar code based on the kernels of the form \eqref{eq:kernel} achieves capacity for general \ac{BMS} channels. In the following, however, we provide a selection procedure for the frozen bits yielding an \ac{SPC} product code, which does not take into account the quality of the synthesized channels. This hinders the possibility to achieve capacity for the \ac{SPC} product codes under \ac{SC} decoding.} Recall the multibase representation \textcolor{black}{\eqref{eq:multibase}} of a decimal number $i$, denoted by $(i_1i_2\dots i_m)_{n_1n_2\dots n_m}$. Then, \textcolor{black}{the} generator matrix $\textcolor{black}{\boldsymbol{G}^{[m]}}$ is obtained by choosing set $\mathcal{A}_\text{PC}\subset [n]$ of frozen bits as \begin{align} \mathcal{A}_\text{PC} = \textcolor{black}{[n]\setminus\left\{i+1\in[n]: i_j \neq 0, \quad\forall j=1,2,\dots,m \right\}}. \label{eq:frozen_set} \end{align} Note that encoding can be done either by using \eqref{eq:generator_product} as $\boldsymbol{x} = \boldsymbol{u}\textcolor{black}{\boldsymbol{G}^{[m]}}$, or by using \eqref{eq:bigGpolar} as $\boldsymbol{x} = \textcolor{black}{\boldsymbol{w}\boldsymbol{\mathsf{G}}^{[m]}}$ with $\textcolor{black}{w_i} = 0$ for all $i\in\mathcal{A}_\text{PC}$ and the remaining positions are allocated for the information bits as for polar codes (see Section \ref{sec:polar}). In other words, \eqref{eq:bigGpolar} generalizes \eqref{eq:generator_polar} to generate the mother code for multi-kernel polar codes generated by $m$ kernels $\boldsymbol{\mathsf{K}}_{n_{\ell}}$ in dimensions \textcolor{black}{$\ell\in[m]$. Note that \eqref{eq:bigGpolar} recovers \eqref{eq:generator_polar} by setting $n_\ell = 2$ for all $\ell\in[m]$.} \begin{example} Consider \textcolor{black}{the} $(3\times 3)$ kernel\textcolor{black}{s} \[\textcolor{black}{\boldsymbol{\mathsf{K}}_{n_1} = \boldsymbol{\mathsf{K}}_{n_2} =} \begin{bmatrix} 1 & 0 & 0 \\ 1 & 1 & 0 \\ 1 & 0 & 1 \end{bmatrix}.\] We construct $\textcolor{black}{\boldsymbol{\mathsf{G}}^{[2]}}$ by using \eqref{eq:bigGpolar}, i.e., \[\textcolor{black}{\boldsymbol{\mathsf{G}}^{[2]}} = \begin{bmatrix} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ 1 & 1 & 0 & 1 & 1 & 0 & 0 & 0 & 0 \\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 & 0 \\ 1 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 1 & 0 & 1 & 0 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 1 \end{bmatrix}. \] Then, the generator matrix $\textcolor{black}{\boldsymbol{G}^{[2]}}$ is constructed as \[\textcolor{black}{\boldsymbol{G}^{[2]}} = \begin{bmatrix} 1 & 1 & 0 & 1 & 1 & 0 & 0 & 0 & 0 \\ 1 & 1 & 0 & 0 & 0 & 0 & 1 & 1 & 0 \\ 1 & 0 & 1 & 1 & 0 & 1 & 0 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 1 \end{bmatrix}\] by removing the rows, with indices given by \eqref{eq:frozen_set}, i.e., $\mathcal{A}_\text{PC} = \{1,2,3,4,7\}$, \textcolor{black}{as depicted} in Fig. \ref{fig:size9_polar_construction_PC}(a). Equivalently, \textcolor{black}{the} generator matrix $\textcolor{black}{\boldsymbol{G}^{[2]}}$ can be formed by \textcolor{black}{using \eqref{eq:generator_product} after} removing the first rows of the kernels to get \textcolor{black}{the generator} matrices $\boldsymbol{G}_{\textcolor{black}{1}}$ and $\boldsymbol{G}_{\textcolor{black}{2}}$ defining \ac{SPC} \textcolor{black}{component} codes, i.e., \[\boldsymbol{G}_{\textcolor{black}{1}} = \boldsymbol{G}_{\textcolor{black}{2}} = \begin{bmatrix} 1 & 1 & 0 \\ 1 & 0 & 1 \end{bmatrix}.\] \begin{figure} \centering \begin{subfigure}{0.5\textwidth} \includegraphics[width=1\textwidth]{./figures/size9_spc_polar_construction_PC} \vspace{-0.5cm} \caption{} \end{subfigure} \begin{subfigure}{0.5\textwidth} \includegraphics[width=1\textwidth]{./figures/size9_spc_polar_construction_PC2} \vspace{-0.5cm} \caption{} \end{subfigure} \caption{(a) \textcolor{black}{illustrates} how to choose the frozen bits \textcolor{black}{to obtain} a SPC product code, where red edges show those carrying frozen bit values and red variables \textcolor{black}{are set to} $0$. In (b), the frozen bits and the corresponding edges \textcolor{black}{are removed, providing a graphical representation of a} $2$-dimensional SPC product code \textcolor{black}{as in Fig. \ref{fig:transmission_recursive}}.} \label{fig:size9_polar_construction_PC} \end{figure} \label{ex:construction} \end{example}
{'timestamp': '2021-07-27T02:20:05', 'yymm': '2008', 'arxiv_id': '2008.06938', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06938'}
arxiv
\section{Sample Section Title} \label{sec:sample1} Lorem ipsum dolor sit amet, consectetur adipiscing \citep{Fabioetal2013} elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud \citet{Blondeletal2008} exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit \citep{Blondeletal2008,FabricioLiang2013} anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum see appendix~\ref{sec:sample:appendix}. \section{Sample Section Title} \label{sec:sample1} Lorem ipsum dolor sit amet, consectetur adipiscing \citep{Fabioetal2013} elit, sed do eiusmod tempor incididunt ut labore et dolore magna \citet{Blondeletal2008} aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit \citep{Blondeletal2008,FabricioLiang2013} anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum see appendix~\ref{sec:sample:appendix}. \section{Introduction} A pickling line is a continuously-acting line where steel strips processed in a hot-rolling mill are exposed to the removal of iron oxides from their surface. The pickling process is required between hot rolling and any further treatments (e.g. hot deep galvanizing, cold rolling, or annealing) and therefore may become a bottleneck in the production process. Meanwhile, the direct increase in the production speed can negatively affect the quality of the final product, if the mill scale is not properly removed. During the pickling process, steel strips are transported through the baths filled with a concentrated acid solution to remove the mill scale defects formed during the hot-rolling process. Unsuitable conditions of the pickling process (the concentration of the acid solution, the baths temperature, and the line speed \cite{hudson1982effect}) result in incomplete removal of scale from the steel surface, namely under-pickling, and require the re-processing. On the other hand, over-pickling can lead to erosion and has a more sensible effect on steel quality. Therefore, there is a trade-off between high productivity and quality of the steel strips. Most of the research papers done so far try to solve the trade-off in favor of satisfying quality requirements, by finding optimal speed line values for the different combinations of acid concentrations and temperature ranges \cite{colla2012prediction, machon2010flsom} or by controlling the acid concentration in range assured the proper conditions for the pickling reaction \cite{kittisupakorn2009neural, noh2015acid, sohlberg2007control, daosud2005neural}. However, to our knowledge, no one of these publications takes into account the sophisticated design of the pickling line. \begin{figure*}[tb] \centering \includegraphics[width=\linewidth]{schema_nta.jpg} \caption{Scheme of picking line} \label{fig:schema} \end{figure*} While the topology of lines can vary with steel mill, the technological procedure responsible for the continuous operation \cite{simeonov2010acid} of the pickling lines is very similar and affects significantly the control strategy of the line. To make the process continuous, the steel strips are first welded lengthwise at the outlet of the first transport unit (FTU) then fed through a pickling bath (the second transport unit, STU), and finally cut down at the inlet of the third unit (TTU) \cite{tytus1925metal} (Figure \ref{fig:schema}). While the FTU and TTU can either move or stop (to make the welding or cutting process to be possible), the STU has to be always in motion, because the line stoppages lead to steel defects. Therefore, the control strategy for the STU should also cover the logic of continuous operation in conditions when FTU stops for welding and provides less input or TTU stops for cutting and can not let the steel strips out. In the current publication, we deal with the premise that pickling defects are rare and demand in productivity is high. Given this assumption, we propose an approach in which the constraints formed by quality requirements are satisfied by designing the speed constraints, a table where for some strip width/thickness/steel grade combinations the relevant STU speed range is defined, and the entire problem is solved as a pure optimal control problem with some associated constraints. There are two main components of control that can be applied to the current task, the control of strip sequence at the inlet of the pickling line formulated as a scheduling problem \cite{priore2001review} and the control of speed line at every time moment. While the scheduling approach is more frequently used in manufacturing systems, in our case we follow the production requirements and presume that the sequence of steel strips entering the pickling line is predetermined and unchangeable. Finally, when solving the speed line control problem, a decision is made on the speed of the STU, which corresponds to the boundaries from the speed table, takes into account the FTU and the TTU states, and leads to maximum performance over a long time horizon. In such formulation, the task seems to be perfectly fit the range of problems successfully solved with the Reinforcement Learning (RL) framework. The main advantage of RL algorithms comes from the ability to construct many potential scenarios considering different actions applied to the system, to evaluate each of them \cite{sutton2018reinforcement}, and, finally, to choose the one that results in desired maximization/minimization of the objective function. Moreover, they also allow assessing a long-term effect of consequently taken actions. The combination of such properties attracts significant interest to the RL framework in the industry \cite{nian2020review} and other fields (e.g. risk management \cite{chakraborty19}, network traffic control \cite{arel2010reinforcement}, healthcare \cite{gottesman2018evaluating}) where the ability to look far ahead provides great benefits for decision making. Thus, in this article, we report a successful implication of the RL algorithm to the production process on the metallurgical pickling line. We formulate our problem as a continuous optimal speed control task with the maximization of an average STU's speed over the long run as the main objective. \section{Process and problem description} In Figure \ref{fig:schema} the scheme of the pickling line is presented. The movement of a steel strip within two units, the FTU and the TTU is characterized by clear periodicity. That periodicity is determined by the length of a particular strip. All steel strips processed on the pickling line come in a rolled state. As soon as the head of a new strip is welded with the tail of the previous one, the unrolling process starts. The FTU moves evenly and then slows down when the strip length left in the decoiler becomes sufficiently small (that is defined by lines settings). When the unrolling process is finished the welding process starts again, and during it the whole FTU is immovable. Then the process repeats for the next coil. The same is fair for the TTU, where instead of the welding process the cutting process takes place, and instead of residual length in the decoiler, a residual length before strip blades is used. The duration of the welding or cutting stages has some variability but can be predicted with acceptable errors. The continual movement of STU becomes possible due to the presence of two loopers, one between the FTU and the STU, the other one between the STU and the TTU, and a separate operation of every unit. The amount of steel stored in every looper is controlled by the speed difference of the units. The excess speed of the FTU over the STU results in the fact that the amount of steel entering the first looper is higher than the amount of steel exiting it. Thus, the looper grows in volume to the resulting difference. During the welding stage, the excessive amount of steel stored in the looper can be utilized for uninterrupted movement. The opposite situation is for the STU and TTU. When the cutting stage takes place, the amount of steel processed during the stage is stored in the second looper. Then, the excessive amount of steel is reduced in the following stage by applying the speed of the TTU higher than the STU speed. The loopers are limited in capacity (have lower and upper bounds) and the capacity of the second looper is lower than the capacity of the first one. When the amount of steel stored in the first looper approaches the upper bound (or the lower bound for the second looper) the speed of the corresponding unit is forced to the speed of the STU. At the same time, the crossing of the opposite boundary can lead to long downtime. Therefore, we formulate the entire problem as follows: \begin{itemize} \item parameters: $L_f$ - strip length, unrolled in FTU; $L_t$ - strip length, recoiled in TTU; $\upsilon_f$ - speed of FTU; $\upsilon_t$ - speed of TTU, $t_W$ - welding time and $t_C$ - cutting time; \begin{equation} t_f = \frac{L_f}{\upsilon_f} + t_W \quad\text{and}\quad t_t = \frac{L_t}{\upsilon_t} + t_C \end{equation} \item decision variable: $\upsilon_s$ - speed of STU, \begin{equation} \upsilon_s \leq \min (\upsilon_{s, set}^1, \dotsc, \upsilon_{s, set}^n) \end{equation} , where $\upsilon_{s, set}^i$ - the upper-speed boundary for every particular strip defined manually from the speed table, and $n$ - strips, currently in the STU of the pickling line; \item constraints: \begin{equation} V_f^{min} < \sum_{i=1}^{t_f} (\upsilon_{f, i} - \upsilon_{s, i}) \end{equation} \begin{equation} \sum_{i=1}^{t_t} (\upsilon_{f, i} - \upsilon_{s, i}) < V_s^{max} \end{equation} , where $V_f^{min}$ - the boundary for the first looper; $V_s^{max}$ - the boundary for the second looper; \item objective function: \begin{equation} maximize \sum_{i=1}^{n} \upsilon_{s, i}, {} n \to \infty \end{equation} \end{itemize} \section{Solution approach} \begin{figure}[ht] \centering \includegraphics[width=0.5\textwidth]{schema_approach.jpg} \caption{Scheme of solution} \label{fig:approach} \end{figure} \subsection{Scheme of solution} The general scheme of the problem solution is shown in Figure \ref{fig:approach}. There are two principal parts in our approach: the environment reflecting the dynamics of the pickling line and the agent making the decision on the action to be taken. We developed a three-level environment with each level describing some particular elements of the system. The first level represents the steel strips that entered the line. The GANs (Generative Adversarial Network) have been used to simulate the real sequence of processed strips. The second level can be associated with the disturbance introduced by steel strips to the production mechanisms. That disturbance arises mainly from the variance in geometrical parameters of the strips and could be modeled by using the probabilistic approach. Finally, the third level (a digital twin or Kinematic ENV) characterizes the entire dynamic of the line by the principles described in the "Process and Problem Description" part. Methods of mathematical modeling have been exploited to simulate the behavior of separate units and to get a highly interpretable scheme of mutual influences. We also used a two-step agent, consisting of a conservative agent and an RL (reinforcement learning) agent. By the conservative agent (\textsl{C-Agent}), we understand the analytical solution that calculates the speed every second during the production process. This agent uses mathematical modeling and the basics of mechanics to calculate the recommended speed. To build the RL agent, various deep RL algorithms were examined. Hereinafter, we concentrate our attention on two parts of the approach, the development of the GAN algorithm producing the realistic tabular data characterizing the steel strip parameters and the investigation of the RL algorithm enabled to improve the solution suggested by the conservative agent. All the estimates in the article, except for those, in conclusion, were calculated using the Kinematic environment. \subsection{GAN: Input data generation} The training and validation of a reinforcement learning system require a significant amount of input data that was not possible to acquire from real datasets. In our case, the input data represent steel strip characteristics of the metal passing through the pickling line. However, there was available a medium-sized historical dataset only, which could be either augmented or fed to a generative adversarial network (GAN). Since GANs were introduced \cite{goodfellow2014}, their applications initially emerged in the tasks involving synthetic image generation and augmentation \cite{radford2015unsupervised, shangguan2019}. The homogeneous structure of images made them perfect objects for this pioneering approach, but recently an increasing number of researchers have been using GANs to create data of different structures, including time series, audio, video \cite{yoon2019time, donahue2018adversarial, vondrick2016generating}, and tabular data. For instance, GANs were successfully implemented to augment healthcare records \cite{che2017boosting}. Xu at el. used a Tabular GAN to generate tabular data with mixed variable types, using preliminary a Gaussian Mixture model for multi-modal columns and a long-short term memory network (LSTM) as a generator \cite{xu2018synthesizing}, or a Conditional Tabular GAN to model rows of data with discrete and continuous columns \cite{xu2019modeling}. Thus, to produce realistic synthetic data and to avoid limitations on the size of a synthesized dataset, we have chosen to use GANs. For each epoch of the reinforcement learning system training, we required a short sequence of steel strips with certain parameters, thus the task was to produce batches of steel strip characteristics of length 15-20. The realistic sequence of steel strips is crucial in this task because timings of different technological processes vary from strip to strip depending on their parameters and on the combination of parameters of the adjacent pair of strips. Disturbance introduced by Kinematic ENV heavily depends on steel strip parameters. Table~\ref{tab:strips} shows the key parameters of the steel strip. \begin{table*}[ht] \caption{Basic Steel Strip Parameters} \label{tab:strips} \centering \begin{tabular}{p{0.3\textwidth}p{0.6\textwidth}} \hline Parameter&Characteristics\\ \hline Steel grade & Categorical, over 100 unique values, highly imbalanced. Sequential properties are of great importance. \\ Original width & Integer. Sequential properties are of great importance – the difference between consequential strips widths matters.\\ Resulting width & Integer. Depending on the original width that might be adjusted on the pickling line. \\ Thickness & Integer. Sequential properties are of great importance, there are limitations on thickness differences for adjacent strips.\\ Weight & Integer, continuous. \\ Coiling temperature & Float, continuous. \\ Number of strips in resulting coil & Float. Strips may be rearranged to different coils on the pickling line. One strip can be cut into several strips and are coiled separately or 2-3 strips could be coiled together. \\ \hline \end{tabular} \end{table*} The steel grade is a category of steel comprising its chemical and mechanical properties and other parameters that are directly or indirectly conditioned on the steel grade, thus we have chosen to use a CGAN architecture to generate numerical parameters for this task and to use steel grade as a conditioning parameter. Therefore, we design a two-phase approach to model tabular data with sequential properties. \subsubsection{Steel grade generation with RNN} Firstly, we generate a sequence of steel grades using an LSTM (Long short-term memory) recurrent neural network \cite{hochreiter1997long}. We have chosen this architecture because the parameter behaves as a sequence and can be generated using classical sequence generation approaches. Steel strips with the same parameters: grade, width, thickness - are usually organized in batches of different lengths during pickling and are pickled consequently. The size of the batch depends on the steel grade, for rare specialized grades the batches are usually smaller. Moreover, there might be consequential batches of the same steel grade, but with different other parameters. Thus, we add an $"END"$ token to the vocabulary of unique steel grades to denote the end of the batch. In this model called GradeGenerator, we used a single LSTM layer with 512 units, a dropout layer, a dense layer with softmax activation for the final output, and trained for 500 epochs optimizing the cross-entropy loss. A smaller number of hidden units turned out to be insufficient to capture specific patterns. We use the batch size of 256, sequences of length 20, and do not use an Embedding layer as the size of the unique steel grades vocabulary is relatively small. Then we sample novel sequences of steel grades according to the softmax distribution to make the results more diverse. \subsubsection{Conditional generative adversarial net (CGAN) for numeric parameters} After that, we apply a conditional adversarial network algorithm using steel grade from GradeGenerator as an input. The Generative adversarial network consists of two neural networks: a generator $G(x)$ that creates the data and a discriminator $D(x)$ that tries to distinguish generated data from real data. Both are trained simultaneously through a minimax game. The discriminator tries to maximize the objective while the generator tries to minimize it, i.e to fool the discriminator by generating realistic samples. The generator uses the feedback provided by the discriminator to synthesize more and more believable samples. For the CGAN the loss is modified and the distributions of the variables are conditioned on $y$, in our case it is the steel grade $Gr$ resulting in the following objective function: \begin{equation} \begin{aligned} \min_{G} \max_{D} V(D,G) = & \mathbb{E}_{x\sim p_{data}(x)}[log D(x|y)] + \\ & E_{z\sim p_{z}(z)}[log(1 - D(G(z)|y))] \end{aligned} \end{equation} The generator takes as an input the Gaussian noise vector of length $n$ with the probability density function $z = \frac{1}{{\sigma \sqrt {2\pi } }}e^{{{ - \left( {x - \mu } \right)^2 } \mathord{\left/ {\vphantom {{ - \left( {x - \mu } \right)^2 } {2\sigma ^2 }}} \right. \kern-\nulldelimiterspace} {2\sigma ^2 }}}$ with $\mu = 0, \sigma = 1$ along with the embedded steel grade. The dimension of the embedding layer $E(Gr)$ is equal to $n$. The architecture of the generator is the following: \begin{itemize} \item noise = Flatten(z ($\mu = 0, \sigma = 1$) ) \item label = Flatten(Embedding(Steel Grade)) \item product = Multiply(noise, label) \item x1 = LeakyReLu(Dense(product, 256)) \item x2 = LeakyReLu(Dense(x1, 128)) \item x3 = LeakyReLu(Dense(x2, 64)) \item y = Reshape(\\ LeakyReLu(Dense(x3, n*seqlength))) \end{itemize} The discriminator shares the same architecture, with the difference that the last layer is a dense layer with one neuron. We treat the data as if it was a small image, which results in quite a good approximation of sequential properties. The real strip data are standardized before being fed to the discriminator. Then we train either the generator or the discriminator at a time with the weights of the other part frozen, using techniques proven to help achieve more stability in GAN training, for example, label smoothing \cite{salimans2016improved} and training the discriminator on $k$ times as much data as we give to the generator on each epoch \cite{goodfellow2016nips}. We use the Adam optimizer \cite{kingma2014adam} and train a model for 2000 epochs. The results are presented in Figure \ref{fig:rolls}. The distribution of the crucial parameters of the coils is approximated quite well. \begin{figure}[ht] \centering \includegraphics[width=0.5\textwidth]{small_gans_vert.jpg} \caption{Comparison of real and generated strips} \label{fig:rolls} \end{figure} \subsection{RL: Model description and parameters choice} To solve our continuous optimization problem simply, we treat it as a sequence of episodic tasks, with the length of an episode limited by 20 consecutive steel strips passed through the kinematic environment described earlier. Therefore, one can transform the objective function to the following: $maximize \sum_{i=1}^{n} \upsilon_{s, i}$, where $n = \sum_{i=1}^{20} t_{f,i}$. Meaning the general approach widely accepted for the RL framework we define the following settings: Reward function, State, Policy evaluation strategy and Action. We exploit an approach when two agents cooperatively define the finally applied action. The resulted action is obtained as a plain sum of actions evaluated by the agents and is determined as the speed of the STU at every time step. \subsubsection{Reward} Although we are using a two-agent approach, we consider the reward function to be applied only for the second agent (RL-agent). According to the problem description, there should be two main contributors to the reward function: a reward associated with an increase in the values of the objective function and penalties acquired from a violation of constraints. The analytical solution was built to keep the highest possible STU's speed in conditions that no constraints are broken. Therefore, any deviations from such safe behavior are considered to be the contribution of the RL agent and reflected in the reward function. We define the reward function of our RL agent consisting of the following terms: the contribution to the STU's speed with a positive sign, the violation of constraints associated with the death of the agent with a negative sign, and, optionally, the degree of proximity to boundaries of constrains. The term "death" for an agent hereinafter denotes the violation of constraints. \subsubsection{State} The state vector was chosen as follows $$S_i = (V_{f,i}, V_{s,i}, \upsilon_{f,i}, \upsilon_{s,i}, \upsilon_{t,i}, t_{W, pred}, L_{f,i}, L_{t,i})$$, where $t_{W, pred}$ indicates the expected time left to the end of the welding stage (based on the predicted welding time value). \subsubsection{Policy evaluation strategy} We used Deep Q-learning for the evaluation of the most optimal STU's speed regulation strategy. In Q-learning the action-value (or Q-value) is used to estimate the expected sum of the gamma-discounted rewards acquired from taking action $a_i$ in state $s_i$ and yielding reward $r_{i+1}$ and a subsequent transition to state $s_{i+1}$. In terms of the \textit{Bellman equation} it could be rewritten for the immediate reward in the form \cite{sutton2018reinforcement}: \begin{equation} \begin{aligned} Q(s_i, a_i) \gets & Q(s_i, a_i) + \\ & \alpha [r_{i+1} + \gamma \max_{a} {Q(s_{i+1}, a)} - Q(s_i, a_i)] \end{aligned} \end{equation} In Deep Q-learning instead of the scalar Q-value the Q-value function approximation is used with the neural network (NN) as a function approximation technique. Considering the clear periodicity in the technological routine of the FTU and the TTU associated with the repetition of even motion, then uniformly accelerated motion and final immobility, one can redefine the behavior of these units in terms of stages. Therefore, one could distinguish three stages: boost ('0'), slowdown ('2') and welding (cutting) ('3'). Meaning the situation when the speed of the FTU or the TTU is forced to speed of the STU at the amount of steel in the looper approaching a certain boundary, one could add an extra synchronization stage ('1'). Thus, there are sixteen stage combinations. For each combination ($C^k, k=1...16$) we initialized a separate neural network responsible for the Q-value function approximation. Every network takes normalized state values as an input and passes them through the fully-connected network. Every hidden layer of the network is built from neurons with a ReLu activation function and an l1-regularizer. The last linear layer outputs a 1-d vector with Q-values associated with available actions, ranging from 1 to 10. While naturally speed is understood as a continuous quantity, in our case the simplification of it to the discrete variable is explained by the controller's regulation abilities. In addition to the stage combination parameter, we also define the active-time parameter ($T^k, k=1...16$): the k-th stage combination is active for the total time of $T^k$ during the length of one episode (with $\tau$=1...$T^k$). \begin{algorithm}[htb] \caption{Pseudo-code for Q-value function approximation learning} \label{alg:pseudocode} Initialization of kinematic ENV, \textsl{C-Agent}\; Initialization of NN $Q(s, a| \theta)$ for every combination $C^k$\; \For{episode in range(1, N)}{ Receive coil sequence, disturbance parameters\; Receive initial state $s_1$\; \For{t in range(1, T)}{ \If{$C_t^k \neq C_{t-1}^k$}{ Observe state $s_{t,\tau}^k$ and reward $r_{\tau-1}^k$\; Set $z_{\tau-1} = r_{\tau-1}^k + \gamma \max_{a} {Q^k(s_{t,\tau}^k, a_{\tau-1}^k | \theta)}$\; Update weights of NN of this stage combination $C_t^k$ by minimizing the loss: $L(\theta) = \frac{1}{N} \sum_{\tau} {|z_{\tau-1} - Q^k(s_{\tau-1}^k, a_{\tau-1}^k | \theta)|^2}$\; Update step size $\alpha$ to reduce on factor 0.003; Select action $a_{\tau,RL-agent}^k$ according to $\epsilon$-greedy policy from $Q^k(s_{t,\tau}^k, a_{\tau-1}^k | \theta)$\; Select action $a_{\tau,C-agent}^k$\; Receive cumulative action $a_{\tau}^k = a_{\tau,RL-agent}^k + a_{\tau,C-agent}^k$\; } Execute action $a^k$ and observe state $s_{t+1}$\; Update reward $r^k$ until stage combination ends\; \If{constraints were violated}{ receive reward \textbf{break}\;} } } \end{algorithm} Switching between different NN could be described as follows when a new stage combination becomes active the appropriate NN is taken (at time $\tau$) and the Q-value is updated with the reward evaluated from previous steps (at the time ($\tau-1$)) with the same function approximation network. The update for the function approximation as well as a choice of the appropriate action is done only once at the beginning of a new stage combination and is kept until the next stage combination arrives. The pseudo-code for the entire learning procedure is shown in Algorithm~\ref{alg:pseudocode} \begin{table*}[!ht] \caption{Setting's variations for RL-agents} \centering \label{tab:actions} \begin{tabular}{p{0.3\textwidth}p{0.3\textwidth}p{0.3\textwidth}} \hline Parameter & \textsl{P-Coop Agent} & \textsl{F-Coop Agent}\\ \hline The number of NNs layers & 2 (8 | 8) & 3 (32 | 64 | 16) \\ The state vector & $(V_{f,i}, V_{s,i}, \upsilon_{f,i}, \upsilon_{t,i}, t_{W,pred},$ $ L_{f,i}, L_{t,i})$ & $(V_{f,i}, V_{s,i}, t_{W,pred}, L_{f,i}, L_{t,i})$ \\ The reward contributors & (action, constraints violation) & (action, constraints violation, proximity to boundaries of constraints) \\ The reward on stage calculation ($t'$ - stage combination duration) & $\sum_{i=1}^{t'} r_i$ & $\frac{1}{t'} \sum_{i=1}^{t'} r_i$\\ Action from agent & [0, 9] & [-5, 5] \\ Frequency & Every stage combination, except where welding or cutting stage is involved & Every stage combination, plus every 30 sec. during combination time \\ \hline \end{tabular} \end{table*} \subsubsection{Action, cooperation strategy} Next, we introduce two RL agents with several different key points in respect to their interaction with the conservative agent, while the architecture of the solution stays the same. We explore the behavior of two RL agents since they represent a different approach to the final solution. On the one hand, we consider a fully cooperative agent (\textsl{F-Coop Agent}), when the decision on the action applied to the system is assessed by both agents at every change of the stage combination. On the other hand, we describe a more conservative but more industry-tolerated agent (\textsl{P-Coop Agent}), where the cooperative decision is taken for all stage combinations except those where the welding or cutting stage is involved. That is done because the duration of these stages has high variance and any lapses in logic may result in continuous downtime of the pickling line. The variations in the earlier introduced solution done for every agent are shown in Table~\ref{tab:actions}. The modified parameters are the number of layers in NNs responsive for the Q-value approximation, the composition of the state vector, the reward function evaluation strategy, the range of available actions, and the frequency of actions selection. \section{Results and Discussion} The agents were firstly trained at 800 episodes with generated initial conditions (IC) and $\epsilon$-greedy policy. Then $\epsilon$ was forced to zero and the training was continued to the next 200 episodes with the IC taken from the historical data. All the IC and states were precomputed to ensure the re-productivity and identity of the starting condition for different agents. For generated IC the pipeline shown in Figure \ref{fig:approach} was used. Below, the results obtained at the last 100 episodes with historical IC are discussed. Above we have determined the objective function of our problem as a sum of the STU speeds obtained at every time step during the episode. With the limitation of the episode to the production time of 20 consecutive steel stripes one could redefine the objective function as an average STU speed per episode. In Figure \ref{fig:objective} the results for the original objective function as well as for the modified one (average speed) are shown. Here and further we distinguish the \textsl{C-Agent} applied stand-alone as a baseline solution to compare the gain in productivity raised from the implication of the RL-approach and the \textsl{C-Agent per stage} as an agent that contributes to the decision made by the RL-agent. The \textsl{C-Agent}, as a baseline solution, acts every second, while the RL agents are more restricted in the acting frequency (see Table~\ref{tab:actions}). \begin{figure*}[ht] \centering \includegraphics[width=\textwidth]{sum_speeds2.jpg} \caption{Objective function for \textsl{F-Coop Agent}, \textsl{P-Coop Agent}, and \textsl{C-Agent} agents. A) Average STU speed per episode; B) Sum of STU speed during the episode. Values shown in boxes correspond to median values of distributions.} \label{fig:objective} \end{figure*} As it is seen from Figure \ref{fig:objective} the decision on which the agent shows the best strategy depends on the approach taken for the objective function. The \textsl{F-Coop Agent} shows the best performance if an average speed is considered as a decision function and significantly loses when the sum of speed per episode is assessed. Such behavior could be explained by the rate of agents death. The early death of the agent results in a shortening of the episode length, while its effect on the average speed is not obvious and even may increase the average speed value. \begin{table*}[ht] \caption{Amount of deaths for different agents} \centering \label{tab:death} \begin{tabular}{l p{0.018\textwidth} p{0.018\textwidth} p{0.018\textwidth} p{0.018\textwidth} p{0.02\textwidth} p{0.018\textwidth} p{0.018\textwidth} p{0.018\textwidth} p{0.018\textwidth}} \hline Agents & \multicolumn{9}{c}{Stage combinations}\\ & '01' & '03' & '10' & '13' & '23' & '30' & '31' & '32' & '33'\\ \hline \textsl{F-Coop Agent} & 5 & 3 & 1 & 6 & 0 & 3 & 2 & 2 & 22 \\ \textsl{P-Coop Agent} & 0 & 1 & 1 & 2 & 1 & 2 & 1 & 2 & 15 \\ \textsl{C-Agent} & 0 & 1 & 1 & 2 & 1 & 2 & 2 & 2 & 15 \\ \hline \multicolumn{10}{c}{Stage combinations: 'stage in FTU' + 'stage in TTU'} \end{tabular} \end{table*} \begin{figure*}[htb] \centering \includegraphics[width=\linewidth]{speeds_by_stage.jpg} \caption{The average STU speed over different stage combinations. A) \textsl{F-Coop Agent} vs. \textsl{C-Agent per stage}; B) \textsl{P-Coop Agent} vs. \textsl{C-Agent per stage}; C) \textsl{F-Coop Agent} and \textsl{P-Coop Agent} vs. \textsl{C-Agent}.} \label{fig:speed_by_stage} \end{figure*} In Table~\ref{tab:death} the amount of agents deaths is presented with the differentiation for the stage combination when the death happened. Logically, most of the deaths occurred at the stage combinations when either welding or cutting stage('3') took place. These stages possess a high variability in the duration time and while this time could be predicted with some errors the agents hardly adapted to such variations. Moreover, some deaths could be predetermined by starting conditions, when the initiation took place at a stage combination with welding or cutting stage involved, death could be expected with a high probability. Nevertheless, the comparison of the excessive death rate of the RL-agents (Fully Cooperative and Partly Cooperative) over the \textsl{C-Agent} (27\% death rate) shows a significant growth of deaths rate for the \textsl{F-Coop Agent} (43\% death rate) over the \textsl{P-Coop Agent} (26\% death rate). These data also confirm the assumption done from the objective function consideration, that lower values of the speed's sum for the \textsl{F-Coop Agent} as well as for the \textsl{C-Agent} could be attributed to a higher death rate. \begin{figure*}[ht] \centering \includegraphics[width=\linewidth]{history_compare.jpg} \caption{Average STU speed over different stage combinations, the factual data collected before (2019 year) and after (2020 year) the implementation of the suggested approach. Data were collected according to the logic described in the manuscript, 100 runs of 20 consecutive steel stripes are used as input data for the plot.} \label{fig:history} \end{figure*} To clarify the reasons for the excessive death rate the comparison of the speed taken by the agents with the speed contributed by the \textsl{C-Agent per stage} is done for every stage combination (Figure \ref{fig:speed_by_stage}). Presented data is obtained as follows, the average STU speed over different stage combinations per episode is calculated, then data from all 100 episodes is aggregated; therefore, one box at the plot represents the distribution of the average STU speed for a given stage combination at 100 separate runs. Since we know that most of the death is associated with having-'3' combinations we could take a more close look at them. According to the initial descriptions of the agents, the \textsl{P-Coop Agent} is restricted at having-'3' stages by the decision made by the \textsl{C-Agent per stage}. Therefore, there is only a minor deviation, less than 3.5\%, of the speed displayed by the agent over the basic decision of the \textsl{C-Agent per stage} (Figure \ref{fig:speed_by_stage} (B)). Meanwhile, the \textsl{F-Coop Agent} could act with positive or negative additive over the base decision of the \textsl{C-Agent per stage}. As it is shown in Figure \ref{fig:speed_by_stage} (A) the final action taken by the \textsl{F-Coop Agent} in having-'3' stages exceeds the speed suggested by the \textsl{C-Agent per stage} in most of the cases. Thus, from 7 having-'3' stages in 5 of them, we detect a surplus, and in 3 of them, the surplus is over 15\% of the basic decision of the \textsl{C-Agent per stage}. Such speed advantage of the \textsl{F-Coop Agent} over the \textsl{C-Agent per stage} despite of the high death rate of the first one could be explained by two reasons. The first reason is the more risky behavior of the \textsl{F-Coop Agent} agent compared to the \textsl{C-Agent per stage}. There is an emergency system that forces the speed of the STU to decrease when the system is approaching a constraints violation. That emergency braking system was originally built for the \textsl{C-Agent} to hedge against uncertainty arising from errors in predicting the welding/cutting times. However, the \textsl{F-Coop Agent} exploits it to set high-speed values at the beginning of stage combination and at the end of the stage combination to go at the lowest possible speed, forced by the emergency braking system. We find confirmation of that behavior by analyzing the actions of the agent. However, the aforementioned errors in predicting the welding/cutting time also occur for the \textsl{F-Coop Agent}, apparently causing additional deaths. The second reason could be that the values of the reward function are chosen insufficiently well: if the penalties values are too small compared to the reward values, then the agent will set high-speed values for the stage combination. However, in our case, the penalty was more than two orders of magnitude higher than the reward, so we believe that the first reason (i.e. risky behavior) is more likely to explain the speed advantage of the \textsl{F-Coop Agent}. \begin{table*}[ht] \caption{Speed excess of RL-agents in percent over the conservative agents} \centering \label{tab:surplus} \begin{tabular}{l p{0.01\textwidth} p{0.01\textwidth} p{0.01\textwidth} p{0.01\textwidth} p{0.01\textwidth}} \hline Agents & \multicolumn{5}{c}{Stage combinations}\\ & '02' & '12' & '20' & '21' & '22'\\ \hline \textsl{F-Coop Agent} vs. \textsl{C-Agent per stage} & 23 & 17 & 16 & 30 & 36\\ \textsl{F-Coop Agent} vs. \textsl{C-Agent} & 14 & 17 & 6 & 31 & 18\\ \textsl{P-Coop Agent} vs. \textsl{C-Agent per stage} & 7 & 26 & 12 & 27 & 35\\ \textsl{P-Coop Agent} vs. \textsl{C-Agent} & 1 & 21 & 6 & 12 & 25\\ \hline \end{tabular} \end{table*} Besides the having-'3' stages, the excess in the speed of the agents over the speed suggested by the \textsl{C-Agent per stage} occurred also for having-'2' stages. In Table~\ref{tab:surplus} the surplus as the percentage of the base agent speed is calculated. Both agents, the \textsl{F-Coop Agent}, and the \textsl{P-Coop Agent} show identical behavior that could be attributed to the potentially positive effect of the RL approach. In Figure \ref{fig:speed_by_stage} (C) the final results of the comparison of the speeds from the \textsl{F-Coop Agent}, the \textsl{P-Coop Agent}, and the \textsl{C-Agent} are presented. The same tendency for having-'2' stages is preserved here, we detect a distinct excess of the RL-agents speed over the conservative \textsl{C-Agent}, although it is less than in the case of the \textsl{C-Agent per stage} (Table~\ref{tab:surplus}). Therefore, we could consider it as the main effect of the application of the RL agents to the current problem. From all of the above we could conclude that while the \textsl{F-Coop Agent} shows sometimes better STU speed values than the \textsl{P-Coop Agent} and could be considered as a more flexible agent, its risky decisions are responsible for a higher death rate and therefore for a lower value of the objective function. At the same time, the more conservative \textsl{P-Coop Agent} allows the increase in speed of the STU only in a safe condition and thereby results in higher productivity. \section{Conclusions} In this work, we have proposed a multi-level approach addressed to the speed line control problem on a metallurgical pickling line. The main objective of STU's speed regulation is to maximize the productivity of the pickling line, on the one hand, and, on the other hand, to provide the conditions when all quality requirements for the processed stripes are met. At the first level of our approach, the combination of LSTM and CGAN has been exploited to generate the realistic input data and thereby overwhelm the deficiency in original data necessary to solve the problem. Then several steps have been done, that are only partially described in the manuscript, such as the development of a C-agent based on the analytical solution of the problem and the kinematic environment simulating the real processes on the pickling line. Finally, at the third level, the complete architecture of the Reinforcement Learning system has been built and trained. The entire approach with the \textsl{P-Coop Agent} has been successfully applied at the Cherepovets Steel Mill and has allowed to increase the productivity of the pickling line by more than 6.5\% and to significantly improve line automation processes. In Figure \ref{fig:history} the comparison of the average STU speed over different stage combinations before and after the implementation of the entire approach is presented. Moreover, an additional quality check of the processed strips was done as well, which did not show a statistically significant difference in the number of over- and under-pickling defects before and after the solution deployment.The whole approach was released in two steps: firstly a base C-Agent (5\% productivity increase) and then the RL-Agent (1.5\% productivity increase). These numbers correspond to the factual increase in productivity of the pickling line in 2020. We used a technological stack including Kubernetes, Docker, Kafka, and OPC UA. All modelling was performed in Python. Later, the approach has been partially extended to one more unit at the Cherepovets Steel Mill. The Kinematic ENV has also been successfully used to test hypotheses regarding the productivity of the pickling line and has the potential to be used for scheduling problems. \section*{Acknowledgment} The authors wish to thank the Flat-Rolled Products Subdivision at the Cherepovets Steel Mill and especially Andrei Fedotov and Alexandr Ruban for valuable knowledge and assistance during the project. \bibliographystyle{elsarticle-num-names}
{'timestamp': '2022-04-05T02:11:48', 'yymm': '2008', 'arxiv_id': '2008.06933', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06933'}
arxiv
\section{Introduction} Since early attempts that pretrain a backbone model \cite{Krizhevsky_Sutskever_Hinton_2012, Simonyan_Zisserman_2015, He_Zhang_Ren_Sun_2016} on large-scale dataset \cite{Deng_Dong_Socher_Li_Li_Li_2009} and then transfer the knowledge to numerous computer vision tasks, pretraining has become a hallmark of the success of deep learning. More recently, the volume of transformer-based and Bert-style pretraining models \cite{Devlin_Chang_Lee_Toutanova_2019,Song_Tan_Qin_Lu_Liu_2019,Dong_Yang_Wang_Wei_Liu_Wang_Gao_Zhou_Hon_2019,Conneau_Lample_2019,Liu_Ott_Goyal_Du_Joshi_Chen_Levy_Lewis_Zettlemoyer_Stoyanov_2019} has grown tremendously in the research field of natural language processing and has achieved state-of-the-art performance in various NLP tasks. Likewise, the success of Bert-style pretraining techniques has been transferred to the research field of the intersection of vision and language \cite{Lu_Batra_Parikh_Lee_2019,Li_Yatskar_Yin_Hsieh_Chang_2019,Su_Zhu_Cao_Li_Lu_Wei_Dai_2020,Sun_Myers_Vondrick_Murphy_Schmid_2019,Sun_Baradel_Murphy_Schmid_2019}. \begin{figure}[!t] \begin{center} \includegraphics[width=0.9\columnwidth]{./figures/FirstPage.pdf} \caption{ An illustration of the transition from traditional association-based learning to causal intervention-based learning. The critical difference is that the intervention mitigates the spurious correlation by blocking the back-door path $\protect Z \rightarrow X$ and thus controlling the condition $\protect X$. } \label{fig:first} \end{center} \vspace{-0.4cm} \end{figure} \begin{figure*}[t] \begin{center} \includegraphics[width=0.85\textwidth]{./figures/Dox_Combined.pdf} \caption{ The conditional probabilities of a token Y (visual object or language word) given another token X (from the other modality) before intervention (\textit{i}.\textit{e}., P(Y|X), colored in red) and after intervention (\textit{i}.\textit{e}., P(Y|do(X), colored in blue). } \vspace{-0.2cm} \label{fig:condi} \end{center} \end{figure*} Despite the significant progress that recent methods have made over the initiative work ViLBert \cite{Lu_Batra_Parikh_Lee_2019}, part of their success can be traced back to the introduction of \textit{in-domain} pretraining datasets besides the Conceptual Caption \cite{Sharma_Ding_Goodman_Soricut_2018} dataset. By \textit{in-domain}, we refer to those datasets used in both pretraining and downstream tasks, such as MSCOCO \cite{Lin_Maire_Belongie_Hays_Perona_Ramanan_Dollr_Zitnick_2014}, and Visual Genome \cite{Krishna_Zhu_Groth_Johnson_Hata_Kravitz_Chen_Kalantidis_Li_Shamma_et_2017}. However, out-of-domain pretraining, \textit{i}.\textit{e}., pretraining models on \textit{out-of-domain} datasets and transferring the learned knowledge into downstream tasks with \textbf{unkown} data distributions, can be an essential research topic. In this paper, we focus on out-of-domain pretraining and learning generic representations as the ViLBert does. A fundamental requirement for out-of-domain transfer learning is to mitigate the biases from the pretraining data \cite{Wang_Huang_Zhang_Sun_2020}, which may be useful for the in-domain testing but harmful for out-of-domain testing \cite{Kuang_Cui_Athey_Xiong_Li_2018} due to the \textit{spurious correlation} \cite{Pearl_Glymour_Jewell_2016}. To verify such existence of the correlation biases, we follow \cite{Wang_Huang_Zhang_Sun_2020} to conduct a toy experiment on Conceptual Caption dataset. We observe that the conditional probability of \texttt{shirt} (visual object) given the \texttt{instrument} (language word) is large, \textit{i}.\textit{e}., $p(\textrm{shirt}|\textrm{instrument}) = 5.98\%$, but there are actually no robust relationships between them. Most previous works just blame this for the biased data collection without further justification. However, this is not reasonable since we human ourselves are just living in a biased nature. In our methodology, we draw inspiration from the causal inference \cite{kuang2020causal} and borrow the idea of the backdoor adjustment (also known as covariate adjustment or statistical adjustment) \cite{Wang_Huang_Zhang_Sun_2020, neuberg2003causality,angrist2008mostly} to mitigate these biases. As shown in Figure \ref{fig:first}, the traditional \textit{association-based} learning fashion may lead to the spurious correlation between two tokens (visual objects or language words) by a common cause, \textit{i}.\textit{e}., the confounder. By introducing backdoor adjustment (deconfounding), the original conditional probability of $p(\textrm{shirt}|\textrm{instrument})$ can be adjusted to $3.10\%$ (nearly half) with a \textbf{do} operator. The essence of deconfounding is to control the condition (\texttt{instrument}) from being affected by other potential confounders when assessing the effect on the outcome (\texttt{shirt}) given the condition, \textit{i}.\textit{e}., \textbf{intervention}. In this way, the pure \textit{association}-based pretraining becomes to the causal \textit{intervention}-based pretraining. We note that our goal is not performing theoretically causal inference but learning generic and de-biased visio-linguistic representations that can well generalize to downstream tasks with unknown data distributions. We are particularly targeting at the Bert-style pretraining models and the context-based proxy tasks for supervision, such as masked language/object modeling (MLM/MOM). Context-based proxy tasks solely care about association, \textit{i}.\textit{e}., what co-occur with the anchor token without considering whether there are spurious correlations (\textit{e}.\textit{g}., \texttt{shirt} cannot cause \texttt{instrument}, and vice versa) or not. More formally, masked token modeling, abbreviated as MTM, models the conditional probability $P(Y|X)$ as the distribution of $Y$ when observing $X$. $Y$ is the masked token and $X$ denotes the context information. The spurious correlation occurs when $X$ and $Y$ are confounded by a common cause $Z$, as depicted in Figure \ref{fig:first}. Our goal is to model the interventional operation $P(Y|do(X))$, meaning the distribution of $Y$ when controlling $X$ to mitigate the correlation bias as we introduced before. Real-world cases concerning the conditional probabilities and the corresponding intervention results from the Conceptual Captions dataset can be found in Figure \ref{fig:condi}. In this paper, we propose several intervention-based BERT architectures to help learn deconfouned visio-linguistic representations. We name this kind of architectures as \textbf{DeVLBert}, which refers to \textit{\textbf{De}confounded \textbf{V}isio-\textbf{L}inguisitic \textbf{Bert}}. DeVLBert is designed as model-agnostic and can be easily encapsulated into any other Bert-style models. We conduct in-depth experiments to discuss the performance of the proposed DeVLBert architectures. Pretraining is performed on the Conceptual Caption dataset which most downstream tasks are not built on, \textit{i}.\textit{e}., out-of-domain dataset. We evaluate the effects of these architectures on three downstream cross-modal tasks, including text-to-image retrieval \cite{Wang_Li_Lazebnik_2016}, zero-shot text-to-image retrieval, and visual question answering \cite{Antol_Agrawal_Lu_Mitchell_Batra_Zitnick_Parikh_2015}. We also conduct case studies to evaluate DeVLBert from the human perspective, and demonstrate that mitigating dataset biases boosts the generalization ability. The main contributions of our work are summarized as follows: \begin{itemize} \item We investigate the problem of out-of-domain pretraining, where pre-trained models are transferred to downstream tasks with unknown data distributions. \item We propose the novel DeVLBert framework designed for the Bert-style pretraining architectures with causal intervention to mitigate the spurious correlations caused by the context-based proxy tasks. \item We devise four implementations of the DeVLBert framework \footnote{Code will be released at \url{https://github.com/shengyuzhang/DeVLBert}} and discuss the empirical performance on several downstream tasks. The advantages of the DeVLBert are demonstrated by quantitative experiments, ablation studies, and case studies. \end{itemize} \section{Related Works} \subsection{Visio-linguistic Pretraining} Visio-linguistic (cross-modal) pretraining is a nascent research area that attracts considerable interests in recent years due to their strong ability of knowledge transfer. Existing works \cite{Li_Yatskar_Yin_Hsieh_Chang_2019,Lu_Batra_Parikh_Lee_2019,Su_Zhu_Cao_Li_Lu_Wei_Dai_2020,Chen_Li_Yu_Kholy_Ahmed_Gan_Cheng_Liu_2019,Li_Duan_Fang_Jiang_Zhou_2019,Tan_Bansal_2019} are mainly based on the Bert framework, including single-stream models and two-stream models. Besides the model structure, these methods differ mainly in the pretraining datasets and proxy tasks. Considerable methods incorporate in-domain datasets for pretraining, such as MSCOCO \cite{Lin_Maire_Belongie_Hays_Perona_Ramanan_Dollr_Zitnick_2014} and Visual Genome \cite{Krishna_Zhu_Groth_Johnson_Hata_Kravitz_Chen_Kalantidis_Li_Shamma_et_2017}. , which means the datasets are shared in the processes of both pretraining and downstream task training. In this paper, we investigate the particular out-of-domain pretraining problem, which can be a more general setting in the real-world. \subsection{Causality in Vision \& Language} It is of increasing research interests in computer vision that attempts to borrow useful analysis tools from causality. Typical works are concerning object tracking \cite{Lebeda_Hadfield_Bowden_2015,Xu_Qin_Liu_Xie_Zhu_2018}, interpretable Learning \cite{Kim_Canny_2017}, image classification \cite{Chalupka_Perona_Eberhardt_2015,Lopez-Paz_Nishihara_Chintala_Schlkopf_Bottou_2017}, and image generation \cite{Kocaoglu_Snyder_Dimakis_Vishwanath_2018,Bau_Zhu_Strobelt_Zhou_Tenenbaum_Freeman_Torralba_2019}. More recently, Wang \textit{et al}. \cite{Wang_Huang_Zhang_Sun_2020} proposes the VC R-CNN framework for visual representation learning. They employ the causal intervention to deal with spurious correlation within datasets for visual common sense learning. However, VC R-CNN solely concerns intervention for visual domain. Alleviating the spurious correlations between vision and language in visio-linguistic pretraining can be also necessary, especially for cross-modal downstream tasks. There are also considerable works that explore causality in natural language processing, varying among relation identification \cite{Ning_Feng_Wu_Roth_2018}, text classification \cite{Wood-Doughty_Shpitser_Dredze_2018}, and question answering \cite{Sharp_Surdeanu_Jansen_Clark_Hammond_2016}. More recently, some causality-related techniques also emerge in the research field of cross-modality. For example, visual dialogue \cite{Qi_Niu_Huang_Zhang_2019}, image caption \cite{Yang_Zhang_Cai_2020}, scene graph generation \cite{Tang_Niu_Huang_Shi_Zhang_2020} and VQA \cite{niu2020counterfactual}. Different from these works, DeVLBert investigates generic representation learning. \section{Data Collection} \section{Visio-Linguistic Bert} \subsection{Bidirectional Transformer} \label{sec:BERT} We choose Bidirectional Transformer (Bert) as our backbone structure, which can be the main-stream pretraining architecture for both natural language pretraining and visio-linguistic pretraining. For brevity, we take natural language pretraining as an example to illustrate the Bert structure. Given a language sequence $ S = \{ w_t \}_{t=1,\dots,N_w}$, Bert is pretrained to produce the contextualized word representations $ \mathbf{S} = \{ \mathbf{w}_t \}_{t=1,\dots,N_w} $. We note that the first token is often a pre-defined "[CLS]" and the learned representation for this token denotes the global representation of the whole sequence. Bert is composed of $N_l$ Transformer layers where each of the layers will output a feature sequence $ \mathbf{S}^l = \{ \mathbf{w}^l_t \}_{t=1,\dots,N_w} $. We view the feature sequence of the last layer as the final pretrained representations, \textit{i}.\textit{e}., $\mathbf{w}_t = \mathbf{w}^{N_l}_t$. Each Transformer layer consists of a multi-head self attention module and a feed-forward module. Formally, such a process can be formulated as: \begin{align} \mathbf{w}^l &= \textrm{MultiHeadAttention}(\mathbf{w}^{l-1}), \\ \tilde{\mathbf{w}}^l &= \textrm{LayerNorm}(\mathbf{w}^{l-1} + \mathbf{w}^l), \\ \hat{\mathbf{w}}^l &= \textrm{FeedForward}(\tilde{\mathbf{w}}^l), \\ \mathbf{w}^l &= \textrm{LayerNorm}(\tilde{\mathbf{w}}^l + \hat{\mathbf{w}}^l). \end{align} Each self attention head connect all pairs of input and output positions \cite{Vaswani_Shazeer_Parmar_Uszkoreit_Jones_Gomez_Kaiser_Polosukhin_2017}: \begin{align} \textrm{ SelfAttention }(\mathbf{S})=\operatorname{softmax}\left(\frac{Q(\mathbf{S}) K(\mathbf{S})^{T}}{\sqrt{D_{w}}}\right) V(\mathbf{S}), \end{align} while $Q$ and $K$ are learnable query transformation and key transformation to compute the attention weights. $V$ is the learnable linear transformation to obtain the value context. $D_{w}$ is the feature dimension of keys, values, and queries. This design yields a global correlation, \textit{i}.\textit{e}., the final representation of each word token will be correlated with all other words. Since this modeling schema has no sense of word order (in the sequence) unlike RNNs, it is necessary add the position signals onto each word embedding. There are some techniques doing this, such as position embedding \cite{Gehring_Auli_Grangier_Yarats_Dauphin_2017} and position encoding \cite{Vaswani_Shazeer_Parmar_Uszkoreit_Jones_Gomez_Kaiser_Polosukhin_2017}, and we follow the position embedding for simplicity. For the $t$th word token, the initial representation can be $\mathbf{w}_t^0 = \mathbf{w}_t^e + p_t$, where $\mathbf{w}_t^e$ denotes the word representation taken from the embedding layer and $p_t$ denotes the embedding for the position index $t$. This structure can be easily transferred to the visual domain if the visual words are reasonably defined. A simple yet effective approach is to view the sub-regions of interest as visual words. More concretely, object detectors, such as Faster-RCNN \cite{Ren_He_Girshick_Sun_2015}, will be used to extract object bounding boxes and object feature maps. The original object representations $\mathbf{O}^e = \{ \mathbf{o}^e_i \}_{i=1,\dots,N_v}$ are obtained by global average pooling over the object feature maps. Similar to the language pretraining, we add a global representation $\mathbf{o}^e_{[\textrm{G}]} = 1/N_v \sum_{i=1}^{N_v}\mathbf{o}^e_i$ at the beginning of the sequence. To be aware of the position signals of objects, we encode the information within bounding boxes to obtain position encodings. Concretely, each bounding box can be represented as a 5-d vector, including the normalized top-left coordinates, the normalized bottom-right coordinates, and the scaling factor. We note that for the global representation, the bounding box refers to that of the entire image. The position encoding vector of the same dimension as the object representation is then obtained by a feed-forward network. \subsection{Two-stream Visio-Linguistic Modeling} Existing Bert-like visio-linguistic pretraining methods can be roughly categorized into single-stream architectures and two-stream architectures. We are following the two-stream architectures \cite{Lu_Batra_Parikh_Lee_2019,Su_Zhu_Cao_Li_Lu_Wei_Dai_2020,Tan_Bansal_2019} since they keep the independence of each modality as well as modeling the interaction across different modalities. The only difference between the visio-linguistic Transformer layer and the modality-specific Transformer layer lies in the queries. Formally, the attention head in visio-linguistic Transformer layer for the language side can be formulated as: \begin{align} \textrm{ SelfAttention }(\mathbf{S}, \mathbf{O})=\operatorname{softmax}\left(\frac{Q(\mathbf{S}) K(\mathbf{O})^{T}}{\sqrt{D_{w}}}\right) V(\mathbf{O}), \end{align} Intuitively, this process is designed to borrow language-related information (language features $\textbf{S}$ as queries) from the visual features ($\textbf{O}$ as keys and values). Likewise, for the visual side, we have: \begin{align} \textrm{ SelfAttention }(\mathbf{O}, \mathbf{S})=\operatorname{softmax}\left(\frac{Q(\mathbf{O}) K(\mathbf{S})^{T}}{\sqrt{D_{o}}}\right) V(\mathbf{S}). \end{align} where $D_{o}$ denotes the feature dimension of visual queries. By combining the visio-linguistic Transformer layer and the modality-specific Transformer layer and further stacking the combined layers, we obtain the main structure of two-stream visio-linguistic Bert. \begin{figure*}[t] \begin{center} \includegraphics[width=0.8\textwidth]{./figures/Implementations.pdf} \caption{ A vivid illustration of four intervention formulations for Bert-style training. Deciding the forms of X and Y in Bert is essential for further intervention-based context prediction. Design A\&C require twice inference. Design A\&B replace the frequently used masked-token-modeling (MTM) objective while Design C\&D are independent of the MTM. } \vspace{-0.2cm} \label{fig:imple} \end{center} \end{figure*} \subsection{Pretraining Proxy Tasks} Masked language modeling (MLM) and masked object modeling (MOM) are popular context-based proxy tasks for language and vision, respectively. We group MLM and MOM into masked token modeling (MTM) in this paper for brevity. As the name (masked) implies, MTM often randomly masks tokens in a sequence by a given probability and replace them with special tokens, such as "[MASK]". Then, Bert is required to make predictions to recover these tokens. Typical recovering strategies include token vocabulary classification and feature regression. For MLM, we follow the standard practice in original BERT\cite{Devlin_Chang_Lee_Toutanova_2019}. For MOM, 15\% proportion of the objects will be masked ready for recovering. Since no objects are masked during testing, which yields a setting gap between training and testing, we replace 10\% of the masked objects with their original representations. We note that these objects are still required to be \textit{recovered}, which are different from the initially unmasked objects. By recovering, we mean the object classification with soft labels, which come from the object detectors. Visio-linguistic alignment follows the original design of the next sentence prediction objective in natural language pretraining. By the probability of 50\%, the originally paired sentence will be replaced by a random sampled unpaired sentence. The Bert model is required to predict whether the language sequence and the objects sequence are aligned. We employ a simple feed-forward neural network to compute the alignment score based on the global representation of words/objects sequence, \textit{i}.\textit{e}., $\mathbf{w}_{[CLS]}$ and $\mathbf{o}_{[G]}$, where $\mathbf{o}_{[G]}$ denotes the final representation of the special global object $o_{[G]}$. \section{Deconfounded Vsio-Linguistic Bert} \subsection{Bert in the causal view} As illustrated in section \ref{sec:BERT}, the Transformer layer connects each output token representation with all input token representations. We denote the representation of one output token as $Y$ and the representations of all other tokens as $X$. Bert models the function of $P(Y|X)$. In the causal view, there can be some confounder $Z$ affecting both $X$ and $Y$. If such confounders are not controlled in modeling, some false conclusion about $X$ and $Y$ may be drawn as part or all of the effect might come from $Z$. The key to alleviate the spurious correlations is to control the confounders when evaluating the causal effect of $Y$ given $X$, \textit{i}.\textit{e}., intervention-based modeling $P(Y|do(X))$. Our framework borrows the idea of backdoor adjustment \cite{neuberg2003causality, Wang_Huang_Zhang_Sun_2020}. Formally, by the Bayes Rule, the conventional likelihood can be re-written as: \begin{align} P(Y | X) = \sum_{z} P(Y, z | X) = \sum_{z} P(Y | X, z) \underline{P(z | X)}, \end{align} By using the \textit{do}-calculus, we remove any incoming influence to the intervened variable, \textit{i}.\textit{e}., $X$. By the definition of \textit{do}-calculus, we have: \begin{align} P(Y | do(X)) &= \sum_{z} P(Y, z | do(X)) \\ &= \sum_{z} P(Y | do(X), z) P(z | do(X)) \\ &= \sum_{z} P(Y | X, z) \underline{P(z)}. \end{align} The proof of transitions $ P(Y | do(X)) = P(Y | X, z)$ and $P(z | do(X) = P(z)$ can be found in the book \cite{Aronow_Svje_2020} and in several following works \cite{Wang_Huang_Zhang_Sun_2020, Qi_Niu_Huang_Zhang_2019}. The prior probability of each $z$ can be easily pre-counted before training following \cite{Wang_Huang_Zhang_Sun_2020}. It is infeasible to individually model the distribution of $P(Y|X,z)$ for each $z$ as the number of potential confounders can be large. We borrow the idea of Normalized Weighted Geometric Mean \cite{ Xu_Ba_Kiros_Cho_Courville_Salakhutdinov_Zemel_Bengio_2015,Srivastava_Hinton_Krizhevsky_Sutskever_Salakhutdinov_2014} to approximate the expensive sampling and separate modelling as \cite{Wang_Huang_Zhang_Sun_2020} does. Formally, if the last objective is classification, we can re-write the following terms: \begin{align} P(Y | X, z) &= \textrm{softmax}\left(f_c(\mathbf{x}, \mathbf{z})\right), \\ P(Y | do(X)) &= \mathbb{E}_{z}\left[\operatorname{softmax}\left(f_{c}(\mathbf{x}, \mathbf{z})\right)\right], \end{align} where $\mathbf{x}$ and $\mathbf{z}$ denote the feature representations of $X$ and $z$, and $f_c$ denotes the classification head of intervention. The essence of NWGM is to move the expectation into the operation of softmax: \begin{align} \mathbb{E}_{z}\left[\operatorname{softmax}\left(f_{c}(\mathbf{x}, \mathbf{z})\right)\right] \stackrel{NWGM}{\approx} \operatorname{softmax}\left(\mathbb{E}_{z}\left[f_{c}(\mathbf{x}, \mathbf{z})\right]\right). \end{align} In this paper, we model the term $f_{c}(\mathbf{x}, \mathbf{z})$ by the feed-forward neural network $\mathbf{W}_c[\mathbf{x}, \alpha_y(\mathbf{z}) * \mathbf{z}]$, where $[,]$ denotes the concatenation operation and $\alpha_y(\mathbf{z})$ denotes the importance factor that is parameterized by $\mathbf{y}$. The introduction of y-dependent confounder importance re-weighting strategy follows VC R-CNN \cite{Wang_Huang_Zhang_Sun_2020}. This formulation is reasonable in the sense that a particular $z$ that well correlates with $Y$ have high probability to be the confounder of $Y$ and $X$. Formally, we have: \begin{align} \alpha_y(\mathbf{z}) &= \frac{(\mathbf{W}_y\mathbf{y})^T(\mathbf{W}_z\mathbf{z})}{\sum_{v \ne \varsigma} (\mathbf{W}_y\mathbf{y})^T(\mathbf{W}_z\mathbf{v})}, \\ P(Y|do(X)) &= \operatorname{softmax} \left(\mathbf{W}_c\left[\mathbf{x}, \sum_z P(\mathbf{z}) * \alpha_y(\mathbf{z}) * \mathbf{z} \right]\right). \end{align} where $\mathbf{y}/\mathbf{v}$ is the feature representation of $Y/v$. $\varsigma$ denotes the confounder that has the same token class as $Y$. For example, if the predicted token is $y=\texttt{cat}$, it is unreasonable to take $z=\texttt{cat}$ as a potential confounder for predicting $y=\texttt{cat}$. We note that the corresponding weight $\alpha_y(\mathbf{\varsigma})$ is thus $0$. Now the problem of how to perform intervention-based learning is transformed to define how Bert models the feature representation of $X$ and $Y$. In this paper, we propose several implementations. We note that in the following illustrations, each case is concerning only one masked token, and it is easy to extend the framework to the general case with multiple masked tokens. \begin{itemize} \item \textbf{Design A}. We firstly investigate how to harness masked token modeling with intervention, since 1) MTM is among the most popular pretraining proxy tasks. 2) MTM is solely based on likelihood estimation, which might introduce spurious correlations. Still, we take natural language pretraining as an example for illustration. For one masked word $w_t$, it is intuitively to view the final representation $\mathbf{w}_t$ as $\mathbf{x}_t$ since $\mathbf{w}_t$ contains no explicit information from the word itself (being masked). However, it is not easy to find $\mathbf{y}$ which contains the information of word $w_t$ in single inference. We choose to run another inference with no masked tokens. In this way, the final representation of word $w_t$ can be viewed as $\mathbf{y}$. This implementation is depicted in Figure \ref{fig:imple} A. \item \textbf{Design B}. Figure \ref{fig:imple} B depicts another design to harness MTM. Under the framework of MTM, Bert leverages and aggregates $w_t$-related information from the context to predict the label of $w_t$. In this perspective, the final representation of the masked token $w_t$ can be viewed as $\mathbf{y}_t$ while the final representations of all unmasked tokens can be viewed as $\{ \mathbf{x}_k \}_{k=1,\dots,t-1,t+1,\dots,N_w}$. This design is efficient without an extra inference process. The time complexity is $O(N_u * N_m)$, where $N_u$ and $N_m$ are the numbers of unmasked tokens and masked tokens, respectively. \item \textbf{Design C}. As depicted in Figure \ref{fig:imple} C, Design C is a variant of Design A and views the final representations of all unmasked tokens as $\{ \mathbf{x}_k \}_{k=1,\dots,t-1,t+1,}$${}_{\dots,N_w}$. \item \textbf{Design D}. By viewing the final representations of unmasked tokens as integrated representations of $X$ and $Y$, Design D is non-intrusive and can be the most efficient among the proposed designs. By non-intrusive, we mean that this design makes fewer modifications, \textit{i}.\textit{e}., without another forward run and without hurting the original MTM objective. With the time complexity of $O(N_u)$, Design D is more efficient than the double-run designs as well as Design B. We note that in this design, the modeling of $P(Y|do(X))$ is slightly different: \begin{align} \alpha_r(\mathbf{z}) &= \frac{(\mathbf{W}_r\mathbf{r})^T(\mathbf{W}_z\mathbf{z})}{\sum_z (\mathbf{W}_r\mathbf{r})^T(\mathbf{W}_z\mathbf{z})}, \\ P(Y|do(X)) &= \operatorname{softmax} \left(\mathbf{W}_c\sum_z P(\mathbf{z}) * \alpha_r(\mathbf{z}) * \mathbf{z} \right). \end{align} where $\mathbf{r}$ denotes the integrated representation of $\mathbf{y}$ and $\mathbf{x}$, and $\alpha_r(\mathbf{z})$ is the importance factor parameterized by $\mathbf{r}$. Since the representation $\mathbf{x}$ is no longer available, we omit the concatenation operation. Using both $\mathbf{y}$ and $\mathbf{x}$ to re-weight the importance of each $\mathbf{z}$ is also reasonable in the sense that a particular $z$ that well correlates with both $Y$ and $X$ have high probability to be the confounder of $Y$ and $X$. \end{itemize} \subsection{Intra- \& Inter-modality Intervention} \vpara{Vision deconfounding \& Vision Confounder Set.} It is infeasible to take each particular object (in some image) as a potential confounder as there can be numerous objects in pretraining datasets. Following VC R-CNN \cite{Wang_Huang_Zhang_Sun_2020}, we consider the high-level object classes as potential confounders. The representation of each object class is obtained by averaging pooling the set of object features belonging to the class (but in different images). The size of the confounder set (1,600) is equivalent to the number of object classes that are pre-defined by the pre-trained object detector. For vision deconfounding, $Y$ and $X$ are only selected from the final representations of the visual regions, and confounders in the vision confounder set are discussed. For Design A and B, the MOM objective is totally replaced by the intervention objective. For Design C and D, the intervention is married with the MOM objective. \vpara{Language deconfounding \& Language Confounder Set.} Likewise, it is infeasible to take each particular word token (in some sentence) as a potential confounder, and it is also expensive to discuss all high-level words since there are about 30,000 words in the Bert vocabulary. In this paper, we choose nouns as potential confounders since 1) nouns are content words that have meaning or semantic value \cite{Yang_Liu_2020}; 2) the role of nouns is similar to the role of objects in image, which might ease the inter-modality intervention. Specifically, we use the NLTK toolkit \cite{Bird_2006} to perform Part-of-Speech Tagging, and choose word tokens of which the tags belong to $["NN", "NNS", "NNP", "NNPS"]$ as potential confounders. There are in total 156 potential confounders in the language confounder set (after removing nouns with low-frequencies since such words have less chance to be confounders). The feature representation of each noun is initialized as the mean-pooled vector of the Bert contextual embeddings of words (the same noun) in different sentences. Similarly, for language deconfounding, $Y$ and $X$ are only selected from the final representations of the language words, and confounders in the language confounder set are discussed. We note that only noun words are considered as $X$ and $Y$ since they are of high probability to pose spurious correlations with visual objects. For Design A and B, the MLM objective is replaced by the intervention objective for masked noun words, and others words still have chance to process masked prediction. For Design C and D, the masked prediction objective is not affected by the intervention objective. \vpara{Inter-modality Intervention.} It is necessary to perform inter-modality (or cross-modal) intervention since with the two-stream visio-linguistic modeling, the token representations of each modality contain information from other modalities, which may lead to spurious correlations without inter-modality intervention. We observe that in the Conceptual Caption dataset, the conditional probability of visual object "\texttt{shirt}" give the word "\texttt{instrument}" is about 6\% while \texttt{shirt} and \texttt{instrument} have no causal relationship but might have a common cause, \textit{i}.\textit{e}., the visual object or the language word \texttt{person}. Specifically, for inter-modality intervention, $Y$ and $X$ can be tokens from different modalities, and confounders can be selected from both vision and language confounder sets. We note that both the MTM and the intervention-based objective conduct object classification for vision, and word prediction for language. The difference between intervention and MTM is that intervention discusses the effect of $Y$ given $X$ and each potential confounder $z$, which helps mitigate the spurious correlations. \section{Experiments} \subsection{Experiment Setup} \vpara{Pretraining DeVLBert.} We follow ViLBERT \cite{Lu_Batra_Parikh_Lee_2019} to pretrain DeVLBert on the Conceptual Caption \cite{Sharma_Ding_Goodman_Soricut_2018} dataset, which is an out-of-domain dataset that has little data overlap with most downstream tasks. Images and raw descriptions are harvested from HTML pages that contain images and Alt-text attributes. Then, automatic language cleaning pipelines are developed to obtain the final image captions that are clean, informative, but less similar to the human-annotated captions in datasets of downstream tasks. In other words, the Conceptual Caption dataset serves as an excellent dataset for out-of-domain pretraining. Due to broken or expired links by the time we downloaded, we use around 3.04 million <image, caption> pairs for pretraining, which is smaller than the original 3.3 million dataset when first published, and also smaller than the 3.1 million dataset used in ViLBERT. To make our results comparable to the previous out-of-domain pretraining work, \textit{i}.\textit{e}., ViLBERT, we are following the exact pipeline as theirs, including the initialization of the linguistic stream and visual region feature extraction. \vpara{Finetuning on downstream tasks.} Also, we are following the pipelines of three downstream tasks, \textit{i}.\textit{e}., Text-to-Image Retrieval (IR), Zero-shot Text-to-Image Retrieval (Zero-shot IR), and Visual Question Answering (VQA) of ViLBERT. For more details, such as dataset split, fine-tuning strategies, and hyper-parameters, please refer to ViLBERT\cite{Lu_Batra_Parikh_Lee_2019}. We note that our goal is not achieving the state-of-the-art with bells\&whistles but demonstrating the effectiveness of mitigating spurious correlations of DeVLBert for out-of-domain pretraining. Besides the quantitative evaluations, we conduct user studies that qualitatively show whether and how DeVLBert achieves better results by mitigating biases. \begin{table}[!t] \centering \caption{ % % % Comparisons between different DeVLBert implementations, and ablation studies on the architecture D. } \setlength\doublerulesep{0.5pt} \begin{tabular}{l|ccc|ccc} & \multicolumn{3}{c}{Image Retrieval (IR) } & \multicolumn{3}{c}{Zero-shot IR} \\ \multicolumn{1}{c|}{Method} & R@1 & R@5 & R@10 & R@1 & R@5 & R@10 \\ \hline \hline Baseline & 58.2 & 84.9 & 91.5 & 31.9 & 61.1 & 72.8 \\ \hline A-V & 60.3 & 86.24 & 92.06 & 30.18 & 59.46 & 71.88 \\ A-VL & 58.3 & 85.5 & 91.6 & 25.4 & 54.7 & 67.2 \\ \hline B-V & 58.9 & 85.3 & 91.1 & 33.0 & 62.2 & 74.0 \\ \hline C-V & - & - & - & 27.0 & 56.2 & 69 \\ \hline D-V & 59.3 & 85.4 & 91.8 & 32.8 & 63.0 & 74.1 \\ D-VL & 60.3 & 86.7 & 92.2 & 34.9 & 65.5 & 77.0 \\ D-VLC & \textbf{61.6} & \textbf{87.1} & \textbf{92.6} & \textbf{36.0} & \textbf{67.1} & \textbf{78.3} \\ \hline \end{tabular} \vspace{-0.2cm} \label{tab:designs} \end{table} \vpara{Hardware \& Software Configuration} We implement the models in python3.6 and PyTorch 1.1.0 \cite{paszke2017automatic}, and train the models on a Linux server equipped with 8 NVIDIA V100-SXM2-16GB GPUs. \subsection{Quantitative Evaluation} By quantitative evaluation, we care about a few issues listed below: \vpara{How do different intervention-based architectures perform?} To answer this question, we evaluate the performance of different architectures on the downstream tasks, \textit{i}.\textit{e}., image retrieval, and zero-shot image retrieval. The results are listed in Table \ref{tab:designs}. We use A-V to denote the architecture of design A, A-VL to denote the architecture of design A with both vision and language deconfounding. Based on the results, we can see that: \begin{itemize} \item Most of the architectures obtain performance gain on at least one of the tasks, which demonstrates the effectiveness of intervention-based learning. \item The twice inference design achieves inferior results on the zero-shot image retrieval task. Partially due to the complexities introduced by another inference, it might take more iterations to converge, which can be expensive. Moreover, similar to the results shown in VC R-CNN \cite{Wang_Huang_Zhang_Sun_2020} that the performance of directly using the pre-trained commonsense features (intervention-based) is lower than that of the original features (association-based) while combining these two features would achieve the best performance. In our case, combining the pretrained deconfounding features with the knowledge in the downstream task (regular image retrieval) achieves better results in zero-shot IR. \item Comparing A-VL with A-V, the introduction of language deconfounding leads to a performance drop on IR and zero-shot IR. We attribute this phenomenon to the incomplete training of MTM. For the language side, following ViLBERT, the classification module shares the word embedding matrix with the input embedding layer. For A-VL, we only mask noun words since the language confounder set comprises only noun words. Therefore, the embedding matrix solely sees noun words in the classification, which leads to inferior results due to incomplete learning of other words. Non-intrusive design D mitigates this problem. \item Without the structure and training complexities introduced by the other inference, B-V and D-V show clear advantages over A-C and C-V. \item D-V further outperforms the architecture of B-V, and we attribute this consistent improvement to the non-intrusive intervention modeling. More concretely, isolating the masked token modeling makes the shared embedding module in the MTM classification module learn better. Meanwhile, architecture D is the most efficient. \end{itemize} \begin{table}[!t] \centering \caption{ % % % Comparisons between DeVLBert and VC R-CNN (with Bert as language feature extractor). } \setlength\doublerulesep{0.5pt} \begin{tabular}{l|ccc|cc} & \multicolumn{3}{c}{Image Retrieval (IR) } & \multicolumn{2}{c}{VQA} \\ \multicolumn{1}{c|}{Method} & R@1 & R@5 & R@10 & test-dev & test-std \\ \hline \hline VC R-CNN \cite{Wang_Huang_Zhang_Sun_2020} & 15.0 & 40.4 & 54.7 & 53.2 & 53.6 \\ \hline DeVLBert & 39.2 & 70.2 & 80.5 & 53.5 & 53.9 \\ \hline \end{tabular} \vspace{-0.2cm} \label{tab:vcrcnn} \end{table} \begin{figure*}[t] \begin{center} \includegraphics[width=0.9\textwidth]{./figures/AttentionVisualization.pdf} \caption{ Case studies by visualizing the attention of the last cross-modal attention layer in DeVLBert (the left for each case) and ViLBERT (right). Cases are sampled from the testing/validation set of downstream tasks, \textit{i}.\textit{e}., image retrieval (top), and VQA (bottom). The labeled word is the attention query word from the input sentence, and the number is the corresponding attention weight. } \vspace{-0.2cm} \label{fig:cases} \end{center} \end{figure*} \vpara{Do both intra-modality intervention and inter-modality intervention improve the out-of-domain pretraining?} Since architecture D-V achieves the best performance, we further extend architecture D-V to architecture D-VL by incorporating language deconfounding, and architecture D-VLC by incorporating the cross-modal (inter-modality) deconfounding. The evaluation results are shown in Table \ref{tab:designs}, it can be seen that removing any deconfounding component will lead to a performance drop, which again verifies the effectiveness of the proposed framework. \vpara{How does DeVLBert perform comparing with existing visio-linguistic pretraining methods and task-specific downstream SOTA models?} We view the architecture D-VLC as DeVLBert due to its empirical effectiveness. As shown in Table \ref{tab:quantitative}, when compared to task-specific SOTA models, including SCAN \cite{Lee_Chen_Hua_Hu_He_2018} for image retrieval, BUTD \cite{Anderson_He_Buehler_Teney_Johnson_Gould_Zhang_2018} for visual question answering, DeVLBert yields a large margin improvement over these methods. More importantly, while the baseline method, \textit{i}.\textit{e}., ViLBERT \cite{Lu_Batra_Parikh_Lee_2019}, cannot beat in-domain pretraining methods, including VisualBERT \cite{Li_Yatskar_Yin_Hsieh_Chang_2019} using MSCOCO as the pretraining dataset, and InterBert using both Conceptual Caption and MSCOCO as pretraining datasets, DeVLBert obtains a performance boost over the VisualBert and InterBert on the VQA task and achieves comparable results to the InterBert on the image retrieval task. On zero-shot image retrieval, DeVLBert cannot beat InterBert, which is a reasonable result since MSCOCO is the testing dataset for zero-shot image retrieval, and InterBert uses MSCOCO for pretraining. \begin{sloppypar} \vpara{How does DeVLBert perform comparing with VC R-CNN?} The comparison results with VC R-CNN \cite{Wang_Huang_Zhang_Sun_2020}, which learns visual commonsense features by intervention, are listed in Table \ref{tab:vcrcnn}. We use VC R-CNN as the visual feature extractor and vanilla Bert as the language feature extractor. For fair comparison, we do not fine-tune DeVLBert on the downstream datasets either, and view DeVLBert as visio-language feature extractor. We mean-pool the extracted features for each modality and concatenate the pooled features from two modalities. We use two layer MLP as classifier with hidden size twice as large as the input feature size. According to Table \ref{tab:vcrcnn}, DeVLBert achieves large performance gain over VC R-CNN on multi-modal matching tasks (Image Retrieval) and competitive results on VQA, which shows cross-modal pretraining and deconfounding are essential for cross-modal downstream tasks. \end{sloppypar} \subsection{Case Studies} To further evaluate the effectiveness of DeVLBert from the human perspective, we follow \cite{Wang_Huang_Zhang_Sun_2020} to conduct case studies on the testing/validation set of downstream tasks, including image retrieval and VQA (See Figure \ref{fig:cases}). For image retrieval, given a query sentence, we select the top answer image of DeVLBert (left) and ViLBERT (right). Compared to the VC R-CNN that focusing on visual attention, here we are especially interested in cross-modal attention, which is essential for visual-language tasks. Concretely, there are multiple co-attention blocks in both ViLBERT and DeVLBert, and we select the last block to obtain task-oriented association (the closer to the classification layer, the more task-oriented). Each co-attention block still contains multiple attention heads, we take the average attention map of all heads for visualization. We select the box with the biggest attention weight for each word. The results indicate that: 1) \textbf{The attended visual tokens (object boxes) of DeVLBert are more accurate than those of ViLBERT.} By "accurate", we mean the attended tokens are more useful for determining whether this image is locally relevant to the query sentence, and better as reasoning cues given the question. For example, in the case $C_{34}$, which denotes the case in the $3$rd row and the $4$th column, the attended box of ViLBERT (right) directly focuses on \texttt{sitting} and fails to consider the \texttt{sandwiches sitting}, \textit{i}.\textit{e}., question-specific context, while the attended box of DeVLBert is more accurate. We further compute the conditional probability of the answer given word \texttt{sitting}, which shows that DeVLBert can generate less frequent but more accurate answers. 2) \textbf{The results of DeVLBert yields less cognitive errors or spurious correlations}. For example, in case $C_{11}$, ViLBERT considers "person with wedding veil" as the "bride", and view the man as "bride" by mistake. In case $C_{32}$, there is a spurious correlation between the word \texttt{grass} and the visual object \texttt{highway}, which drives the ViLBERT to attend to the region with both \texttt{grass} and \texttt{highway}. With such attended region, ViLBERT fail to realize that the grass is growing wild and untamed. The conditional probabilities under $C_{31}$ and $C_{32}$ show DeVLBert can learn to pay less attention to spuriously correlated tokens such as \texttt{sky} and \texttt{highway} by deconfounding. \section{Conclusion} In this paper, we propose to mitigate the spurious correlations for out-of-domain visio-linguistic pretraining. The fact that each output token is connected with all input tokens in Bert, and the pure association nature of masked token modeling objective makes the problem more severe. We borrow the idea of back-door adjustment to propose four novel Bert-style architectures as DeVLBert for out-of-domain pretraining. We conduct extensive quantitative evaluations as well as ablation studies to discuss the empirical effectiveness of different architectures. The results show that DeVLBert can achieve promising numerical results compared to the baseline and even some in-domain visio-linguistic pretraining methods. \section{ACKNOWLEDGMENTS} \begin{sloppypar} The work is supported by the NSFC (61625107, 61751209, 61836002), National Key R\&D Program of China (No. 2018AAA0101900, No. 2018AAA0100603), Zhejiang Natural Science Foundation (LR19F020006), Fundamental Research Funds for the Central Universities (2020QNA5024), and a research fund supported by Alibaba. \end{sloppypar} \section{Appendix} \label{sec:appendix} \subsection{Details on the Experimental Setup and Hyperparameters} \vpara{Hyper-parameter Configuration} The parameter setup of \textit{granular level interaction modeling} process is shown in Figure \ref{fig:granular-level}. During training, the batch size is set to 64 and we use Adam optimizer \cite{Kingma_Ba_2015} with the setting $\beta _ { 1 } = 0.9 , \beta _ { 2 } = 0.999, \mathrm{weight decay} = 1 \times 10 ^ {-4} \text { and } \epsilon = 1 \times 10 ^ { - 8 }$. Learning rate is $4 \times 10 ^ {-4}$. We employ dropout rate of 0.2 and batch normalization after graph information propgation. We also applied a dropout rate of 0.5 for RNNs and linear layers as regularization. The hidden size of both story-line summarization RNN and decoder RNN is set to 512. The loss weight $\lambda_{gc}$ is set to 0.1. At the inference stage, we use the greedy strategy to generate the final title. \begin{figure}[!h] \begin{center} \includegraphics[width=\columnwidth]{./figures/Granular-Level.pdf} \caption{ Architecture and parameter configuration of granular-level interaction modeling process. } \label{fig:granular-level} \end{center} \end{figure} \begin{figure}[!t] \begin{center} \includegraphics[width=\columnwidth]{./figures/example.pdf} \caption{ A <video, comment, attributes, title> quadruple data sample in T-VTD. } \label{fig:example} \end{center} \end{figure} \vpara{Hardware \& Software Configuration } The experiments are conducted on a Linux server equipped with an Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz, 512GB RAM and 1 NVIDIA Titan V GPU. All models are implemented in PyTorch \citep{paszke2017automatic} of version 1.2.0, pytorch-geometric \cite{Fey_Lenssen_2019} of version 1.3.2 and Python 3.6. We'll soon release the main code of \Our for reproduction and further development. \begin{table*}[t] \centering \setlength{\tabcolsep}{7.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|cccccc} \multicolumn{1}{c|}{Dataset} & Context & \#Video & \#Sentence & \#Word & \#Vocabulary & Total Duration(hrs) \\ \hline \hline MSVD \cite{Chen_Dolan_2011} & multi-category & 1,970 & 70,028 & 607,339 & 13,010 & 5.3 \\ YouCook \cite{Das_Xu_Doell_Corso_2013} & cooking & 88 & 2,668 & 42,457 & 2,711 & 2.3 \\ TACos \cite{Regneri_Rohrbach_Wetzel_Thater_Schiele_Pinkal_2013} & cooking & 123 & 18,227 & 146,771 & 28,292 & 15.9 \\ TACos M-L \cite{Rohrbach_Rohrbach_Qiu_Friedrich_Pinkal_Schiele_2014} & cooking & 185 & 14,105 & 52,593 & - & 27.1 \\ MPII-MD \cite{Rohrbach_Rohrbach_Tandon_Schiele_2015} & movie & 94 & 68,375 & 653,467 & 24,549 & 73.6 \\ M-VAD \cite{Torabi_Pal_Larochelle_Courville_2015} & movie & 92 & 55,905 & 519,933 & 18,269 & 84.6 \\ VTW \cite{Torabi_Pal_Larochelle_Courville_2015} & multi-category & 18,100 & 44,603 & - & 23,059 & 213.2 \\ MSR-VTT \cite{Zeng_Chen_Niebles_Sun_2016} & multi-category & 7,180 & 200,000 & 1,856,523 & 29,316 & 41.2 \\ Charades \cite{Sigurdsson_Varol_Wang_Farhadi_Laptev_Gupta_2016} & human & 9,848 & 27,847 & - & - & 82.01 \\ \hline \hline T-VTD & e-commerce & 90,000 & 180,000 & 3,878,436 & 68,232 & 755.73 \\ \hline \end{tabular} \caption{ Comparison between T-VTD with benchmark video captioning datasets, considering various capacity indicators.. } \label{table:Data} \end{table*} \subsection{Additional Details on the Dataset } \label{sub:data} The summarized statistics of T-VTD and comparisons with other frequently used benchmark video captioning datasets are shown in Figure \ref{table:Data}. Specifically, T-VTD contains 90000 videos with a total length of 755.73 hours, which is much larger than current datasets. As for natural language data, T-VTD has totally 3,878,436 words (in titles and comments) with a vocabulary of 68232. The nature of abundant vocabulary and little repetitive information poses a direct challenge to fully understand the semantic information and avoid obtaining high scores just by overfitting to some biases. We summary the statistics of video durations in our dataset in Table \ref{table:videoduration}. The video durations in our dataset are mainly 15-30s, with an average video length around 30.23s. The longest video can reach 600 seconds (about 10 minutes). As shown in Table \ref{table:titlecontent} and \ref{table:attributes}, the average length of elements in the titles, comments and attributes are 6.6, 36.49 and 17.54, respectively. The vocabulary size is 27,976 for video titles and 59,109 for narrative comments. There are 81 different attribute-key types and 266,648 different attribute-value types, \textit{i}.\textit{e}., the vocabulary size of human-nameable attributes. A real case in our dataset is shown in Figure \ref{fig:example}. It can be seen that the comment sentences mainly narrate the preference for different aspects of products. Although the attributes of associated products structurally specify the human-nameable qualities of the products, these attributes can be noisy since they may cover all possible choices (such as different colors) and not exactly the product in the video. Models are required to fully understand the video rather than simply distill information from the attributes or the comment. \begin{table}[!t] \centering \setlength{\tabcolsep}{5.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|ccc} & avg\_len & total\_len & vocab \\ \hline \hline title & 6.6 & 594,279 & 27,976 \\ comment & 36.49 & 3,284,157 & 59,109 \\ \hline \end{tabular} \caption{ Basic statistics of titles and comments in T-VTD. } \label{table:titlecontent} \end{table} \subsection{Details on Data Pre-processing} \label{sub:id} For text pre-processing, we remove the punctuations and tokenize sentences using Jieba Chinese Tokenizer \footnote{https://github.com/fxsjy/jieba}. Our vocabulary contains all attributes values, comment tokens and ground-truth title tokens. Since the real-world text data is noised and many expressions can be confusing or meaningless, such as brands and homophonic words. We roughly filter them by replacing low-frequency tokens (less than 50) with the special token $<unk>$, resulting in 6347 tokens in total. The length limitations for title, comment and attributes are 12, 50 and 15, respectively. Text with number of tokens more than the corresponding limitation will be truncated. We add a special $<sos>$ token as the first word for the title and a $<eos>$ at the end. When the $<sos>$ token is predicted in the decoding stage, the generation will be terminated. For video processing, we first uniformly sample 30 frames per video. For landmark feature extraction, we extract the product area using internal product detector for all sampled frames. Then we use the pre-trained landmark detector \footnote{https://github.com/fdjingyuan/Deep-Fashion-Analysis-ECCV2018} provided by \cite{liu2018deep}. Specifically, the backbone model $VGG16$ takes each frame as input and output the activations of shape $512 \times 7 \times 7$ from layer \textit{pooled\_5}. This feature map is forwarded to the landmark decoder, which produce the landmark-oriented features of shape $64 \times 14 \times 14$ and the mask-like landmark maps of shape $8 \times 56 \times 56$, \textit{i}.\textit{e}., 8 landmarks maps of shape $\times 56 \times 56$ each. We downsampled each landmark map to have the same width and height as the landmark-oriented features. Deriving from the observation that intermediate feature map and emergent patterns are highly correlated, we normalize each landmark map as weights using softmax and compute weighted sum over the landmark-oriented features as the landmark feature. \begin{table}[!t] \centering \setlength{\tabcolsep}{3.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|cccccc} & average & min & Q1 & median & Q3 & max \\ \hline \hline video duration (s) & 30.23 & 1.5 & 15.72 & 23.56 & 32.2 & 600.08 \\ \hline \end{tabular} \caption{ Statistics of the video duration. (Q1 denotes the lower quartile and Q3 denotes the upper quartile.) } \label{table:videoduration} \end{table} For frame-level feature extraction, we use the same model as landmark feature extraction and obtain the activations of shape $128 \times 7 \times 7$ from layer \textit{conv4} for each frame. We use the global average pooling result as the frame feature. The dataset we use for training is a subset (84394 samples) of the released dataset (90000 samples) due to the the data pre-processing (mainly the low-frequency words removal procedure) after which many words in the comment and elements in the attributes set will be replaced by $<unk>$. Specifically, we remove the following 3 kinds of samples: 1) sample with less than 2 non-$<unk>$ elements (\textit{i}.\textit{e}., where will be no edges in the graph) in the attributes set. 2) sample with 0 non-$<unk>$ words in the title. 3) sample with less than 11 non-$<unk>$ nodes in or less than 5 edges in the narrative comment graph. Overall, we mainly remove samples with little information within either one kind of fact (narrative comment or human-nameable attributes) or the ground truth title to make the data more reliable. We randomly split the whole dataset by train 65\%, validation 5\% and test 30\%, resulting in 54856 samples for training, 4220 samples for validation and 25318 samples for testing. \begin{table}[!t] \centering \setlength{\tabcolsep}{2.5pt} \setlength\doublerulesep{0.5pt} \begin{tabular}{l|ccccc} & \multirow{2}{*}{avg\_num} & total\_num & total\_num & vocab & vocab \\ & & of keys & of values & of keys & of values \\ \hline \hline attributes & 17.54 & 1,578,777 & 2,604,904 & 81 & 266,648 \\ \hline \end{tabular} \caption{ Basic statistics of attributes in T-VTD. } \label{table:attributes} \end{table}
{'timestamp': '2020-10-05T02:13:06', 'yymm': '2008', 'arxiv_id': '2008.06884', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06884'}
arxiv
\section{Introduction} \label{Introduction} Object detection in aerial images serves as an essential step for numerous applications such as urban planning, traffic surveillance, port management, and maritime rescue \cite{azimi2018towards,zhang2018toward}. The aerial images are taken from the bird's-eye view. Detecting objects in aerial images is a challenging task as the objects typically have different scales and textures, and the background is complex. Moreover, the objects are usually densely packed and displayed in arbitrary directions. Consequently, applying the horizontal bounding boxes to oriented object detection would lead to misalignment between the detected bounding boxes and the objects \cite{ding2019learning}. To deal with this problem, oriented bounding boxes are preferred for capturing objects in aerial images. \begin{figure}[t!] \begin{center} \includegraphics[width=\linewidth]{images/pic1.pdf} \end{center} \caption{Oriented bounding box (OBB) descriptions for (a) baseline method, termed Center+$wh$+$\theta$, where $w,h,\theta$ are the width, height and angle of an OBB. Note that $w$ and $h$ of the OBBs are measured in different rotating coordinate systems for each object; (b) the proposed method, where $\textbf{t}, \textbf{r}, \textbf{b}, \textbf{l}$ are the top, right, bottom and left box boundary-aware vectors. The box boundary-aware vectors are defined in four quadrants of the Cartesian coordinate system for all the arbitrarily oriented objects; (c) illustrates the corner cases where the vectors are very close to the $xy$-axes.} \label{fig:figure1} \end{figure} Current oriented object detection methods are mainly derived from the two-stage anchor-based detectors \cite{girshick2014rich,girshick2015fast,ren2015faster}. Generally, in the first stage, those detectors spread anchor boxes on the feature maps densely and then regress the offsets between the target box and the anchor box parameters in order to provide region proposals. In the second stage, the region-of-interest (ROI) features are pooled to refine the box parameters and classify the object categories. Notably, they use the center, width, height, and angle as the descriptions of an oriented bounding box. The angle is learned either in the first stage or in the second stage. For instance, R$^2$CNN \cite{jiang2017r2cnn}, Yang et al. \cite{yang2018position}, and ROI Transformer \cite{ding2019learning} regress the angle parameters from the pooled horizontal region proposal features in the second stage; similarly, R$^2$PN \cite{zhang2018toward}, R-DFPN \cite{yang2018automatic} and ICN \cite{azimi2018towards} generate oriented region proposals in the first stage. These oriented object detection methods share the same drawbacks with the anchor-based detectors. For example, the design of the anchor boxes is complicated; and the choices of aspect-ratios and the size of the anchor boxes need to be tuned carefully. Besides, the extreme imbalance between the positive and negative anchor boxes would induce slow training and sub-optimal performance \cite{duan2019centernet}. Moreover, the crop-and-regress strategies in the second stage are computationally expensive \cite{zhou2019bottom}. Recently, the keypoint-based object detectors \cite{law2018cornernet,zhou2019bottom,duan2019centernet} have been developed to overcome the disadvantages of anchor-based solutions \cite{ren2015faster,liu2016ssd,yi2019assd} in the horizontal object detection task. In particular, these methods detect the corner points of the bounding boxes and then group these points by comparing embedding distances or center distances of the points. Such strategies have demonstrated improved performance, yet with one weakness that the grouping process is time-consuming. To address this issue, Zhou's CenterNet \cite{zhou2019objects} suggests detecting the object center and regressing the width ($w$) and height ($h$) of the bounding box directly, which achieves faster speed at comparable accuracy. Intuitively, Zhou's CenterNet can be extended to the oriented object detection task by learning an additional angle $\theta$ together with $w$ and $h$ (see Fig.~\ref{fig:figure1}a). However, as the parameters $w$ and $h$ are measured in different rotating coordinate systems for each arbitrarily oriented object, jointly learning those parameters may be challenging for the model. In this paper, we extend Zhou's CenterNet to the oriented object detection task. However, instead of regressing the $w$, $h$ and $\theta$ at the center points, we learn the box boundary-aware vectors (BBAVectors, Fig.~\ref{fig:figure1}b) to capture the rotational bounding boxes of the objects. The BBAVectors are distributed in the four quadrants of the Cartesian coordinate system. Empirically we show that this design is superior to directly predicting the spatial parameters of bounding boxes. In practice, we observe that in the corner cases, where the vectors are very close to the boundary of the quadrants (i.e., $xy$-axes in Fig.~\ref{fig:figure1}c), it would be difficult for the network to differentiate the vector types. To deal with this problem, we group the oriented bounding box (OBB) into two categories and handle them separately. Specifically, we have two types of boxes: horizontal bounding box (HBB) and rotational bounding box (RBB), where RBB refers to all oriented bounding boxes except the horizontal ones. We summarize our contributions as follows: \begin{itemize} \item We propose the box boundary-aware vectors (BBAVectors) to describe the OBB. This strategy is simple yet effective. The BBAVectors are measured in the same Cartesian coordinate system for all the arbitrarily oriented objects. Compared to the baseline method that learns the width, height and angle of the OBBs, the BBAVectors achieve better performance. \item We extend the center keypoint-based object detector to the oriented object detection task. Our model is single-stage and anchor box free, which is fast and accurate. It achieves state-of-the-art performances on the DOTA and HRSC2016 datasets. \end{itemize} \section{Related Work} \label{Related Work} \subsection{Oriented Object Detection} The horizontal object detectors, such as R-CNN \cite{ma2015hierarchical}, fast R-CNN \cite{girshick2015fast}, faster R-CNN \cite{ren2015faster}, SSD \cite{liu2016ssd}, YOLO \cite{redmon2016you}, are designed for horizontal objects detection. These methods generally use the horizontal bounding boxes (HBB) to capture the objects in natural images. Different from the horizontal object detection task, oriented object detection relies on oriented bounding boxes (OBB) to capture the arbitrarily oriented objects. Current oriented object detection methods are generally extended from the horizontal object detectors. For example, R$^2$CNN \cite{jiang2017r2cnn} uses the region proposal network (RPN) to produce the HBB of the text and combines different scales of pooled ROI features to regress the parameters of OBB. R$^2$PN \cite{zhang2018toward} incorporates the box orientation parameter into the RPN network and develops a rotated RPN network. R$^2$PN also utilizes a rotated ROI pooling to refine the box parameters. R-DFPN \cite{yang2018automatic} employs the Feature Pyramid Network (FPN) \cite{lin2017feature} to combine multi-scale features and boost the detection performance. Based on the DFPN backbone, Yang \textit{et al}. \cite{yang2018position} further propose an adaptive ROI Align method for the second-stage box regression. RoI Transformer \cite{ding2019learning} learns the spatial transformation from the HBBs to OBBs. ICN \cite{azimi2018towards} develops an Image Cascade Network that enhances the semantic features before adopting R-DFPN. RRD \cite{liao2018rotation} uses active rotation filters to encode the rotation information. Gliding Vertex \cite{xu2020gliding} glide the vertex of the horizontal bounding boxes to capture the oriented bounding boxes. All these methods are based on anchor boxes. Overall, the anchor-based detectors first spread a large amount of anchor boxes on the feature maps densely, and then regress the offsets between the target boxes and the anchor boxes. Such anchor-based strategies suffer from the imbalance issue between positive and negative anchor boxes. The issue would lead to slow training and sub-optimal detection performances \cite{law2018cornernet}. \begin{figure*}[t!] \begin{center} \includegraphics[width=0.9\linewidth]{images/pic2.pdf} \end{center} \caption{The overall architecture and the oriented bounding box (OBB) descriptions of the proposed method. The input image is resized to $608\times 608$ before being fed to the network. The architecture is built on a U-shaped network. Skip connections are adopted to combine feature maps in the up-sampling process. The output of the architecture involves four maps: the heatmap $P$, offset map $O$, box parameter map $B$, and orientation map $\alpha$. The locations of the center points are inferred from the heatmap and offset map. At the center points, the box boundary-aware vectors (BBAVectors) are learned. The resolution of the output maps is $152\times 152$. HBBs refer to the horizontal bounding boxes. RBBs indicate all oriented bounding boxes except the HBBs. The symbols $\textbf{t},\textbf{r},\textbf{b}, \textbf{l}$ refer to the top, right, bottom and left vectors of BBAVectors, $w_e$ and $h_e$ are the external width and height of an OBB. The decoded OBBs are shown in red bounding boxes.} \label{fig:figure2} \end{figure*} \subsection{Keypoint-Based Object Detection} The keypoint-based object detectors \cite{law2018cornernet,zhou2019bottom,zhou2019objects,yi2019multi} capture the objects by detecting the keypoints and therefore provide anchor-free solutions. Keypoint detection is extensively employed in the face landmark detection \cite{merget2018robust} and pose estimation \cite{newell2016stacked,sun2018integral}. In the horizontal object detection task, the keypoint-based detection methods propose to detect the corner points or the center points of the objects and extract the box size information from these points. Cornernet \cite{law2018cornernet} is one of the pioneers. It captures the top-left and bottom-right corner points of the HBB using heatmaps. The corner points are grouped for each object by comparing the embedding distances of the points. Duan's CenterNet \cite{duan2019centernet} detects both corner points and center points. ExtremeNet \cite{zhou2019bottom} locates the extreme and center points of the boxes. These two methods both use the center information to group the box points. However, the post-grouping process in these methods is time-consuming. To address this problem, Zhou's CenterNet \cite{zhou2019objects} proposes to regress the width and height of the bounding box at the center point without a post-grouping process, which makes the prediction faster. The keypoint-based object detectors show advantages over the anchor-based ones in terms of speed and accuracy, yet the keypoint-based detectors are barely applied to oriented object detection task. \paragraph{Baseline method.} In this paper, we extend Zhou's CenterNet to the oriented object detection task. In particular, we first build a baseline method that directly regresses the width $w$ and height $h$ as well as the orientation angle $\theta$ of the bounding boxes. We term this baseline method as Center$+wh+\theta$ (see Fig.~\ref{fig:figure1}a). We compare the proposed method with Center$+wh+\theta$ to demonstrate the advantages of box boundary-aware vectors. \section{Method} In this section, we first describe the overall architecture of the proposed method, and then explain the output maps in detail. The output maps are gathered and decoded to generate the oriented bounding boxes of the objects. \subsection{Architecture} \label{sub:architecture} The proposed network (see Fig.~\ref{fig:figure2}) is built on a U-shaped architecture \cite{ronneberger2015u}. We use the ResNet101 Conv1-5 \cite{he2016deep} as the backbone. At the top of the backbone network, we up-sample the feature maps and output a feature map that is 4 times smaller (scale $s=4$) than the input image. In the up-sampling process, we combine a deep layer with a shallow layer through skip connections to share both the high-level semantic information and low-level finer details. In particular, we first up-sample a deep layer to the same size of the shallow layer through bilinear interpolation. The up-sampled features map is refined through a $3\times3$ convolutional layer. The refined feature map is then concatenated with the shallow layer, followed by a $1\times1$ convolutional layer to refine the channel-wise features. Batch normalization and ReLU activation are used in the latent layers. Suppose an input RGB image is $I\in\mathbb{R}^{3\times H\times W}$, where $H$ and $W$ are the height and width of the image. The output feature map $X\in \mathbb{R}^{C\times \frac{H}{s}\times \frac{W}{s}}$ ($C=256$ in this paper) is then transformed into four branches: heatmap ($P\in \mathbb{R}^{K\times \frac{H}{s}\times \frac{W}{s}}$), offset ($O\in \mathbb{R}^{2\times\frac{H}{s}\times \frac{W}{s}}$), box parameter ($B\in \mathbb{R}^{10\times \frac{H}{s}\times \frac{W}{s}}$), and the orientation map ($\alpha\in \mathbb{R}^{1\times \frac{H}{s}\times \frac{W}{s}}$), where $K$ is the number of dataset categories and $s=4$ refers to the scale. The transformation is implemented with two convolutional layers with $3\times3$ kernels and $256$ channels. \subsection{Heatmap} \label{sub:heatmap} Heatmap is generally utilized to localize particular keypoints in the input image, such as the joints of humans and the facial landmarks \cite{merget2018robust,newell2016stacked,sun2018integral}. In this work, we use the heatmap to detect the center points of arbitrarily oriented objects in the aerial images. Specifically, the heatmap $P\in \mathbb{R}^{K\times \frac{H}{s}\times \frac{W}{s}}$ used in this work has $K$ channels, with each corresponding to one object category. The map at each channel is passed through a sigmoid function. The predicted heatmap value at a particular center point is regarded as the confidence of the object detection. \paragraph{Groundtruth} Suppose $\textbf{c}=(c_x, c_y)$ is the center point of an oriented bounding box, we place a 2D Gaussian exp$({-\frac{(p_x-c_x)^2+(p_y-c_y)^2}{2\sigma^2}})$ (see Fig.~\ref{fig:figure2}) around each $\textbf{c}$ to form the groundtruth heatmap $\hat{P}\in \mathbb{R}^{K\times \frac{H}{s}\times \frac{W}{s}}$, where $\sigma$ is a box size-adaptive standard deviation \cite{zhou2019objects,law2018cornernet}, point $\hat{\mathbf{p}} = (p_x,p_y)$ indexes the pixel points on $\hat{P}$. \paragraph{Training Loss} When training the heatmaps, only the center points $\textbf{c}$ are positive. All the other points including the points in the Gaussian bumps are negative. Directly learning the positive center points would be difficult due to the imbalance issue. To handle this problem, following the work of \cite{law2018cornernet}, we decrease the penalty for the points inside the Gaussian bumps and use the variant focal loss to train the heatmap: \begin{equation} L_{h}= -\frac{1}{N}\sum_{i} \begin{cases} (1-p_{i})^\alpha\log(p_{i}) & \text{if } \hat{p}_{i}=1\\ (1-\hat{p}_{i})^\beta p_{i}^\alpha \log(1-p_{i}) & \text{otherwise},\\ \end{cases} \end{equation} where $\hat{p}$ and $p$ refer to the ground-truth and the predicted heatmap values, $i$ indexes the pixel locations on the feature map, $N$ is the number of objects, $\alpha$ and $\beta$ are the hyperparameters that control the contribution of each point. We choose $\alpha=2$ and $\beta=4$ empirically as in \cite{law2018cornernet}. \subsection{Offset} \label{sub:offsets} In the inference stage, the peak points are extracted from the predicted heatmap $P$ as the center point locations of the objects. These center points $\textbf{c}$ are integers. However, down-scaling a point from the input image to the output heatmap generates a floating-point number. To compensate for the difference between the quantified floating center point and the integer center point, we predict an offset map $O\in \mathbb{R}^{2\times\frac{H}{s}\times \frac{W}{s}}$. Given a ground-truth center point $\Bar{\mathbf{c}} = (\Bar{c}_x,\Bar{c}_y)$ on the input image, the offset between the scaled floating center point and the quantified center point is: \begin{equation} \textbf{o} = (\frac{\Bar{c}_x}{s}-\lfloor{\frac{\Bar{c}_x}{s}}\rfloor, \frac{\Bar{c}_y}{s}-\lfloor{\frac{\Bar{c}_y}{s}}\rfloor), \end{equation} The offset is optimized with a smooth $L_1$ loss \cite{girshick2015fast}: \begin{equation} L_{o} = \frac{1}{N}\sum_{k=1}^{N}\text{Smooth}_{L_1}(\mathbf{o}_k-\hat{\mathbf{o}}_k), \end{equation} where $N$ is the total number of objects, $\hat{\mathbf{o}}$ refers to the ground-truth offsets, $k$ indexes the objects. The smooth $L_1$ loss can be expressed as: \begin{equation} \text{Smooth}_{L_1}(x) = \begin{cases} 0.5x^2 &\text{if }|x|<1\\ |x|-0.5 & \text{otherwise}. \end{cases} \end{equation} \subsection{Box Parameters} To capture the oriented bounding boxes, one natural and straightforward way is to detect the width $w$, and height $h$, and angle $\theta$ of an OBB from the center point. We term this baseline method as Center$+wh+\theta$ (see Fig.~\ref{fig:figure1}a). This method has several disadvantages. First, a small angle variation has marginal influence on the total loss in training, but it may induce a large IOU difference between the predicted box and the ground-truth box. Second, for each object, the $w$ and $h$ of its OBB are measured in an individual rotating coordinate system that has an angle $\theta$ with respect to the $y$-axis. Therefore, it is challenging for the network to jointly learn the box parameters for all the objects. In this paper, we propose to use the box boundary-aware vectors (BBAVectors, see Fig.~\ref{fig:figure1}b) to describe the OBB. The BBAVectors contain the top $\textbf{t}$, right $\textbf{r}$, bottom $\textbf{b}$ and left $\textbf{l}$ vectors from the center points of the objects. In our design, the four types of vectors are distributed in four quadrants of the Cartesian coordinate system. All the arbitrarily oriented objects share the same coordinate system, which would facilitate the transmission of mutual information and therefore improve the generalization ability of the model. We intentionally design the four vectors instead of two (i.e., $\textbf{t}$ and $\textbf{b}$, or $\textbf{r}$ and $\textbf{l}$) to enable more mutual information to be shared when some local features are obscure and weak. The box parameters are defined as $\textbf{b}=[\textbf{t},\textbf{r},\textbf{b},\textbf{l},w_e, h_e]$, where $\textbf{t},\textbf{r},\textbf{b},\textbf{l}$ are the BBAVectors, $w_e$ and $h_e$ are the external horizontal box size of an OBB, as described in Fig.~\ref{fig:figure2}. The details of $w_e$ and $h_e$ are explained in Section \ref{sub: orientation}. Totally, the box parameter map $B\in \mathbb{R}^{10\times \frac{H}{s}\times \frac{W}{s}}$ has $10$ channels with $2\times4$ vectors and $2$ external size parameters. We also use a smooth $L_1$ loss to regress the box parameters at the center point: \begin{equation} L_{b} = \frac{1}{N}\sum_{k=1}^{N}\text{Smooth}_{L_1}(\mathbf{b}_k- \hat{\mathbf{b}}_k), \end{equation} where $\mathbf{b}$ and $\hat{\mathbf{b}}$ are the predicted and ground-truth box parameters, respectively. \subsection{Orientation} \label{sub: orientation} In practice, we observe that the detection would fail in situations where the objects nearly align with $xy$-axes (see Fig.~\ref{fig:figure4}b). The reason would be that at the boundary of the quadrant, the types of the vectors are difficult to be differentiated. We term this problem as corner cases (see Fig.~\ref{fig:figure1}c). To address this issue, in this work we group OBBs into two categories and process them separately. In particular, the two types of boxes are HBB and RBB, where RBB involves all the rotation bounding boxes except the horizontal ones. The benefit of such a classification strategy is that we transform the corner cases into the horizontal ones, which can be dealt with easily. When the network encounters the corner cases, the orientation category and the external size ($w_e$ and $h_e$ in Fig.~\ref{fig:figure2}) can help the network to capture the accurate OBB. The additional external size parameters also enrich the descriptions of an OBB. We define the orientation map as $\alpha\in \mathbb{R}^{1\times \frac{H}{s}\times \frac{W}{s}}$. The output map is finally processed by a sigmoid function. To create the ground-truth of the orientation class $\hat{\alpha}$, we define: \begin{equation} \hat{\alpha}=\begin{cases} 1 \text{ (RBB)} & \text{IOU(OBB, HBB)}<0.95\\ 0 \text{ (HBB)}& \text{otherwise}, \end{cases} \end{equation} where IOU is the intersection-over-union between the oriented bounding box (OBB) and the horizontal bounding box (HBB). The orientation class is trained with the binary cross-entropy loss: \begin{equation} L_{\alpha} = -\frac{1}{N}\sum_i^N(\hat{\alpha}_i\log(\alpha_i)+(1-\hat{\alpha}_i)\log(1-\alpha_i)), \end{equation} where $\alpha$ and $\hat{\alpha}$ are the predicted and the ground-truth orientation classes, respectively. \input{tables/table1.tex} \section{Experiments} \subsection{Datasets} We evaluate our method on two public aerial image datasets: DOTA \cite{xia2018dota} and HRSC2016 \cite{icpram17}. \paragraph{DOTA.} We use DOTA-v1.0 \cite{xia2018dota} dataset for the oriented object detection. It contains 2,806 aerial images with a wide variety of scales, orientations, and shapes of objects. These images are collected from different sensors and platforms. The image resolution ranges from $800\times800$ to $4000\times4000$. The fully-annotated images contain 188,282 instances. The DOTA-V1.0 has 15 categories: Plane, Baseball Diamond (BD), Bridge, Ground Track Field (GTF), Small Vehicle (SV), Large Vehicle (LV), Ship, Tennis Court (TC), Basketball Court (BC), Storage Tank (ST), Soccer-Ball Field (SBF), Roundabout (RA), Harbor, Swimming Pool (SP) and Helicopter (HC). The DOTA images involve the crowd and small objects in a large image. For accurate detection, we use the same algorithm as ROI Transformer \cite{ding2019learning} to crop the original images into patches. In particular, the images are cropped into $600\times600$ patches with a stride of 100. The input images have two scales $0.5$ and $1$. The trainval set and testing set contain 69,337 and 35,777 images after the cropping, respectively. The trainval set refers to both training and validation sets \cite{ding2019learning}. Following the previous works \cite{azimi2018towards,ding2019learning}, we train the network on the trainval set and test on the testing set. The detection results of cropped images are merged as the final results. Non-maximum-suppression (NMS) with a 0.1 IOU threshold is applied to the final detection results to discard repetitive detection. The testing dataset is evaluated through the online server. \noindent\paragraph{HRSC2016.} Ship detection in aerial images is important for port management, cargo transportation, and maritime rescue \cite{yang2018automatic}. The HRSC2016 \cite{icpram17} is a ship dataset collected from Google Earth, which contains 1,061 images with ships in various appearances. The image sizes range from $300\times300$ to $1500\times900$. The dataset has 436 training images, $181$ validation images, and $444$ testing images. We train the network on the training set and use the validation set to stop the training when the loss on the validation set no longer decreases. The detection performance of the proposed method is reported on the testing set. \subsection{Implementation Details} We resize the input images to $608\times 608$ in the training and testing stage, giving an output resolution of $152\times 152$. We implement our method with PyTorch. The backbone weights are pre-trained on the ImageNet dataset. The other weights are initialized under the default settings of PyTorch. We adopt the standard data augmentations to the images in the training process, which involve random flipping and random cropping within scale range $[0.9,1.1]$. We use Adam \cite{kingma2014adam} with an initial learning rate of $1.25\times 10^{-4}$ to optimize the total loss $L=L_h+L_o+L_b+L_{\alpha}$. The network is trained with a batch size of 20 on four NVIDIA GTX 1080 Ti GPUs. We train the network for about 40 epochs on the DOTA dataset and 100 epochs on the HRSC2016 dataset. We additionally report an experiment with a larger batch size 48 on 4 NVIDIA Quadro RTX 6000 GPUs, we mark the results with symbol $*$ in Table \ref{Table:Table1}. The speed of the proposed network is measured on a single NVIDIA TITAN X GPU on the HRSC2016 dataset. \subsection{Testing Details} To extract the center points, we apply an NMS on the output heatmaps through a $3\times 3$ max-pooling layer. We pick the top 500 center points from the heatmaps and take out the offsets ($\textbf{o}$), box parameters ($\textbf{b}$), and orientation class ($\alpha$) at each center point ($\textbf{c}$). The heatmap value is used as the detection confidence score. We first adjust the center points by adding the offsets $\tilde{\mathbf{c}} =\mathbf{c} + \textbf{o}$. Next, we rescale the obtained integer center points on the heatmaps by $\bar{\mathbf{c}} = s\tilde{\mathbf{c}}, s=4$. We obtain the RBB when $\alpha>0.5$, and we get the HBB otherwise. We use the top-left ($\textbf{tl}$), top-right ($\textbf{tr}$), bottom-right ($\textbf{br}$) and bottom-left ($\textbf{bl}$) points of the bounding box as the final decoded points. Specifically, for a center point $\bar{\mathbf{c}}$, the decoded RBB points are obtained from: \begin{align} \textbf{tl} &= (\textbf{t}+\textbf{l})+\bar{\mathbf{c}}, \quad \textbf{tr} = (\textbf{t}+\textbf{r})+\bar{\mathbf{c}}\nonumber\\ \textbf{br} &= (\textbf{b}+\textbf{r})+\bar{\mathbf{c}}, \quad \textbf{bl} = (\textbf{b}+\textbf{l})+\bar{\mathbf{c}}. \end{align} For a HBB, the points are: \begin{align} \textbf{tl} &= (\bar{c}_x-w_e/2, \bar{c}_y-h_e/2), ~\textbf{tr} = (\bar{c}_x+w_e/2, \bar{c}_y-h_e/2)\nonumber\\ \textbf{br} &= (\bar{c}_x+w_e/2, \bar{c}_y+h_e/2), ~\textbf{bl} = (\bar{c}_x-w_e/2, \bar{c}_y+h_e/2). \end{align} We gather the RBBs and HBBs as the final detection results. \subsection{Comparison with the State-of-the-arts} We compare the performance of the proposed method with the state-of-the-art algorithms on the DOTA and HRSC2016 datasets. To study the impact of orientation classification, we define two versions of the the proposed method: BBAVectors$+r$ and BBAVectors$+rh$. BBAVectors$+r$ only learns the box boundary-aware vectors to detect OBB, which contains box parameters $b=[\textbf{t}, \textbf{r}, \textbf{b}, \textbf{l}]$. BBAVectors$+rh$ additionally learns the orientation class $\alpha$ and the external size parameters ($w_e$ and $w_h$). \begin{figure*}[tbh!] \begin{center} \includegraphics[width=0.92\linewidth]{images/pic3.pdf} \end{center} \caption{Visualization of the detection results of BBAVectors+$rh$ on DOTA dataset.} \label{fig:figure3} \end{figure*} \paragraph{DOTA.} The detection results on the DOTA dataset are illustrated in Table~\ref{Table:Table1}. YOLOv2 \cite{redmon2017yolo9000} and FR-O \cite{xia2018dota} are trained on HBB \cite{xia2018dota} and their performances are comparably lower than the other methods. Notably, although the one-stage detector YOLOv2 runs faster, its accuracy is lower than the two-stage anchor-based detectors. R-DFPN \cite{yang2018automatic} learns the angle parameter from faster R-CNN \cite{ren2015faster} and improves performance from 54.13\% to 57.94\%. R$^2$CNN \cite{jiang2017r2cnn} pools multiple sizes of region proposals at the output of RPN and improves the accuracy from 57.94\% to 60.67\%. Yang \textit{et al}. \cite{yang2018position} use the adaptive ROI align to extract objects and achieve 1.62\% improvement over 60.67\%. ICN \cite{azimi2018towards} adopts the Image Cascaded Network to enrich features before R-DFPN and boost the performance from 62.29\% to 68.16\%. ROI Transformer \cite{ding2019learning} transfers the horizontal ROIs to oriented ROIs by learning the spatial transformation, raising the accuracy from 68.16\% to 69.56\%. Different from these methods, the proposed method offers a new concept of oriented object detection, a keypoint-based detection method with box boundary-aware vectors. As shown in Table \ref{Table:Table1}, Without orientation classification, the BBAVectors$+r$ improves 2.05\% over 69.59\% of ROI Transformer+FPN \cite{lin2017feature} and 3.87\% over 67.74\% of ROI Transformer without FPN. As the proposed method is single-stage, this result demonstrates the detection advantages of the keypoint-based method over the anchor-based method. With the orientation classification and additional external OBB size parameters ($w_e$ and $h_e$), the proposed BBAVectors$+rh$ achieves 72.32\% mAP, which exceeds ROI Transformer+FPN by 2.76\%. Besides, BBAVectors$+rh$ runs faster than ROI Transformer (see Table~\ref{Table:Table2}). With a larger training batch size, the BBAVectors$+rh^*$ achieves about 3 points higher than BBAVectors$+rh$. The visualization of the detection results of BBAVectors$+rh$ on DOTA dataset is illustrated in Fig.~\ref{fig:figure3}. The background in the aerial images is complicated and the objects are arbitrarily oriented with different sizes and scales. However, the proposed method is robust to capture the objects even for the tiny and crowd small vehicles. \paragraph{HRSC2016.} The performance comparison results between the proposed method and the state-of-the-arts on HRSC2016 dataset is illustrated in Table~\ref{Table:Table2}. The R$^2$PN \cite{zhang2018toward} learns the rotated region proposals based on VGG16 backbone, achieving 79.6\% AP. RRD \cite{liao2018rotation} adopts activate rotating filters and improves the accuracy from 79.6\% to 84.3\%. ROI Transformer \cite{ding2019learning} without FPN produces 86.2\%, while BBAVectors+$r$ achieves 88.2\%. BBAVectors$+rh$ performs slightly higher (0.4\% over 88.2\%) than BBAVectors$+r$. In the inference stage, the proposed method achieves 12.88 FPS on a single NVIDIA TITAN X GPU, which is 2.18x faster than ROI Transformer. \input{tables/table2.tex} \begin{figure}[tbh!] \begin{center} \includegraphics[width=0.95\linewidth]{images/pic4.pdf} \end{center} \caption{Comparison of BBAVectors+$r$ and BBAVectors+$rh$.} \label{fig:figure4} \end{figure} \subsection{Ablation Studies} \label{sub:ablation studies} We compare the performances of the proposed BBAVectors$+r$ and BBAVectors$+rh$ to study the impact of orientation classification. As we mentioned before, BBAVectors$+r$ refers to box parameters $b=[\textbf{t}, \textbf{r}, \textbf{b}, \textbf{l}]$. BBAVectors$+rh$ corresponds to $b=[\textbf{t}, \textbf{r}, \textbf{b}, \textbf{l}, w_e, h_e, \alpha]$. BBAVectors$+r$ has $274.01$MB parameters with $25.82\times 10^{9}$ FLOPs, while BBAVectors$+rh$ has $276.28$MB parameters and $27.68\times 10^{9}$ FLOPs. As can be seen in Fig.~\ref{fig:figure4}, the BBAVectors$+r$ can hardly capture the bounding boxes that nearly align with the $xy$-axes. These are the corner cases as discussed above. The reason for the failure detection would be that it is difficult for the network to differentiate the type of vectors near the quadrant boundary (i.e., classification boundary). To address this problem, we separate the OBB into RBB and HBB by learning an orientation class $\alpha$ and we use the external parameters ($w_e$ and $w_h$) to describe HBB. As illustrated in Fig.~\ref{fig:figure4}, the BBAVectors$+rh$ excels in capturing the oriented bounding box at the corner cases. On the DOTA dataset (see Table~\ref{Table:Table1}), the BBAVectors$+rh$ improves 0.71\% over BBAVectors$+r$. On the HRSC2016 dataset (see Table~\ref{Table:Table2}), BBAVectors$+rh$ achieves 0.4\% improvement over BBAVectors$+r$. \subsection{Comparison with Baseline} To explore the advantage of the box boundary-aware vectors, we also compare our method with the baseline Center+$wh$+$\theta$ (see Fig.~\ref{fig:figure1}a), which employs the width ($w$), height ($h$) and angle ($\theta\in(-90^\circ,-0^\circ]$) as the descriptions of OBB. Note that the baseline method shares the same architecture as the proposed method except for the output box parameter and orientation map. The training procedure is the same as the proposed method. Here we do not explicitly handle the corner cases for a fair comparison. From Table~\ref{Table:Table3}, we can see that the proposed method performs 4.82\% and 2.74\% better than Center+$wh$+$\theta$ on HRSC2016 and DOTA datasets, respectively. The results suggest that the box boundary-aware vectors are better for oriented object detection than learning the $w,h,\theta$ of OBB directly. The reason would be that the box boundary-aware vectors are learned in the same Cartesian coordinate systems, while in the baseline method, the size parameters ($w$ and $h$) of an OBB are measured in different rotating coordinate systems that have an angle $\theta$ with respect to the $y$-axis. Jointly learning those parameters would be difficult for the baseline method. \input{tables/table3.tex} \section{Conclusion} In this paper, we propose a new oriented object detection method based on box boundary-aware vectors and center points detection. The proposed method is single-stage and is free of anchor boxes. The proposed box boundary-aware vectors perform better in capturing the oriented bounding boxes than the baseline method that directly learns the width, height, and angle of the oriented bounding box. The results on the HRSC2016 and DOTA datasets demonstrate the superiority of the proposed method over the state-of-the-arts. \input{paper24.bbl} \end{document}
{'timestamp': '2020-09-01T02:07:10', 'yymm': '2008', 'arxiv_id': '2008.07043', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07043'}
arxiv
\section{Introduction} The measurement and definition of well-being, as referred to both individuals and societies, is a long-time debated topic that in recent times increasingly captured the attention of stakeholders and policy-makers \citep{sen1999commodities}. This interest has been mostly motivated by the broadening of well-being definition, going further than the usual economic status \citep{wesselink2007measurement}. Hence the need of finding measures other than the economic ones that could reflect the level of societal progress. In a society funded on the awareness that "what is being measured" has direct consequences on "what is done" \citep{commission2009report}, it is of primary importance to develop proper measurement tools that are capable to catch all relevant features of a complex phenomenon and such that assumptions and ideas are easily and clearly included. Such tools will allow policy-makers and stakeholders to make correct, transparent and efficient decisions. Since $2001$, the Organization for the Economic and Co-operation Development (OECD) recognized the importance of finding a proper way to measure social progress and promoted the international debate around its definition and measurement. With the "Istanbul Declaration", jointly signed in $2007$ by the European Commission, OECD, Islamic Conference Organization, United Nations Development Program (Undp) and World Bank, a first international consensus was reached on the necessity of measuring social progress in every Country embracing a vision capable of going beyond the use of the Gross Domestic Product (GDP). The most relevant contribution, in these terms, is that of the "Final report of Stiglitz-Sen-Fitoussi Commission" \citep{commission2009report}, where several recommendations are made. Firstly, the authors suggest to draft the focus from production to available income and consumption and to pay special attention to the distribution of wealth in the population. Secondly, well-being should be conceived as a \emph{multidimensional} phenomenon, and its measurement should contemplate citizen's subjective features, and include indicators specifically meant to capture economic, social and environmental sustainability. Other tangible initiatives soon followed, all aiming at establishing work directions towards the implementation of effective measurement of well-being. Among these, a round table arranged on the topic during G20 in Pittsburgh (2009), with the specific intent of extending the measurement of economic development in order to include social and environmental dimensions; and the European Commission's initiative "Not only the GDP", through which the European Commission and the member states committed to elaborate on specific aspects: 1) to complement GDP with social and environmental indicators; 2) to produce timely and effective measurements of the social and environmental aspects; 4) to give more precise measurements of wealth distributions and inequalities; 3) to come up with a possibly harmonized European table to evaluate social development. Noteworthy, this is also the framework in which looking at the Sustainable Development Goals (SDGs) defined in the 2030 Agenda signed by the United Nations in 2015, and aiming at defining goals and targets for all countries to reach, specifically highlighting the importance of sustainability as an inescapable characterization of the process of development. Multiple and diverse initiatives trying to implement the above-mentioned tasks and challenges followed, at both national and international levels. The "Canadian Index of Well-being" (Ciw), the "Measures of Australia’s Progress", the Buthan's "Gross National Happiness Index", the "Measuring National Well-being" project in the United Kingdom and the "Final Report adopted by the European Statistical System Committee", from the "Sponsorship Group on Measuring Progress, Well-being and Sustainable Development", are just some of them. Among the most ambitious initiatives attempting at measuring well-being, the Italian "Equitable and Sustainable Well-being" (BES) project finds its own place. The BES project started in $2010$, when a steering committee was formed by the joint effort of the Italian National Institute of Statistics (ISTAT) together with the National Council for Economics and Labour (CNEL) with the objective of elaborating on a system of indicators that would achieve a proper measurement of the Italian well-being. This experience was soon characterized by being widely shared among all interested social parties: field's experts, stakeholders, policy officials, statisticians, civil society's delegates and the citizens (through citizen's consultations). This choice was motivated by the consideration that the concept of well-being unavoidably changes across time, places and cultures, and thus it can only be defined together with all relevant social actors, fact that gives BES a remarkably democratic legitimacy. The BES system of indicators represents a unique chance to monitor all relevant aspects of well-being in the Italian context and this work aims at investigating possible relationships among the BES atomic indicators and the BES domains. In order to embrace the inherent multidimensionality of the BES system of indicators, the multivariate class of models of Bayesian Networks (BNs) has been implemented and different geographic scales have been tested in order to find the best grouping of the Italian regions that would allow for these relationships to emerge. The basic idea of BNs is to combine probability and graph theory by encoding the set of \emph{conditional independence relationships} among a set of variables in a graphical structure that can be easily read and interpreted. The graphical structure is made up of nodes and edges between pairs of node. Each variable is represented by a node in the graph and a missing edge between two nodes corresponds to a conditional independence relationship between the two variables. Compared to other classes of models, BNs seem to present some advantages. Unlike, for example, classical multiple regression models, BNs can also return indirect relationships mediated by third variables and do not need to calibrate the model by specifying one or more target variable, standing out as a more suitable tool to study a phenomenon from a \emph{systemic} point of view. If compared to other multivariate statistical models like, for example, factor analysis, BNs have the advantage of being able to build an entire system of relationships to be possibly used as a decision making tool. Moreover, if compared with Neural Networks (NNs), BNs can explicitly formalize the set of relationships among variables and, as a consequence, results are generally highly interpretable. In literature, the BES dataset has been inspected from several points of view: cluster analysis \citep{monte2017benessere}, factor analysis \citep{chelli2015comparing,chelli2016assessing, mazziotta2019use}, regression models \citep{istat2018benessere}, partial least squares path modeling \citep{davino2017quantile}. To the best of the authors' knowledge, this is the first time that the class of models of Bayesian Networks is considered for the BES dataset, even though its usage in the field of well-being was already suggested \citep{maggino2012measuring, ceriani2016multidimensional}. In this work, we implement Bayesian Networks for the BES atomic indicators in order to answer three main research questions: \begin{enumerate} \item What is the structure of the relationships, in terms of conditional independence statements, among the \emph{BES atomic indicators}? \item What is the role that the different \emph{BES domains}, as they are currently defined and formalized in the BES framework, play in the whole BES system of indicators and how do they relate to each other? \item To what extent the structure of the relationships reflect the current BES theoretical framework? \end{enumerate} The first two questions mainly refer to the possibility of identifying mechanisms that can guide resources' allocation in policy decision making. This specifically instantiates in pinpointing either BES atomic indicators or domains having a central role in spreading information over the network as well groups of either indicators or domains that strictly relate to each other. In order to distinguish the level of the analysis, by looking at either BES atomic indicators or BES domains of well-being, we do exploit the flexibility of Bayesian Networks in formalizing prior information and suggest two different prior strategies, with Strategy $1$ focusing exclusively on relationships among the BES atomic indicators and Strategy $2$ devoted to capture interrelations among the BES domains. In order to find the most suitable geographic scale through which looking at the above mentioned relationships, four different grouping options for the Italian regions were tested: regional (NUTS 2 level), macro-areas (NUTS 1 level: NW-NE-C-S-I), North/South and national. Considerations derived from implementing both prior settings will also allow to answer the third research question, which basically refers to the opportunity of highlighting some future directions for the BES system of indicators in light of the relationships arising from the network. The work will proceed as follows. In section $2$ we give an in-depth overview of the "Equitable and Sustainable Well-being" (BES) framework and report on the most important characteristics of the data. In section $3$ we briefly review the statistical tools of the Bayesian Network's methodology. In section $4$ we present results from implementation of the Bayesian Networks on the BES dataset. We conclude, in Section $5$, by commenting on the obtained results and suggesting some directions for future works. \section{Well-being as a multidimensional phenomenon: a change in perspective in the Italian context} \label{second} In order to reach a definition of well-being that could be appropriate for the Italian context, the starting point was the theoretical framework elaborated by OECD \citep{hall2010framework}, according to which specific domains and dimensions for the phenomenon are identified. In agreement with this framework, a preliminary distinction is made between Human well-being and Ecosystem well-being. Within the former, a further separation is also made between Individual and Societal well-being, both relying on three supporting pillars: culture, economy and governance. These pillars are not meant as final goals but rather as means to reach both Individual and Societal well-being. On the other hand, the Ecosystem well-being accounts for one domain, namely the one of environmental conditions and, evidently, important exchanges intervene between Human well-being and Ecosystem well-being, in terms of ecosystem's services and resources management. An important perspective through which considering this theoretical framework for the societal progress is that of its distribution, both across regions (space distribution) and generations (time distribution). The regional distribution is what has been identified as the \emph{equity} aspect that the definition of well-being necessarily must consider, hence the need for well-being to be \emph{equitable}. While the time (or inter-generational) distribution refers to the fact that the current well-being should guarantee the possibility to be maintained and augment also for future generations \citep{oposa1994defense, gardiner2011perfect}, from which the need for well-being to be also \emph{sustainable}. Grounded on this theoretical bases, the \emph{BES framework} consists of two different sets of domains. The first one comprises the \emph{outcome} domains, i.e. those domains that directly affect human and environmental well-being. A total of $12$ outcome domains have been pinpointed, namely: Health, Education, Work \& Life Balance (Quality), Work \& Life Balance (Employment), Economic Well-being (Min. Conditions), Economic Well-being (Income), Social Relationships, Security (Predatory Crimes), Security (Murders), Subjective Well-being, Landscape \& Cultural Heritage, Environment. Conversely, the elements of the second group are referred to as \emph{contextual} (or instrumental) domains, and they incorporate the functional elements that allow well-being to express, as regards both society and the environment. Within the BES framework, $3$ domains belong to this second group: Politics \& Institutions, Research, Innovations \& Creativity, Quality of Services. For each domain, a number of atomic indicators are selected in order to monitor all relevant features. At present, a total of $129$ atomic indicators have been identified and, among these, $61$ indicators are aggregated on a yearly basis into domain composite indicators by means of the \emph{Adjusted Mazziotta-Pareto Index} (AMPI) \citep{mazziotta2016generalized}, following criteria of timeliness, availability of the time series and capability at representing the different features of each domain. The Mazziotta-Pareto Index (MPI) works under the hypothesis that atomic indicators to by synthesized are not exchangeable and all have the same relevance. In its \emph{adjusted} version, an ad hoc normalization procedure is implemented in order to allow comparability across years \citep{de2009composite}. Henceforth, we will refer to the $61$ indicators considered for building the composite indicators as the \emph{BES atomic indicators}. Domains and corresponding atomic indicators used for the synthesis, are reported in Table \ref{tab:bes1} and Table \ref{tab:bes2} in Appendix. For all but three domains, one single composite indicator is computed, while for Work \& Life Balance, Economic Well-being and Security, two composite indicators are considered, to better represent heterogeneous attributes within the same domain \citep{istat2018benessere}. The measurement model used for the BES framework follows the so called \emph{formative} approach, since indicators are deemed to \emph{define} the latent trait representing the phenomenon, contrary to the \emph{reflexive approach}, according to which the phenomenon reflects into indicators \citep{maggino2017developing,diamantopoulos2001index, diamantopoulos2006formative}. This distinction has important consequences on the measurement model specification in terms of the relationship between indicators and the latent trait. In fact, within a formative approach indicators are not exchangeable, and a different set of indicators would result in a different operational definition (and thus a different value) for the latent trait being measured \citep{blalock2018causal}. Furthermore, indicators are not required to be correlated to each other (i.e. no internal consistency in terms of correlation is required) and, if any correlation shows up, it is not strictly explained by the model itself. For what the error term concerns, it only has a disturbing role within the measurement model. On the contrary, according to the reflective approach, indicators are exchangeable, must be correlated, the correlation is explained by the model and the error term plays a role in explaining the indicators' variance. It is worth mentioning that a long-term, yet on-going debate pertain to scholars of different views, about the superiority or even the suitability of one approach with respect to the other (see for example \citep{howell2007reconsidering, wilcox2008questions, bollen2017defense}. Some important characteristics of the BES atomic indicators employed to compute composite indicators immediately stand out, and we will briefly consider the main ones \citep{istat2015benessere}. First of all, the atomic indicators do not yearn for an exhaustive representation of the considered domain (for which a huge number of indicators should instead be envisioned), but rather aim at catching those aspects that mainly characterize the domain, while ensuring a timely monitoring and the proper geographic breakdown. Secondly, both objective and subjective indicators are used, in the belief that citizens' perceptions and opinions can complement knowledge about well-being, providing pieces of information that could not be added otherwise. Thirdly, all atomic indicators must encounter at least the regional disaggregation (NUTS2) level, possibly allowing the monitoring of the phenomenon in all its aspects also at a more local level. Lastly, indicators should allow for an analysis disaggregated at the level of some relevant structural variables (sex, age, education, social status, etc...) In this work, we deal with $61$ BES atomic indicators currently used to build composite indicators for each domain and we will sometimes refer to this set of indicators as the \emph{BES dataset} (Table \ref{tab:bes1} and Table \ref{tab:bes2} in Appendix). The Italian National Institute of Statistics (ISTAT) updates the time series of the BES atomic indicators at the regional level on a yearly basis, starting from $2010$. Therefore, the available BES dataset comprises values for the $61$ atomic indicators for the $20$ Italian regions for a period of eight years, from $2010$ to $2017$, for a total of $160$ observations. Although it is usually common to consider the BES atomic indicators as synthesized into composite indicators, one for each domain (see Section \ref{second}), in this work information will be kept at the atomic indicators level, with the twofold intention of not (potentially) loosing information along the synthesis process and deal with variables whose meaning is maximally clear and transparent. However, it will also be shown how the theoretical framework of the $61$ atomic indicators organized into $15$ well-being domains can conceivably be incorporated into the BN learning scheme and what kind of information it is possible to gain out of it. \section{Methodology} \subsection{Bayesian Networks} \label{BN} Bayesian Networks models (or Bayesian Networks, shortly BNs) are a class of multivariate statistical models that allow for the representation of probabilistic relationships among a set of variables by means of a graph \citep{ lauritzen1996graphical, pearl2014probabilistic, neapolitan2004learning, koller2009probabilistic}. Bayesian Networks have been extensively applied in a variety of fields, from genomic and gene expression analysis \citep{friedman2000using, rodin2005mining, scutari2014multiple} to official statistics \citep{sebastiani2001use, penny2004using}, ecology \citep{milns2010revealing,hradsky2017bayesian}, fault diagnosis \citep{helldin2009explanation}, healthcare \citep{lappenschaar2013multilevel, van2014learning} and climate data applications \citep{ebert2012causal, molina2013dynamic, vitolo2018modeling}. The present section aims at providing the fundamental elements for understanding Bayesian Networks. For a complete theoretical treatise, we refer to the well established literature \citep{lauritzen1996graphical, pearl2014probabilistic, koller2009probabilistic, whittaker2009graphical, scutari2014bayesian, cowell2006probabilistic}. Given a set $\mathbf{X}=(X_{1}, \dots, X_{n})$ of random variables, a Bayesian Network is defined by specifying \begin{itemize} \item A graph $G= (V, E)$, where $V$ is a set of vertices (or nodes), one for each random variable in $\mathbf{X}$ (nodes and random variables are used interchangeably), while $E \subseteq V \times V$ is a set of edges (links) connecting pairs of different nodes. For a BN to be properly specified, the graph $G$ must be a \emph{directed} and \emph{acyclic} (shortly, a DAG). \item A multivariate probabilistic distribution defined over $\mathbf{X}$, called the \emph{global} distribution. The univariate distributions associated to each $X_{i}$ are called \emph{local} distributions. \end{itemize} Let $\alpha,\beta \in V$ be two vertices, we write $\alpha \to \beta$ if an arrow exists going from $\alpha$ to $\beta$. In this case we call $\alpha$ the \emph{parent} node and $\beta$ the \emph{children} node. The set of parents of a node $\beta$ is denoted as $pa(\beta)$ and the set of children of a node $\alpha$ is denoted as $ch(\alpha)$. A \emph{path} from $\alpha \in V$ and $\beta \in V$ is a sequence $\alpha = \alpha_{0}, \dots, \alpha_{n} = \beta $ of distinct vertices such that $(\alpha_{i-1}, \alpha_{i}) \in E$, for all $i= 1,\dots,n$. If there is a path from $\alpha$ to $\beta$, we say that $\alpha$ \emph{leads} to $\beta$ and we write $\alpha \mapsto \beta$. On the contrary, those nodes $\beta$ for which no path exists leading from $\alpha$ to $\beta$ are said to be \emph{non-descendants}. A central property for Bayesian Networks is the so called the (local) \emph{Markov property}, according to which each variable $X_{i}$ is conditionally independent of its non-descendants given its parents. As a consequence of both the Markov property and the chain rule, the joint distribution can be conveniently factorized into a product of marginal/conditional distributions \citep{lauritzen1996graphical}, which is certainly one of the most relevant features of Bayesian Networks. In fact, it allows algorithms to scale to fit high-dimensional data and avoid incurring in the so called \emph{curse of dimensionality} \citep{ wainwright2008graphical, jordan1998learning, kolar2013uncovering}. Ultimately, the DAG being acyclic guarantees that factorizations are indeed well defined. The possibility of establishing a link between graphical structures and probabilistic properties is made possible by defining a suitable concept of \emph{graphical separation} for subsets of nodes in a graph (the so called \emph{$d$-separation}, and then relating it to the well known conditional independence property for a set of random variables (for more details on this aspect, please refer to \citep{lauritzen1996graphical,koller2009probabilistic}). Remark that perhaps the most informative feature of an edges set is the absence of an edge: if two nodes $X_{i}$ and $X_{j}$ are not connected by an edge, then the two random variables are either marginally or conditionally independent (i.e. they are independent when conditioning on a subset of the remaining variables). On the other hand, the presence of an edge connecting two nodes in the graph reflect possible conditional dependencies between the two variables. In fact, after a Bayesian Network is estimated from a real dataset, \emph{an evaluation step} performed by field experts should follow, in order to better understand the final results \citep{ebert2015using}. Some of the connections could for example be confirmed by the scientific literature on the relative field and, if that is the case, the edges could indeed be thought of as corresponding to specific \emph{mechanisms in action}. On the contrary, if literature cannot confirm a connection, this could potentially shed light on (maybe new) hypothesis to be tested by future works. \subsubsection{Fundamental Connections} \label{fundamental_connections} It is possible to think of the graphical structure of a BN as it was built upon some "building blocks" known as the \emph{fundamental connections} \citep{whittaker2009graphical, scutari2014bayesian}. These are the only possible configurations for three nodes and two edges and they are (see Figure \ref{fig:struct}) \begin{itemize} \item \emph{Converging} connections: structures of the type $X \to Z \gets Y$. A converging connection where $X$ and $Y$ are not connected is said to be a \emph{$v$-structure}. \item \emph{Serial} connections: structures of the type $X \to Z \to Y$. \item \emph{Diverging} connections: structures of the type $X \gets Z \to Y$. \end{itemize} \begin{figure} \centering \includegraphics[width=10 cm,height=8 cm,keepaspectratio]{Fig1.eps} \caption{Bayesian Networks' three fundamental connections: a) serial connection; b) diverging connection; c) converging connection.} \label{fig:struct} \end{figure} The three connections represent different probabilistic relationships by means of different graphical structures. In converging connections, the graph is associated with the marginal independence statement $X \perp \!\!\! \perp_{P}Y$ while, when conditioning on the value of the variable $Z$, $X$ and $Y$ become conditionally dependent. Furthermore, the joint distribution factorizes as $P(X,Y,Z) = P(X)P(Y)P(Z|X,Y)$. In serial and diverging connections, the missing edge between nodes $X$ and $Y$ corresponds to the conditional independence statement $X \perp \!\!\! \perp_{P}Y|Z$ and, for both kinds of connections, the joint distribution factorizes as $P(X,Y,Z) = P(X)P(Z|X)P(Y|Z) = P(Z)P(X|Z)P(Y|Z)$. Therefore serial and diverging connections - albeit different graphical structures - encode the same conditional independence relationships and thus reveal the same factorization for the joint distributions. Such graphical structures are said to be in the same \emph{equivalence class} \citep{frydenberg1990chain, verma1991equivalence}. \subsubsection{In-degree, Out-degree and Markov Blanket size} \label{MB} When reading information out of a network, it is relevant to quantify the degree of connection of each node to the whole network which in turn allows to characterize the different roles that the nodes fulfill. There are different ways for quantifying the degree of connection of a node and the in-degree, out-degree and Markov blanket size are among the more explicative and more easily interpretable ones. The \emph{in-degree} of a node is the number of edges pointing to that node, while the \emph{out-degree} of a node is the number of edges departing from that node. In order to define the Markov blanket (and thus the Markov blanket size) of a node, we should refer to the concepts introduced in the last paragraphs. The joint distribution and density factorization derived from the Markov property, and discussed in the previous paragraph, provide a very convenient way to describe (and define) a BN. Nonetheless, when making inference about a node $X_{i}$, information about some other nodes beside its parents can reveal useful. In the limit case we could simply add all nodes in the graph but, among them, we know there might be some that are d-separated from $X_{i}$ and therefore, conditionally independent on $X_{i}$. For this purpose, a useful concept derived from the notion of d-separation and playing a central role in Bayesian Networks is that of \emph{Markov Blanket}. The Markov blanket of a node $X_{i}$ is the union of its parents, its children and its children's other parents and it corresponds to the set of nodes that makes all other nodes redundant when performing inference on a specific node (see Figure \ref{fig:mb}). It is worth noticing however, that not all nodes in the Markov Blanket of a node are necessarily required to get complete probabilistic independence between $X_{i}$ and the nodes that are not in its Markov Blanket. Furthermore, the definition is symmetric: if a node $X_{j}$ is in the Markov Blanket of a node $X_{i}$, then the node $X_{i}$ is in the Markov Blanket of $X_{j}$. The interpretation of the above mentioned measures of connection of a node to the whole network is straightforward. While the in-degree measures the number of nodes which have direct influence on a particular node (parent nodes), the out-degree measures the number of nodes that a particular node can directly influence (children nodes). On the other hand, the Markov blanket size of a node is always equal or greater than the sum of its in-degree and out-degree, since it is the sum of the number of its parent nodes, children nodes and the other parents of the children nodes. The Markov blanket size of a particular node is thus the number of nodes in the network that are involved in some conditional dependence relationship with it \citep{koller2009probabilistic}. \begin{figure} \centering \includegraphics[width=7 cm,height=6 cm,keepaspectratio]{Fig2.eps} \caption{A directed acyclic graph (DAG) with eleven nodes. \normalsize{The Markov blanket of node $X_{3}$ comprises the nodes in the blue region: its parents $\{X_{1}, X_{2}\}$, its child $\{X_{4}\}$ and its child's other parents $\{X_{8}, X_{9}\}$. }As per the local Markov property, the global probability distribution factorizes as \footnotesize{$P(\mathbf{X}) = P(X_{1})P(X_{2})P(X_{6})P(X_{7})P(X_{8}|X_{6})P(X_{3}|X_{1}, X_{2})P(X_{9}|X_{2}X_{7})P(X_{10}|X_{7})P(X_{4}|X_{8}X_{3}X_{9})P(X_{11}|X_{9})P(X_{5}|X_{4})$}.} \label{fig:mb} \end{figure} \subsubsection{Types of BNs} \label{sec:type_of_BN} Depending on the nature of the variables included in the model, we distinguish between: \begin{enumerate}[label={\arabic*.}] \item \textbf{Discrete BNs}: all nodes are discrete variables \item \textbf{Continuous BNs}: all nodes represent continuous variables \item \textbf{Hybrid BNs}: nodes can represent either discrete or continuous variables. \end{enumerate} Moreover, looking at the temporal characterization of the phenomenon, it is possible to consider: \begin{enumerate}[label={\arabic*.}] \item \textbf{Static BNs}: the temporal dependence is not accounted for by the model and observations must be stochastically independent. \item \textbf{Dynamic BNs}: the system evolves over time and the temporal dependence is accounted for by the model. The most common procedure to model a phenomenon dynamically by means of BNs requires to duplicate the original variables. That is, given $N$ variables considered at $S$ different lagged times, the resulting dynamical BN would have a total of $N\times S$ nodes to deal with \citep{ebert2012new}. Due to such an increase in the number of variables, the dynamic model commonly requires a bigger sample size, compared to the static case, in order to yield valid and reliable results. \end{enumerate} \subsubsection{Estimating a Bayesian Network}\label{dynamic} estimating a Bayesian Network firstly requires to estimate the network structure (equivalent to the usual model selection problem) and secondly estimate the parameters of the global distribution. \paragraph{Structure learning} In literature, algorithms for structure learning of a BN are generally classified into three different classes, depending on the adopted approach: constraint-based algorithms, score-based algorithms and hybrid algorithms \citep{zhou2011structure}. In this work we adopt a score-based approach by implementing the Hill-Climbing algorithm with $r=2$ random restarts \citep{scutari2014bayesian}. A score-based algorithm assigns each network a score (here the Bayesian Information Criterion (BIC)) and explores the DAGs' space in search for the structure that maximizes this score \citep{russell2016artificial}. Since the number of DAGs grows more than exponentially in the number of nodes, an exhaustive search in the space of all possible DAGs is barely feasible in practice. This is the reason as to why resorting to heuristic search algorithms, such as the Hill-Climbing, is very common in applications. More specifically, the Hill Climbing algorithm explores the DAGs space starting from a network, usually the one with no edges, and then adds, removes or reverses one edge at a time until the maximum gain in terms of the score is reached. Being the search strategy of a local type, there is no guarantee that the final structure recovered is indeed a global optimum. Therefore, in order to escape \emph{local optima}, further steps can be implemented such as \emph{random restarts} , that consist in randomly changing some arcs in the current optimal DAG, up to a number $r$ of times (see details in Algorithm \ref{algo:b}). \begin{algorithm} \label{hill-climbin} \DontPrintSemicolon \begin{enumerate} \item Start from a a graph $G$ (usually the empty graph) \item Compute $score_{G} = score(G)$ \item Set $maxscore = score_{G}$ \item Perform the following operations as long as $maxscore$ increases: \begin{enumerate} \item for each possible arc addition, deletion or reversal that results in a DAG \begin{enumerate} \item Compute the score $score(G^{*})$ of the modified structure $G^{*}$ \\and set $score_{G^{*}}= score(G^{*})$ \item if $score_{G^{*}}> score_{G} $, set $G = G^{*}$ and $score_{G} = score_{G^{*}}$ \end{enumerate} \item Update $maxscore = score_{G}$ \end{enumerate} \item Up to $r$ times, perturb $G$ by adding, deleting and reversing multiple edges to obtain \\ a new DAG $G^{*}$ and search from step (IV). \item Return the DAG $G$. \end{enumerate} \caption{Hill Climbing algorithm with $r$ random restart \citep{scutari2014bayesian}} \label{algo:b} \end{algorithm} \paragraph{Parameter learning} After estimating the structure of a BN, it is possible to complete the description of the model by estimating the parameters of the global probability. Depending on the variables nature, the three most common choices in literature, for which exact inference is indeed possible, are: Multinomial Bayesian Networks (all variables are discrete), Gaussian Bayesian Networks (all variables are continuous) and Conditional Linear Gaussian Bayesian Networks (CLGBNs) (variables can be either discrete or continuous) \citep{lauritzen1996graphical, scutari2012bnlearn}. Since we deal with both discrete and continuous variables, in this work we adopt Conditional Linear Gaussian Bayesian Networks. According to this model, the global probability distribution is assumed to be a mixture of multivariate Gaussian distributions with the constraint that continuous nodes cannot be parents of discrete nodes \citep{lauritzen1989graphical}. Additionally, the local distribution of a discrete node is a \emph{conditional probability table}, while the local distribution of a continuous node is a \emph{set of linear regression models}, one for each configuration of the discrete parents, with the continuous parents acting as regressors. Therefore, all probabilistic dependencies between continuous variables are assumed to be linear \citep{scutari2012bnlearn}. \subsubsection{Encoding prior information in the learning algorithm} \label{par:prior_info} Both steps relating to structure and parameter estimation can be performed through numerical algorithms only (\emph{unsupervised learning}), or by combining algorithms that learn from the data with some sort of prior information on the phenomenon under investigation (\emph{supervised} learning). In the context of structure learning, prior knowledge usually takes the form of specific edges that should or should not be present in the net \citep{scutari2012bnlearn}. The former case corresponds to providing the learning algorithm with a \emph{whitelist} that specifies the edges that must necessarily be present in the final DAG: they might be known from the literature or there might be a well established framework for the phenomenon under study that suggests the presence of specific edges. On the contrary, if prior knowledge is available in terms of connections that are not plausible, the learning algorithm is provided with a \emph{blacklist} that prevents some edges from being in the final DAG. This is the case, for instance, of connections that are reputed as incoherent or impossible, or hard to be interpreted. As a direct consequence of including such prior information, the size of the space of DAGs is reduced, which generally helps to recover a better structure. The possibility of including prior information in terms of either a whitelist or a blacklist makes Bayesian Networks a very flexible class of models for real applications. \subsubsection{Reliability of the estimated network } In order to reduce model uncertainty derived from possible noise in the data and improve reliability of the learned structure, we adopt a \emph{model averaging approach} \citep{claeskens2008model, friedman1999learning, friedman1999data}. In place of estimating a single network structure from the data, a number $M$ of bootstrap datasets are created by resampling from the initial one and $M$ (possibly different) network structures (i.e DAGs) are learned, one for each bootstrap dataset. From the $M$ learned structure, it is then possible to compute the relative frequency of each edge, called \emph{arc strength}, and choose only those edges that exceeds a fixed \emph{threshold}. The final network will thus comprise only those edges that are present in a "sufficiently large number" of estimated DAGs and, as a consequence, will generally be less sensitive to the noise in the data and perform better in prediction than the single models. A generally accepted "rule of thumb" for what the threshold should be suggests to keep only those edges that are present in at least $85\%$ of the learned DAGs, i.e. whose arc strength is larger than $0.85$. These arcs are then incorporated in the final network as directed edges with a specified direction if, conditioning on the edge's presence, this direction has a relative frequency bigger than $0.7$. Should this not be the case, the edge would be undirected \citep{scutari2014bayesian}. All analysis were done in R 2.14.0. The \emph{bnlearn} package \citep{scutari2012bnlearn} was used for Bayesian Network estimation, the \emph{bestNormalize} package \citep{peterson2018bestnormalize} for variables' normalization and the \emph{bnstruct} package \citep{franzin2016bnstruct} for handling missing values by means of the KNN algorithm. \section{Results: applications of Bayesian Networks to the BES data} In this work, we implement Bayesian Networks for the BES atomic indicators in order to answer three main research questions: \begin{enumerate} \item What is the structure of the relationships, in terms of conditional independence statements, among the \emph{BES atomic indicators}? \item What is the role that the different \emph{BES domains}, as they are currently defined and formalized in the BES framework, play in the whole BES system of indicators and how do they relate to each other? \item To what extent the structure of the relationships reflect the current BES theoretical framework? \end{enumerate} For the purpose of satisfactorily answering the above inquiries, we deal with static, hybrid BNs that also incorporate geographic information and suggest two different strategies to encode prior information in the learning algorithm. The choice of static BNs was made in light of the small available time-window for the BES data ($8$ years) and the fact that this entirely falls into the western economic crisis started in $2008$. The assumption of time homogeneity and the consequent choice of a static BN thus seemed to be reasonable, beside meeting the limitations of a small sample size (see section \ref{sec:type_of_BN}). Nonetheless, following, among others, \citep{vitolo2018modeling}, we still take into account - and partly model - some time dependency by considering the node YEAR as a discrete variable taking values in the set $\{2010,2011,2012,2013,2014,2015,2016,2017\}$. Hence, the choice of a hybrid BN. On the side, in order to deal with both discrete and continuous variables, the Conditional Linear Gaussian Bayesian Network model was implemented by means of the Hill-Climbing algorithm with $2$ random restarts and the BIC score. For the purpose of diminishing the noise present in the data and increase reliability of the estimated network, a model averaging approach was adopted, repeating the estimation procedure $1000$ times over $1000$ bootstrap samples from the original dataset and retaining only those edges that appeared in at least $85\%$ of the estimated structures. Additionally, we incorporate geographic information in the model and, in order to consider the most suitable geographic scale, four different geographical groupings of the Italian regions are contemplated and compared: \begin{description} \item[\textbf{Regional (NUTS 2 level)}] Geographic information is kept at the regional level and therefore the dataset consists of $63$ variables: $61$ continuous BES atomic indicators and $2$ discrete variables, namely YEAR and the spatial node REGION that takes up to $20$ different values (the number of the Italian regions). As the BES database provided by ISTAT is built at the regional level (see section \ref{second}), this scenario corresponds to the finest geographical partition that is possible to contemplate in the analysis. \item [\textbf{Macro-Areas (NUTS 1 level: NW-NE-C-S-I)}] In this scenario, BES atomic indicators are aggregated according to the NUTS 1 level macro-areas for the Italian peninsula. Therefore, the dataset consists of $63$ variables: $61$ continuous BES atomic indicators and $2$ discrete variables, namely YEAR and AREA, the last one taking values in \{North-West, North-East, Centre, South, Islands\}. \item [\textbf{North/South}] Italian regions are grouped according to the dichotomy North/South. Thus, the dataset consists of $63$ variables: $61$ continuous BES atomic indicators and $2$ discrete variables, namely YEAR and AREA, the last one taking values in \{North, South\}. \item [\textbf{National}] According to this scenario, no relevant differences among regions exist and no spatial label is added to the data, that therefore consists of a total of $62$ variables: $61$ continuous BES atomic indicators and the YEAR discrete variable. This scenario corresponds to a minimum of geographic information to include in the analysis. \end{description} Finally, we did exploit the possibility of including prior information by formalizing blacklists and whitelists to pass to the learning algorithm (see Section \ref{par:prior_info}) and we suggest two different strategies aimed at analyzing relationships between the BES atomic indicators and relationships between the BES domains: \paragraph{Strategy 1: blacklist only.} Prior knowledge takes the form of a blacklist of edges that are not allowed to be in the final network. Two groups of blacklisted edges are considered. The first group is made up of those edges that, in compliance with the restrictions from the CLGBN model, for which discrete node cannot be children of continuous nodes, are of the type $X\to Y$ where $X$ is continuous (i.e. $X$ is any BES atomic indicator) and $Y$ is discrete (i.e. $Y$ is either the variable YEAR or REGION/AREA). In the context of the present application, this assumption seems perfectly reasonable, since it represents the logical assumption that nor temporal or geographical variable can ever be influenced by the BES atomic indicators. In addition to this first group of blacklisted edges, we also formalised a list of connections between BES atomic indicators considered as either unrealistic or incoherent and that, for this reason, should not be present in the final DAG. The complete list of the denied edges belonging to this second group can be found in Table \ref{blacklist} in Appendix. \paragraph{Strategy 2: blacklist and whitelist.} Both a blacklist and a whitelist are passed to the estimation algorithm. The blacklist is exactly the same as the one defined for Strategy $1$. On the other hand, the whitelist is built to reflect the hierarchical BES framework that relates the $61$ atomic indicators to $15$ different well-being domains and consists of all edges between pairs of atomic indicators belonging to the same domain. The usage of such a whitelist allows to investigate the relationships between the BES domains as they are currently formalized within the BES framework \citep{istat2018benessere}. In fact, from the point of view of the implemented score-based learning algorithm (Hill-Climbing with random restarts and BIC score), the introduction of a whitelist of edges between indicators in the same domain results in the algorithm choosing a smaller number of edges between indicators from different domains, if compared to the case of prior information consisting of a blacklist only. Clearly, this is ultimately due to the penalization mechanism brought about by the BIC used to score each network in the greedy search, which penalizes networks with a bigger number of parameters (that is, for a fixed number of nodes, networks with a bigger number of edges). As a consequence, a minor number of connections among different domains are expected, that will thus correspond to the strongest interactions in play, with the resulting network being able to provide a concise and clear picture of the interrelationships among well-being domains. As a final remark, it is worth noticing that the usage of a whitelist defined in terms of edges between atomic indicators to inspect connections among domains can be considered as alternative to directly resorting to domain composite indicators, thus avoiding to potentially loose information along the synthesis process and dealing with variables whose meaning is maximally clear and transparent. The two prior strategies should not be seen as competing, as they are designed to answer different questions. Specifically, Strategy $1$ focuses on the relationships between atomic indicators and was implemented to answer the first research question, while Strategy $2$ aims at investigating connections among the different BES domains, as they are currently defined in the BES framework, and hence is devoted to answer the second question. These two first questions ultimately intend to scrutinize some of the mechanisms underlying the Italian regional well-being and therefore potentially give a contribution for the complex task of resources' allocation in policy decision making. Considerations derived from implementing both prior settings will then allow to answer the third research question, basically referring to the opportunity of highlighting some future directions for the BES system of indicators in light of the relationships arising from the network. \subsection{Pre-processing} The data pre-processing involved a step of missing values imputation and a step of variables' transformation to meet the Gaussianity assumption on the continuous variables required by the Conditional Linear Gaussian Bayesian Network (CLGBN) model. A total of $103$ missing values occurred in the $160\times 61$ data matrix, (the $1\%$ of the whole dataset). Imputation of missing values was accomplished by K-Nearest Neighbour (KNN) algorithm \citep{duda2012pattern} and each missing value was substituted by the median of its $10$ nearest neighbours selected according to the Heterogeneous Euclidean-Overlap Metric (HEOM) distance \citep{wilson1997improved, franzin2016bnstruct}.\footnote{ According to this distance, given a set of continuous variable (or features) and two observations $x$ and $y$, the contribution of each feature to a measure of closeness between $x$ and $y$ is set to $1$ if the feature exhibits missing values in either $x$ or $y$ while, if values are not missing, it corresponds to their difference normalized by the feature range. To come up with a final distance between $x$ and $y$, all features' contributions are then aggregated by means of the euclidean distance.} In order to meet the Gaussianity assumption, a set of transformations, including the logarithmic, arcsin, square root, Box-Cox, Yeo-Johnson and the Ordered Quantile technique transformations were tested over each continuous variable, choosing the one that best performed according to the Pearson $P$ statistic for normality (see Tables \ref{gauss_1} and \ref{gauss_2} in Appendix) \citep{d1986goodness, peterson2019ordered, peterson2018bestnormalize}. \subsection{Bayesian Network Estimation} The structure learning algorithm was implemented for all four geographic scenarios (regional, macro-areas, North/South, national) with prior information encoded according to both Strategy $1$ and Strategy $2$, for a total of $8$ estimated networks. In order to adopt the most suitable geographical scale, a model choice was performed separately for each prior strategy by computing the Bayesian Information Criterion (BIC) and the Akaike Information criterion (AIC). In conformity to \citep{scutari2012bnlearn}, in this application AIC and BIC ($AIC= 2k-ln(\hat{L})$, $BIC = kln(n)-2ln(\hat{L})$), were rescaled by a factor -2, i.e. using $AIC = ln(\hat{L})/2- k$ and $BIC = ln(\hat{L})-kln(n)/2$, where $\hat{L}$ is the maximized value of the likelihood function of the model, $k$ is the number of parameters and $n$ the number of observations. Therefore larger values are preferred over smaller values. Additionally, predictive accuracy for each network was assessed through $k$-fold cross validation ($k=10$), by computing the average (among the continuous nodes) \emph{Posterior Mean Squared Error (MSE)} between the observed and the predicted values. The smaller this value, the higher the accuracy of the network. Table \ref{good} shows goodness-of-fit and predictive accuracy for each one of the eight estimated networks. The most appropriate configuration - among those tested - turned out to be the macro-areas subdivision (NUTS 1 level: NW-NE-C-SI) for both prior strategies. This geographic grouping outperformed the others in terms of both BIC and AIC while still resulting in good prediction accuracy in terms of the Posterior MSE. The estimated networks corresponding to this geographic scale and the two prior strategies are analyzed in the following paragraphs. \subsubsection{Relationships among the BES atomic indicators: implementation of Strategy 1} In order to answer the first research question about the structure of the relationships, in terms of conditional independence statements, among the BES atomic indicators, BNs were estimated by encoding prior information according to Strategy $1$. Figure \ref{fig:strategy_1} shows the network estimated in the prior setting induced by Strategy $1$ and corresponding to the Italian regions grouped into five macro-areas (NUTS 1 level: NW-NE-C-S-I). The analysis of the network will contemplate the network's topological configuration (analysis of the connected components) as well as the inspection of central nodes and particularly interesting structures among groups of nodes. As far as the topology of the estimated network is concerned, it is possible to notice that, apart from $12$ isolated nodes (nodes that are not connected with any other node), the remaining of the $63$ nodes are grouped into $4$ major connected components, i.e. groups of nodes for which it is possible to go from one node to another one through edges that connect nodes in that group only. The larger connected component in this network is the one for which the geographic variable (AREA) is one of the root nodes (considering the nodes reordering in accordance to the arcs' direction). The relevance of considering the geographic position of the Italian regions, and specifically their grouping according to the NUTS 1 level, is revealed by the central role that the geographic variable has in this connected component. In fact, $21$ indicators pertaining to $10$ out of the $15$ BES domains have a \emph{direct connection} with the variable AREA while, if we also look at \emph{indirect connections}, i.e. connections that are mediated by some other node, the variable AREA turns out to influence $41$ out of the $61$ BES atomic indicators, for a total of $12$ affected BES domains. This result seems to be clearly interpreted as almost all features of well-being for the Italian regions showing differences that can exclusively (direct connections) or partly (indirect connections) be explained by the geographic position. Furthermore, almost all domains show to be connected among each other, in a way that intrinsically depends on which macro-area the regions belong to. This result is somehow expected, being very much consistent with the current inequality literature between, for example, northern and southern Italian regions, with southern regions generally suffering more from low employment rate and bad economic conditions \citep{checchi2010inequality,ferrara2019does, panzera2019measuring}. Interestingly, only three domains do not show a clear relationship with the geographic variable AREA, namely Health, Subjective Well-being and Security (Murders). Understanding the reason for this lack of connection is certainly of relevance within the well-being reasoning. A lack of influence of the variable AREA over these domains of well-being might indeed be motivated by these features being predominantly region-specific, with relevant differences even among regions belonging to same NUTS 1 level macro-area. Additionally, further investigation should also explore the possibility of some important variables being missing in the set of the BES atomic indicators currently used to build the estimated network, or even the opportunity for non-linear relationships that the current model (the CLGBN model) cannot recognize. The remaining three connected components formed by more than one node are smaller in size than the first component just considered and only refer to one or maximum two different BES domains. In fact, the connected components $\{$\emph{Economic Difficulties, Low Quality House}$\}$ and $\{$\emph{Friendship Satisfaction, Family Satisfaction}$\}$, respectively refer to the Economic Well-being (Min. Conditions) and Relationship domains, while the component $\{$\emph{Parliament Trust, Parties Trust, Judicial System trust, Life Satisfaction}$\}$ includes variables from the Politics and Subjective Well-being domains. Finally, the presence of nodes that are not connected to any other node should be interpreted as these variables being independent of any other variable in the network. These are therefore variables that are potentially able to bring an exclusive contribution to the picture of the Italian regional well-being, by providing pieces of knowledge that are not related to the other considered aspects of well-being in terms of conditional independence relationships. This is the case for the set of indicators \{\emph{Income Inequality, Material Deprivation, Nursery School, Services Access Difficulty, Prison Overcrowding, Civic \& Political Participation, Other Institution Trust, Killings}\}, and all indicators in the Health domain, namely \{\emph{Life Expectancy at Birth, Life Expectancy in good health at Birth, Life Expectancy without activity limitations at 65 years of age}\}. The node YEAR is also an isolated node, meaning that no aspect of well-being is significantly influenced by the time variable, in the considered time window. This result supports our time-homogeneity assumption. \begin{table} \caption{Goodness-of-fit and Predictive Accuracy of the estimated Bayesian Networks. In conformity to \citep{scutari2012bnlearn}, in this application AIC and BIC ($AIC= 2k-ln(\hat{L})$, $BIC = kln(n)-2ln(\hat{L})$), were rescaled by a factor -2, i.e. using $AIC = ln(\hat{L})/2- k$ and $BIC = ln(\hat{L})-kln(n)/2$, where $\hat{L}$ is the maximized value of the likelihood function of the model, $k$ is the number of parameters and $n$ the number of observations. Therefore larger values are preferred over smaller values.} \label{good} \centering \begin{tabular}{cc|c|cc} \\[-1.8ex]\hline \hline \\[-1.8ex] & Spatial & BIC & AIC & Posterior \\ & Scale & & & MSE \\ \midrule & Regional & -11938 & -10843 & 0.239 \\ Strategy 1 & \textbf{NW-NE-C-S-I} & \textbf{-10969} & \textbf{-10344} & 0.293 \\ & N-S & -11380 & -11061 & 0.297 \\ &National & -11433 & -11116 & 0.546\\ \midrule & Regional & -11503 & -10618 & 0.365 \\ Strategy 2 & \textbf{NW-NE-C-S-I} & \textbf{-10238} & \textbf{-9206} & 0.383 \\ & N-S & -10359 & -9680 & 0.391 \\ &National & -10588 & -10041 & 0.380\\ \midrule \end{tabular} \end{table} \begin{figure} \centering \includegraphics[width=19 cm,height=11.5 cm,keepaspectratio]{Fig3.eps} \caption{Averaged network structure estimated by adopting prior Strategy 1 (blacklist only) with NUTS 1 level macro-areas (NW-NE-C-S-I).} \label{fig:strategy_1} \end{figure} As a second step of the reading-through-the-network exercise, we look at particularly interesting structures and highlight the central role of some nodes in terms of their in-degree, out-degree and Markov blanket size (see Section \ref{MB}). These are measures of the degree of connection of a node to the remaining of the network and a complete description of all three features for each node is provided in Table \ref{degree} and Table \ref{degree2} in Appendix. All nodes have an in-degree varying from $0$ to $2$, and thus no node shows a central role in terms of the number of ingoing edges. On the other hand, three nodes show an interesting behaviour in terms of their out-degrees: AREA, \emph{Employment Rate} and \emph{High School Diploma}. We already highlighted the central role of the node AREA that, with an out-degree equal to $21$, is the node with the maximum number of outgoing edges, which clearly reflects the relevance of the geographic position of the Italian regions on the regional well-being as it is captured by the BES atomic indicators. On the other hand, among the BES atomic indicators, \emph{Employment Rate} and \emph{High School Diploma} have the highest out-degrees, with $4$ and $3$ outgoing edges respectively, as well as the highest value of the Markov blanket size, which is equal to $5$ for both indicators. In order to better understand the role of these central indicators in the network, it is necessary to look at the structures in which they are inserted and, more specifically, the set of serial, diverging and converging connections (see Section \ref{fundamental_connections}) in which they are involved. In what follows, interesting structures (both including and not including \emph{Employment Rate} and \emph{High School Diploma}) arising from the estimated network are analyzed, considering them in light of the engaged BES domains. \paragraph{Work \& Life Balance, Economic Well-being and Services} \emph{Employment Rate} is connected to the remaining of the network by outgoing edges only and hence no BES atomic indicator influences it either directly nor indirectly. On the contrary, it affects $5$ indicators pertaining to $4$ different domains, namely \emph{Low Work Intensity} (Economic Well-being, [Min conditions]), \emph{Satisfied Employees} (Work \& Life Balance [Work Quality]), \emph{Childcare Services} (Services), \emph{Income per Capita} (Economic Well-being [Income \& Inequality]) and \emph{Low wage earners} (Work \& Life Balance [Work Quality]). Due to the diverging connections involved (which form something similar to a "cross" with \emph{Employment Rate} in the center), the first four indicators are pairwise independent given \emph{Employment Rate} or, in other words, it is the level of \emph{Employment Rate} that makes the four indicators pairwise marginally dependent. Therefore, any association detectable between, for example, \emph{Childcare Services} and \emph{Low Work Intensity} or \emph{Satisfied Employees} and \emph{Income per Capita} is due to the level of \emph{Employment Rate}. Another interesting structure involving \emph{Employment Rate} is the serial connection \emph{Employment Rate $\to$ Income per Capita $\to$ Low Wage}, for which \emph{Employment Rate} influences \emph{Low Wage} exclusively through \emph{Income per Capita} and, for this reason, \emph{Employment Rate} and \emph{Low Wage} are independent if conditioning on \emph{Income per Capita}. Finally, \emph{Employment Rate} also plays a role in two converging structures, namely \emph{Employment Rate $\to$ Income per Capita $\leftarrow$ AREA} and \emph{Employment Rate $\to$ Childcare Services $\leftarrow$ AREA}. From these two connections it is possible to scrutinize the dependence of \emph{Employment Rate} from AREA by assessing that \emph{Employment Rate} and AREA are marginally independent and become dependent when conditioning on either the level of \emph{Income per Capita} or \emph{Childcare Services}. In other words, the association between \emph{Employment Rate} and AREA can be explained by either considering the economic wealth (as it is measured by \emph{Income per Capita}) or the availability of municipal childcare services (measured by \emph{Childcare Services}). The central role of \emph{Employment Rate} in influencing variables related to work conditions, work satisfaction, income and childcare services, partly reflects results in, for example, \citep{maitah2015exploring, kitov2011employment, kreyenfeld2000does} and can be potentially relevant for decision making policies. Finally, we report on the indicators \emph{Economic Difficulty} and \emph{Low Quality House} from the Economic Well-being (Min. Conditions) domain, which are not involved in this group of connections but form a connected component on their own, with \emph{Low Quality House} directly reflecting the level of \emph{Economic Difficulty} and the latter being marginally independent on any other node. \paragraph{Education and Research} The node \emph{High School Diploma} from the Education domain shows both ingoing and outgoing edges. It directly influences $3$ indicators pertaining to the Education domain, namely \emph{University Degree}, \emph{Lifelong Learning} and \emph{School Early Leavers} and it is directly affected by the nodes AREA and \emph{Knowledge Workers} from the Innovation domain. Due to the serial connections involved in this group of nodes (which overall forms something similar to a "star" with \emph{High School Diploma} in the center), the three indicators from the Education domain and the node AREA are marginally dependent and become (conditionally) independent when conditioning on the level of \emph{High School Diploma}. Therefore, it is indeed the level of \emph{High School Diploma} that explains the relationship between AREA and \emph{University Degree}, \emph{Lifelong Learning} and \emph{School Early Leavers}. Similar reasoning holds when AREA is substituted by \emph{Knowledge Workers}: the dependence between the latter and the three indicators \emph{University Degree}, \emph{Lifelong Learning} and \emph{School Early Leavers} is explained by the level of \emph{High School Diploma}. Therefore, \emph{High School Diploma} mediates the effect of both AREA and \emph{Knowledge Workers} on the other Education indicators. Finally, \emph{High School Diploma} is also involved in the converging structure AREA $\to$ \emph{High School Diploma} $\leftarrow$ \emph{Knowledge Workers}, from which it is possible to assess that AREA and \emph{Knowledge Workers} are marginally independent and become conditionally dependent if the level of \emph{High School Diploma} is known. As far as the Education domain is concerned, it is noteworthy that \emph{Nursery School} is the only indicator among the ones used to build the composite indicator for Education (see Section \ref{second} and Table \ref{tab:bes1} in Appendix), that does not join this ("star") structure. In fact, it is an isolated node in the estimated network (constituting a connected component on its own) and therefore is (marginally) independent on any other node. This result is somehow reasonable, since the four connected indicators all concern education for the adults (people aged $18$ or above), while \emph{Nursery School} is the only indicator in the Education domain measuring the phenomenon at the children level (people aged between $4$ and $5$). The estimated network confirms the lack of any association between the two groups of indicators representing adult education and children education and could eventually lead to a further discussion on the extent to which children education is properly represented in the final composite indicator for Education or even question the suitability of keeping adult and children education indicators together in the same composite indicator. \paragraph{Subjective Well-being and Politics} Another interesting structure worth analyzing is the one arising from the connected component $\{$\emph{Parliament Trust, Parties Trust, Judicial System trust, Life Satisfaction}$\}$. Here two aspects emerge. First of all, Subjective Well-being domain is connected to three over the four indicators in the Politics domain that measure citizens' trust in political institutions. More specifically, \emph{Life Satisfaction} directly affects \emph{Parties Trust} and is indirectly connected to \emph{Parliament Trust} and \emph{Judicial System Trust}. Secondly, \emph{Parties Trust} seems to have a central role in this relationship, as it mediates for the influence of \emph{Life Satisfaction} on \emph{Judicial System Trust} (due to the corresponding serial connections) and makes \emph{Parliament Trust} and \emph{Life Satisfaction} conditionally dependent (due to the corresponding converging structure). Subjective Well-being affecting Politics is clearly an interesting feature of well-being and is consistent with results in \citep{ceriani2016multidimensional} where the same is assessed in the context of a study of well-being in Eastern and Western Europe by means of data from the Life in Transition Survey (LITS II). \paragraph{Environment, Landscape, Services and Security (Predatory Crimes)} Indicators from the domains of Environment, Landscape, Security and Services clearly appear to be interrelated with each others in more than one part of the network. First of all, indicators related to the satisfaction for the living place, meant as related to either the environment, landscape or mobility, are connected to each other. This is expressed by the serial connection \emph{Landscape Dissatisfaction} $\to$ \emph{Environment Satisfaction} $\to$ \emph{Mobility Satisfaction}, where \emph{Environment Satisfaction} mediates the relationship between the other two. Furthermore, \emph{Landscape Dissatisfaction} is also involved in the serial connection \emph{Urban Green} $\to$ \emph{Illegal Buildings} $\to$ \emph{Landscape Dissatisfaction}, with \emph{Illegal Buildings} explaining the relationship between \emph{Urban Green} and \emph{Landscape Dissatisfaction}, and both \emph{Illegal Buildings} and \emph{Urban Green} being directly influenced by AREA. In the second place, aspects of well being related to the living place satisfaction are interestingly connected to all indicators in the Security (Predatory Crime) domain. In fact, \emph{Environment Satisfaction} directly influences \emph{Robberies} (which is also directly affected by the node AREA) and indirectly influences all other indicators of predatory crimes as it is described by the following concatenation of serial connections \emph{Environment Satisfaction} $\to$ \emph{Robberies}, $\to$ \emph{Pickpocketing} $\to$ \emph{Home Burglaries}. Finally, the Environment, Landscape and Services domains also interact with each other in that some indicators from the Services domain appear to be connected to indicators devoted to measuring environmental sustainability. This is the case, for example, for the diverging connection \emph{Protected Areas} $\leftarrow$ \emph{Places-Km} $\to$ \emph{Renewable Energy} where two environmental indicators are made independent if conditioned on an indicator from the Services domain, and for the serial connection \emph{Water Supply Dispersion} $\to$ \emph{Beds in Hospital} where \emph{Beds in Hospital} reflects what is measured by \emph{Water Supply Dispersion}, both indicators being also strongly influenced by the geographic position of the region. \paragraph{Environment, Work \& Life Balance and Relationships} Interestingly, indicators related to having a stable work, in terms of either the number of hours worked in a week (\emph{Involuntary Part-Time}) or the type of contract (\emph{Temporary Jobs}), connects to aspects of social participation, as they are described by the Relationships indicators \{\emph{Volunteering, Social Participation, Financing of Associations, People to Rely Upon}\}, and to indicators from the Environment domain that pertain to the waste management process, namely \{\emph{Separate Urban Waste, Waste to Landfill}\}. This overall group of nodes could potentially be seen as representing those traits of well-being strictly related to the possibility for the citizens to have an active role in their community. In fact, this opportunity certainly reflects into the undertaken social activities (e.g. volunteering, social participation, financing association...), but also the job contractual conditions and, perhaps more surprisingly, the behaviour related to separating urban waste which, in turn, also directly influences the transfer of urban waste to landfill. Interestingly, \emph{Family Satisfaction} and \emph{Friendship satisfaction} from the Relationship domain are not involved in this group of connections, forming a connected component on its own. \subsubsection{Relationships among the BES domains: implementation of Strategy 2} In order to answer the second research question concerning the relationships and roles of the different BES domains as they are currently defined within the BES framework, BNs were estimated by encoding prior information according to Strategy 2. The only difference with the Strategy 1 set up is that atomic indicators pertaining to the same domain are here compelled to be connected. Figure \ref{fig:model2} shows the structure of the network estimated using the prior setting induced by Strategy $2$ and corresponding to the Italian regions grouped into five macro-areas (NUTS 1 level: NW-NE-C-S-I). As for Strategy $1$, the analysis will focus on the structure of the network and will proceed by considering the network's topological configuration (analysis of the connected components), as well as the study of BES domains showing a central role and particularly interesting connections among domains. In terms of its topological structure, the network is composed of $5$ connected components. The largest component includes the node AREA as well as $12$ out of the $15$ BES domains, with the only exception of Health, Economic Well-being (Min. Conditions) and Security (Murders). This shows, as expected, a high level of interaction among the BES domains, as well as the central role of the regional geographic position in intervening on these interactions, with the node AREA directly influencing $9$ BES domains. Three out of the four remaining connected components correspond to the domains Health, Economic Well-being (Min. Conditions) and Security (Murders) which do not show specific connections with the other domains. For the case of Economic Well-being (Min. Conditions) and Security (Murders), this configuration agrees with the recent development within the formalization of the BES domains, corresponding to the splitting of the Economic Well-being and Security into their sub-components \citep{istat2018benessere}. The last connected component is uniquely formed by the YEAR node, confirming the lack of significant influences of the temporal variable over the indicators' relationships also within this prior setting. For the purpose of quantifying the degree of connection of each domain with the remaining of the network, and consequently identify possible domains having a particularly central role, we resort to the number of directly connected components of a domain, i.e. the number of domains that have at least one direct connection with it. The value of this summery statistics for each domain is reported in Table \ref{strategy2} in Appendix. All domains are directly connected with a number of domains between $0$ to $4$ and the most connected domains are Work \& Life Balance (Work Quality) and Environment, with $4$ directly connected domains each. Specifically, the Environment domain is directly connected to the domains Landscape (by means of indicators related to the living place satisfaction), Security (Predatory Crimes) (by means of the presence of \emph{Urban Areas}), Services (through the indicator \emph{Places-km}) and Relationships (thanks to the connection between \emph{Separate Urban Waste} and \emph{Volunteering}). On the other hand, the Work \& Life Balance (Work Quality) domain has direct connections with the domains Economic Well-being (Income) (by means of the edge \emph{Low Wage} $\to$ \emph{Income per Capita}), Innovation (through the indicator \emph{Knowledge Workers}), Relationships and Services. The high number of direct connections for the Environment and Work \& Life Balance (Work Quality) domains suggests a central role for them in the whole BES system, in that they are potentially able to influence (or at least reflect) several other traits of well-being. In addition to relationships that concern the highest connected domains, there is a number of connections that are worth highlighting and that are, to a certain extent, in agreement to what observed from the network estimated in the prior setting of Strategy $1$. First of all, Subjective Well-being confirms to be able to directly influence (or at least reflect) the Politics domain. This connection is realized through the edge \emph{Life Satisfaction} $\to$ \emph{Parliament Trust}, which seems to confirm that the existing relationships between the two domains is indeed due to the subgroups of indicators in the Politics domain that refer to the level of trust of citizens towards political institutions. The Politics domain is also directly connected to the Innovation and Education domains by means of the edges \emph{ Research Intensity $\to$ Women Political Representation} and \emph{School Early Leavers $\to$ Judicial System Trust}, respectively. Moreover, strict interactions emerge between aspects related to work and economic wealth, with Economic Well-being (Income) mediating the relationship between the two domains of Work \& Life Balance (Work Quality) and Work \& Life Balance (Employment). Finally, it seems interesting to notice the direct connection among the domains Education, Innovation and Work \& Life Balance (Work Quality) by means of the node \emph{Knowledge Workers}. \begin{figure} \centering \includegraphics[width=19 cm,height=11.5 cm,keepaspectratio]{Fig4.eps} \caption{Averaged network structure estimated by adopting prior Strategy 2 (blacklist and whitelist) with NUTS 1 level macro-areas (NW-NE-C-S-I).} \label{fig:model2} \end{figure} \subsubsection{Consistencies and novelties with respect to the BES system of indicators: combining results from the two prior strategies} Considerations derived from implementing both prior settings will allow to answer the third research question, investigating the extent to which the structure of the estimated relationships reflect the current BES theoretical framework. This purpose basically refers to the opportunity of highlighting some future directions for the BES system of indicators in light of the relationships arising from the networks. From the network estimated by implementing Strategy $1$, we can assess that the BES theoretical framework consisting of domains and corresponding atomic indicators is indeed reflected in the estimated network. In fact, the network could recover (at least some) parts of almost all BES domains, by connecting indicators belonging to the same domain for $10$ out of the $15$ BES domains. This is particularly evident for the domains Education, Economic Well-being (Min. Conditions), Work \& Life Balance (Quality), Landscape, Environment, Relationships, Politics and Security (Predatory Crimes). It is noteworthy that the network could even reflect the sub-domains that have recently been introduced by ISTAT with the intent of splitting the domains of Economic Well-being, Work \& Life Balance and Security into two sub-components each \citep{istat2018benessere}. In fact, indicators in the Economic Well-being (Min. conditions) and Economic Well-being (Income) domains never connect with each other, while indicators in the same sub-component do show associations. The same holds for Work \& Life Balance (Work Quality) and Work \& Life Balance (Employment) and for Security (Predatory Crimes) and Security (Murders). Identifying the right domains as well as choosing the atomic indicators informing those domains, is a crucial exercise in order to get a meaningful measurement of the phenomenon of interest. Particularly, this is the key instrument through which balancing a detailed description of the phenomenon -realized by looking, for instance, at hundreds of indicators- with the need of an efficient synthesis of the overall available information. This is precisely the perspective from which reading the following considerations arising from the analysis of the network. In fact, the BN analysis seems to suggest some other possible splittings in light of the different roles that groups of indicators, currently referred to the same BES domain, seem to have in the network’s functioning. An example is given by the Environment domain, with reference to which it is possible to identify the sub-component \{\emph{Separate Urban Waste, Waste to Landfill}\}, to be conceivably ascribed to the Waste Management Process. A second example is in the Relationships domain, for which two sub-components can potentially be identified, namely the group \{\emph{Volunteering, Social Participation, Financing of Associations, People to Rely Upon}\}, related to aspects of social participation and the group \{\emph{Friendship Satisfaction, Family Satisfaction}\}, concerned with the satisfaction for social relationships, the latter sub-component even forming a connected component on its own. Finally, some considerations can also be raised about the Education domain, where the set of indicators \{\emph{University Degree}, \emph{Lifelong Learning} and \emph{School Early Leavers}\} specifically refers to aspects of the adults education and formation, while \emph{Nursery School} is the only indicator (among those used to build the composite indicator for the domain Education) that is currently in charge of measuring children's education. Finally, by looking at the network estimated as in the setting of Strategy $2$, we note that almost all domains are connected to each other by means of at most one direct edge, which can be interpreted as the BES domains, which are expected to catch diverse, although related, aspects of well-being, being distinguished from each other to a good extent. The only exception being the Environment and Landscape domains, which show a higher level of interrelation being directly connected through three edges, which could lead to perceive these two domains as not so clearly distinguishable. \section{Conclusions and Future Remarks} This work aims to be a first attempt to approach the complex phenomenon of multidimensional well-being in the Italian regions through the tool of the Bayesian Networks' class of models. The possibility of combining probabilistic assessments with a graphical representation seemed to be promising for a dataset with a considerable number of variables that poses the question of how to fruitfully deal with the amount of uncertainty present in it. Specifically, BNs can considerably simplify the complexity of the relationships among different aspects of a phenomenon by highlighting the most significant connections and build an overall model of interactions by integrating data and prior knowledge. We showed that Bayesian Networks can be considered as a suitable class of models for studying the multidimensional well-being for the Italian regions, being also able to incorporate geographic information. We suggested two different settings for encoding prior information in the network learning algorithm, which allow to conduct the analysis at two different levels of the hierarchical framework of the BES, by either looking at the relationships among the BES atomic indicators or relationships among the BES domains. Considerations arising from both levels of the analysis could finally lead to formulate some considerations for possible future development of the BES system of indicators. We believe that this work can develop in a number of possible, future directions. By way of illustration, different learning algorithms can be considered for the Conditional Linear Gaussian Bayesian Networks (CLGBN) model, as well as alternative models that could, for example, account for possible dependencies among regions (which were not contemplated in this work). Moreover, gender differences can also be potentially inspected by comparing gender-specific network structures and the availability of data referring to a larger number of years could allow to include other variables in the analysis, as for example those BES indicators that are currently not used to compute composite indicators for each domain. Finally, other directions for future works could also include the attempt to integrate the results from the estimated network in the development of a model-based classifier to characterize, and possibly rank, the Italian regions according to their well-being.
{'timestamp': '2020-08-18T02:17:25', 'yymm': '2008', 'arxiv_id': '2008.06902', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06902'}
arxiv
\chapter{Introduction} Data reduction dates back to 1901 when the English mathematician and biostatistician Karl Pearson published \emph{On lines and planes of closest fit to systems of point in space} \cite{peason1901lines}. In the paper, Pearson studied the data reduction problem and proposed the famous method of Principle Component Analysis (PCA). In 1958 and 1966, Torgerson and Gower proposed a similar method called the classical multidimensional scaling, also known as the Principle Coordinates Analysis \cite{torgerson1958theory}. The two early data reduction methods evolved during the decades and have many variants now. In 2000, two groups of scientists independently published their new methods ISOMAP \cite{tenenbaum2000global} and LLE \cite{roweis2000nonlinear} in \emph{Science}. People then began to realize the importance of data science. \\\\ Data reduction plays a role in data science. According to a famous scientific statement, the curse of dimensionality proposed by mathematician Bellman, most of the algorithms need exponentially more data samples in the high dimensional space to work efficiently as well as in the low one. One way to overcome this difficulty is to reduce the original data to a lower space. In particular, if the original data has too much meaningless information, data reduction becomes a necessary procedure before data analysis. For example, we can regard an image of a handwritten digit with $28\times 28$ pixels as a 784-dimensional vector. In general, the handwritten digit only occupies a little space. It means most of the coordinates of this high dimensional vector contains nothing. Thus, we can reduce these vectors to acquire a dense representation in the low dimension before data analysis without losing too much information. Another role for data reduction is that data scientists want to observe data before data analysis and then they reduce data to a visual space by the data reduction algorithms. \\\\ In the early age of data reduction, scientists only considered the linear case due to their simplicity. When ISOMAP and LLE came out in 2000, people began to pay attention to those data with nonlinear structure. This class of problem is called the manifold learning problem. In general, the framework of the manifold learning problem assumes the data are on (or near) a manifold without knowing their dimensions. The traditional methods such as PCA and MDS cannot be used as efficient ways in most cases, because the linear projection methods won't distinguish the nonlinear structure correctly. In chronological order, the main manifold learning algorithms include ISOMAP \cite[2000]{tenenbaum2000global}, LLE \cite[2000]{roweis2000nonlinear}, EigenMap \cite[2003]{belkin2003problems}, Hessian EigenMap \cite[2003]{donoho2003hessian}, MVU \cite[2004]{weinberger2006unsupervised}, LTSA \cite[2004]{zhang2004principal}, Diffusion Map \cite[2004]{lafon2004diffusion} and Vector Diffusion Map \cite[2011]{singer2012vector}. All the algorithms have their own characteristics. For example: ISOMAP is a method preserving the geodesic distance on the manifold; LLE considers the relation of nearby points as the linearity; EigenMap utilizes the graph Laplacian to approximate the Laplace-Beltrami operator; Hessian EigenMap is based on the fact that a function is linear if and only if it has everywhere vanishing Hessian; MVU keeps the metric isometry; LTSA aligns the bases of tangent space together; Lastly, Diffusion Map and Vector Diffusion Map are methods utilizing the diffusion process on the data graph. All these algorithms are formulated as an optimization problem based on their characteristics, and then scientists will apply spectral decomposition on some matrices to acquire the representation of data. Thus, these algorithms are also called the spectral manifold learning algorithms. Fortunately, there is a large amount of literature to solve this kind of optimization problems \cite{absil2009optimization}.\\\\ This survey is organized in the following way: In Section 2.1 of Chapter 2, we collect the properties from all the algorithms. Since every algorithm holds a special property, we relate them with the general geometric or topological properties and name them. In Section 2.2, we mainly talk about two methods of collecting the local information. One is called the method of the local linearity, which means the local neighbor points hold the linearity property. And, the other method is called the local PCA. It means the scientists do the PCA locally and collect an approximation of the tangent space. In Section 2.3, we introduce all the spectral manifold learning algorithms in chronological order. In this chapter, all the methods are presented in a language of matrix theory for the computational mathematician and statistician. In Section 2.4, we compare the performance of each algorithms based on several factors. In Chapter 3, we cover the convergence issue of the manifold learning algorithms, which is the core subject of this survey. We mainly analyze the convergence issue of the three algorithms EigenMap, Diffusion Map and Vector Diffusion Map. In Section 3.1, we discuss the relation between the geodesic distance and the embedding Euclidean distance. The distance or the function related to the distance parameter can be expanded with some curvature term and higher-order terms because of the intrinsic geometric structure of the manifolds embedded in the Euclidean space. In Section 3.2, we restate the three algorithms in the language of the operator theory on manifolds. These theoretical formulations are helpful for the convergence proof. In Section 3.3, we discuss the main idea for all the convergence issue of the three algorithms in a similar framework. The graph Laplacian converges to an averaging operator and the averaging operator converges to the Laplace-Beltrami operator. Finally, we write all the necessary math background in the Appendix including the basic matrix analysis, the linear manifold reduction algorithm, the Laplace-Beltrami operator and the Hessian tensor on manifolds, the heat operator on manifolds and the basic spectral graph theory. \chapter{Manifold Learning Algorithms} Suppose we have a connected compact smooth Riemannian manifold $(M, g)$ with dim$M=d$ and in addition a Riemannian immersion (or Riemannian embedding) $\iota: (M^d, g) \hookrightarrow (\mathbb{R}^D$, can). The metric $g$ for manifold $M$ is induced from the canonical metric on ($\mathbb{R}^D$, can). This means the metric locally performs like the Euclidean inner product on the tangent space of the manifolds. Suppose the data samples $\{x_1,\dots, x_N\}$ $(x_i\in\mathbb{R}^D)$ are distributed on or near some embedding manifold $\iota(M)$ with an unknown intrinsic dimension $d\ll D$. We will denote the point on $M$ by $x_i$ rather than $\iota(x_i)$ in most cases except for in the vector diffusion map algorithm. We call the space of data sample the \emph{sample} space and the space after reduction the \emph{feature} space. The aim of the reduction algorithm is to find a lower-dimensional representation of data in the feature space $\{y_1, \dots, y_N\}$ $(y_i \in \mathbb{R}^d)$ for the original data samples $\{x_1,\dots, x_N\}$ $(x_i\in\mathbb{R}^D)$. In the spectral method of data reduction, people could always write down a reduction function in an explicit way. In general, the manifold learning algorithms have two steps. In the first step, they extract the local information from the data samples obeying some specific properties. Then in the second step, they patch them to global information and obtain a lower-dimensional representation of the data. \section{Properties of Algorithms} Given two manifolds $(M, g_M)$ and $(N,g_N)$, if there exists a diffeomorphism $F: M\rightarrow N$ satisfying \begin{align*} g_N(dF(v),dF(w))=g_M(v, w) \hspace*{1em} v, w \in TM, \end{align*} we call $F$ a (Riemannian) isometry. We always assume the embedding map $\iota: M^d \hookrightarrow \mathbb{R}^D$ is isometric.\\\\ For a pair of points $x_i$ and $x_j$ on $M$, we define the path space \begin{align*} \Omega_{ij} :=\{\gamma: [0,1]\rightarrow M| \gamma \in C^\infty([0,1]) \text{ and } \gamma(0)=x_i, \gamma(1)=x_j \}. \end{align*} Then the distance on Riemannian Manifolds $(M,g)$ between $x_i$ and $x_j$ is \begin{align*} d_M(x_i, x_j):=\inf_{\gamma \in \Omega_{ij}} \int_{[0,1]} g(\dot{\gamma(t)},\dot{\gamma(t)})^\frac{1}{2} dt. \end{align*}\\ The following parts are the two groups of properties that the algorithms obey: \subsection{Geometric Properties} \begin{itemize} \item \textbf{Global Geodesic Isometry}: There exists a coordinate representation $\{y_1, \dots, y_N\}$ $(y_i \in \mathbb{R}^d)$ in the feature space satisfying \begin{align*} d_M(x_i, x_j) = ||y_i-y_j||_{\mathbb{R}^d}. \end{align*} \item \textbf{Local Geodesic Isometry}: For any point $x \in M$, there is a small neighborhood $U_x\subset M$ such that the distance between $x$ and any other point $y\in U_x$ on the manifold is equal to the Euclidean distance between their corresponding points in the feature space. \item \textbf{Metric Isometry}: Given two metric spaces $(X,d_X)$ and $(Y, d_Y)$, there exists a map $F: X\rightarrow Y$ satisfying \begin{align*} d_Y(F(x_1), F(x_2))=d_X(x_1, x_2) \hspace*{1em} x_1, x_2 \in X. \end{align*} \end{itemize} \subsection{Topological Properties} \begin{itemize} \item \textbf{Local Topology Information}: The algorithm preserves the local orientation or the angle between points. \item \textbf{Connectedness in the Feature Space}: The algorithm requires the feature space to be open and connected in $\mathbb{R}^d$. \end{itemize} \section{Extracting the Local Information} In the section, we only talk about two methods of extracting the local information of the data manifolds. The purpose for extracting the local information is mainly because we need to hold similar structure in the low dimensional representation based on these information. \subsection{Method A: (Local Linearity)} This method views any data point as a linear combination of its neighboring $K$ points. Firstly, we need to compute the weights of the linear combination. We applies the optimization method to get the weights by minimizing the following total cost function, for all $i=1,\dots,N$ and $x_j \in N(x_i)$ \begin{align*} \mathcal{E}(W)&=\sum_i |x_i-\sum_{x_j} W_{ij}\cdot x_j|^2, \\ \sum_{x_j} W_{ij}&=1, \end{align*} where the set $N(x_i)$ is the $K$-neighbor point set of $x_i$ and $W_{ij}$ are non-symmetric weights. \\\\ Fix an index $i$. We find the weights $W_{ij}$ in group $N(x_i)$ independently of the weights in other groups. Thus, we have only to minimize the cost for one group $N(x_i)$ and sum them up: \begin{align*} \mathcal{E}_i(W)&=|x_i-\sum_{x_j} W_{ij}\cdot x_j|^2,\\ \sum_{x_j} W_{ij}&=1. \end{align*} By the method of Lagrange multiplier, we get an explicit solution \begin{align*} W_{ij}=\frac{\sum_k C_{jk}^{-1}}{\sum_{l,m} C_{lm}^{-1}}, \end{align*} where $C_{jk}:=(x_i-x_j)\cdot(x_i-x_k)^T$. \subsection{Method B: (Local Principle Component Analysis)} The main idea of this algorithm is to apply the PCA locally as its name implies. The classical Principle Component Analysis (PCA) algorithm is described in Section B.1 of Appendix B. The first step of the local PCA is to choose a scale parameter $\epsilon$. Then for each point, we define a neighborhood of $x_i$ on the manifold within Euclidean distance $\epsilon$ \begin{align*} B_{\epsilon}(x_i):=\{x_j: 0< ||x_j-x_i||<\epsilon\}. \end{align*} One issue for local PCA is how to pick the scale parameter. We need choose it such that $d \leq |B_{\epsilon}(x_i)|\ll D$. If we pick $\epsilon = O(n^{-\frac{2}{d+1}})$, then $|B_{\epsilon}(x_i)| =O(n^{\frac{1}{d+1}})$ \cite{singer2012vector}. After translating the points in $B_{\epsilon}(x_i)$ by $x_i$, we reduce $B_{\epsilon}(x_i)-x_i$ by PCA method. Since the points in $B_{\epsilon}(x_i)$ is distributed on (or near) $T_{x_i}M$, the estimated reduction dimension of $B_{\epsilon}(x_i)-x_i$ is close to the true dimension of $M$. Since the noise in the samples, scientists prefer to set a global dimension as the mean or the median of the local dimensions in order to \section{Patching to Global Information} In this section, we go over all the existing spectral manifold learning algorithms. The spectral manifold learning algorithm means the manifold learning algorithm applies a procedure of the eigenvalue decomposition in the algorithm. We will present the methods in chronological order. The reference includes ISOMAP \cite{tenenbaum2000global, bernstein2000graph}, LLE \cite{roweis2000nonlinear}, EigenMap \cite{belkin2003problems, belkin2003laplacian, von2008consistency}, Hessian EigenMap \cite{donoho2003hessian}, MVU \cite{weinberger2006unsupervised}, LTSA \cite{zhang2004principal}, Diffusion Map \cite{lafon2004diffusion, coifman2006diffusion} and Vector Diffusion Map \cite{singer2012vector}. \subsection{ISOMAP (2000, J.B. Tenenbaum, V.D. Silva and J.C. Langford)} This algorithm obeys the global geodesic isometry property. The main idea of ISOMAP algorithm is to implement the classical Multidimensional Scaling algorithm on the data samples with the dissimilarities by summing up a sequence of the path length on the weighted graph. The path length is chosen as the geodesic distance between nearby points on the manifold. The convergence issue shows that for a small $\epsilon$ ($\epsilon$-neighbor algorithm) or a suitable $K$ (KNN algorithm), the distance between points in feature space is very close to the geodesic distance between points in the data space \cite[Main Theorem A B \& C]{tenenbaum2000global}. The scheme for this algorithm is as follow, \begin{algorithmic}[1] \State $\text{Construct a neighbor graph by $\epsilon$-neighbor or KNN algorithm}$ \State $\text{Compute the shortest paths between nodes by Floyd-Warshall algorithm}$ \State $\text{Construct the embedding by the Multidimensional Scaling method}$ \end{algorithmic} \noindent We derive the new representation of data by multidimensional scaling. Since the graph distance $d_G(i, j)$ is collected by Floyd-Warshall algorithm, then the Gram matrix $G_g :=C_N\cdot (-\frac{1}{2}d_G^2(i, j))\cdot C_N$, where $C_N$ is the centering matrix (See B.2 on Appendix B). Then we decompose the Gram matrix $G_g$ by the spectral decomposition, i.e. \begin{align*} G_g = V\cdot \Lambda \cdot V^T \end{align*} where $V=[v_1,\dots, v_n]$ and $\lambda=$diag$(\lambda_1,\dots,\lambda_n)$. Then the reduction coordinates are given by $Y=(\sqrt{\lambda_1}\cdot v_1,\dots,\sqrt{\lambda_d}\cdot v_d)^T$. For more details of multidimensional scaling, please refer to B.2 in Appendix B.\\\\ In particular, we have $y_i=(\sqrt{\lambda_1}\cdot v_1(i),\dots,\sqrt{\lambda_d}\cdot v_d(i))$. \subsection{LLE (2000, L.K. Saul and S.T. Roweis)} This algorithm collects the local information by the Method A (Local Linearity) in Section 2.2.1. After computing the weights between nearby points. Saul and Roweis recover the points preserving the same weights in the feature space. The numerical method for this recovering is by minimizing the embedding cost function \begin{align} \Phi(Y)=\sum_{i=1}^N |y_i-\sum_jW_{ij}y_j|^2. \end{align} To avoid degenerate solutions, we add two constraints. We require that the new coordinators $\{y_1,\dots,y_N\}$ are centering on the origin and have unit covariance, i.e. \begin{align*} \sum_{i=1}^N y_i&=0,\\ \frac{1}{N}\sum_{i=1}^N y_i\cdot y_i^T &=I_d. \end{align*} Define the $N\times N$ matrix $M$ be $(I-W)^T(I-W)$ and $M$ can be written as \begin{align*} M_{ij}:=\delta_{ij}-W_{ij}-W_{ji}+\sum_k W_{ki}W_{kj}. \end{align*} We can simplify $\Phi(Y)$ as $tr(YMY^T)$ and then the objective function (2.3.1) becomes an optimization problem with orthogonality constraints, i.e. \begin{align*} \min_{\frac{1}{\sqrt{N}}Y^T\in \mathcal{V}_d(\mathbb{R}^N)} & tr[Y(I-W)^T(I-W)Y^T],\\ s.t. \hspace*{1em} & \sum_{i=1}^N y_i=0, \end{align*} where we write $Y=(y_1, \dots, y_N)$.\\\\ For the optimization problem with orthogonality constraints, we have a routine argument for the solution. See Section A.3 in Appendix A. We apply the SVD method on $M$ and get $M=V\cdot \Sigma \cdot V^T$. After truncating the smallest eigenvector $v_0\approx 0$, the truncated $Y^T$ consist of the eigenvectors $\{v_1,\dots, v_d\}$ corresponding to the 2\textsuperscript{nd} to the $(d+1)$\textsuperscript{st} smallest eigenvalues of $M$. In particular, we have $y_i=(v_1(i),\dots, v_{d}(i))$. \subsection{EigenMap (2003, M. Belkin and P. Niyogi)} This algorithm utilizes the graph Laplacian on the data graph. For the basic spectral graph theory, please see Appendix E for details. Firstly, we regard the data as the node on a graph and connect the nodes by $\epsilon$-Neighborhood algorithm or KNN algorithm. Secondly, we define the graph weights between data by the Gaussian kernel, i.e. \begin{align*} w_{ij}:= e^{-\frac{||x_i-x_j||^2}{t}}. \end{align*} Then we get a weighted graph $W$ and we construct the Laplacian matrix on $W$ by \begin{align*} \mathcal{L}:=D-W. \end{align*} The aim of EigenMap is to find a representation $Y=[y_1,\dots,y_N]^T$ $(y_i \in \mathbb{R}^D)$ minimizing the weight objective function \begin{align} \sum_{i, j=1}^N ||y_i-y_j||_{\mathbb{R}^D} \cdot w_{ij}=tr(Y^TLY), \end{align} which has the orthogonal constraints $Y^TDY=I$.\\\\ The solution to (2.3.2) is the same to the following generalized eigenvector problem \begin{align*} \mathcal{L}f=\lambda D f, \end{align*} where the variable $f\in \mathbb{R}^N$.\\\\ Pick the smallest $d+1$ eigenvalues of $\mathcal{L}$ as $\lambda_0 (=0) \leq \lambda_1 \leq \dots \leq \lambda_d$. And, the corresponding eigenvectors are $f_0, f_1,\dots, f_d$. We truncate $f_0$ since it is a constant vector $c\cdot 1$. Then, the reduction map $\mathcal{E}(x_i)$ is given by \begin{align*} \mathcal{E}(x_i):=(f_1(i), \dots, f_d(i)). \end{align*} \subsection{Hessian EigenMap (2003, D.L. Donoho and C. Grimes)} This algorithm assumes the local geodesic isometry and the connectedness in the feature space. It utilizes the facts that a function is linear if and only if it has everywhere vanishing Hessian and the null space of $\mathcal{H}^{\text{iso}}$ is $(d+1)$-dimensional consisting of constant functions and isometric coordinates.\\\\ Consider two quadratic forms defined on a set of $C^2(M)$ functions \begin{align*} \mathcal{H}^{\text{iso}}(f)&:=\int_M ||H_f^{\text{iso}}||_F^2,\\ \mathcal{H}^{\text{tan}}(f)&:=\int_M ||H_f^{\text{tan}}||_F^2, \end{align*} where $H_f^{\text{tan}}$ in the norm is the Hessian operator in an orthonormal coordinates and $H_f^{\text{iso}}$ is the Hessian operator in an isometry coordinates. \\\\ In general, $\mathcal{H}^{\text{iso}}$ cannot be directly computed. Donoho and Grimes utilize $\mathcal{H}^{\text{tan}}$ to make it computable \cite[Theorem 1]{donoho2003hessian}, since the two Hessian operators obey \begin{align*} \mathcal{H}^{\text{iso}}(f)= \mathcal{H}^{\text{tan}}(f) \end{align*} Hessian EigenMap collects the local information by Method B (Local PCA) in Section 2.2.1. Local PCA collects an orthogonal basis of the tangent space at each point. For each point $x_i$ in the data set, the neighbor points set $\{x_{i_1},\dots,x_{i_k}\}$ is denoted as $N(x_i)$. We reduce the translation of the neighbor points set $M_i:=(x_{i_1}-\bar{x},\dots, x_{i_k}-\bar{x})$ by SVD method and get \begin{align*} M_i=U \cdot \Sigma \cdot V^T \end{align*} where $U:=[u_1,\dots, u_D] \in \mathbb{R}^{D\times D}$, $V:=[v_1,\dots, v_k] \in \mathbb{R}^{k\times k}$ and a diagonal matrix $\Sigma \in \mathbb{R}^{D\times k}$.\\\\ Then the left eigenvector set $\{u_1,\dots, u_D\}$ is an orthogonal basis of $T_{x_i}M$ and the right eigenvector set $\{v_1,\dots, v_k\}$ consists of the tangent coordinate functions, where the tangent coordinate function means $v_i$ is a function with the value $[v_i(x_{i_1}),\dots, v_i(x_{i_k})]$ on $N(x_i)$.\\\\ Recall that the null space of $\mathcal{H}^{\text{tan}}$ is $(d+1)$-dimensional consisting of constant functions and isometric coordinates. Then we construct the local Hessian matrix $H_i(x_i)$ from $[v_i(x_{i_1}),\dots, v_i(x_{i_k})]$. Firstly, we choose the $d$ leading columns from $U$ and $V$. Then we compute the Hadamard product $Q_i:=(v_k \circ v_m)_{1\leq k\leq m\leq d}$. Finally, we orthonormalize the matrix $P_i:=[1, V_i, Q_i]$ and get the orthonormalized matrix \begin{align*} \bar{P}_i=[1, V_i, \bar{Q}_i]. \end{align*} Then the local Hessian matrix is given by $H_i= \bar{Q_i} \cdot \bar{Q_i}^T$.\\\\ Now we need to patch all the local information together. Firstly, we initialize the global Hessian $H$ to an $n\times n$ zero matrix. Then we update it by a submatrix kernel $H(N(i),N(i))$ in each time and obey the rule \begin{align*} H(N(x_i),N(x_i)):=H(N(x_i),N(x_i))+H_i, \end{align*} where $H(N(x_i),N(x_i))$ denote the submatrix of $H$ with rows and columns indexed by $N(x_i)$.\\\\ Minimize the $\mathcal{H}^{\text{tan}}$ over all the linear function $f$ in $C^2(M)$ \begin{align*} \min_f f^T \mathcal{H}^{\text{tan}} f, \end{align*} where $f$ satisfies the orthogonal constraints.\\\\ Then the truncated $Y$ consists of the eigenvector $\{v_1,\dots, v_d\}$ corresponding to the 2\textsuperscript{nd} to the $(d+1)$\textsuperscript{st} smallest eigenvalues of the global Hessian $H$.\\\\ In particular, we have $y_i=(v_1(i),\dots, v_{d}(i))$. \subsection{MVU (2004, K.Q. Weinberger and L.K. Saul)} This algorithm is designed based on the metric isometry in Section 2.1.1. The metric isometry means the distance between any two points in the sample space $X$ is equal to the one in the feature space $Y$, i.e. \begin{align*} ||y_i-y_j||_{\mathbb{R}^d}=||x_i-x_j||_{\mathbb{R}^D}. \end{align*} Suppose the Gram matrix $G_{ij}=\langle x_i, x_j \rangle_{\mathbb{R}^D}$ and the Gram matrix $K_{ij}=\langle x_i, x_j \rangle_{\mathbb{R}^d}$. Then the metric isometry is equivalent to \begin{align*} K_{ii}+K_{jj}-K_{ij}-K_{ji}=G_{ii}+G_{jj}-G_{ij}-G_{ji}. \end{align*} The objection function is to maximize the cost function \begin{align*} \mathcal{E}(Y):&=\frac{1}{2N}\sum_{i,j=1}^N |y_i-y_j|^2\\ &=\sum_{i=1}^N |y_i|^2 \\ &=\sum_{i=1}^N K_{ii} \\ &=tr(K). \end{align*} Centering $y_i$ to 0, we get a semidefinite programming problem \begin{align*} \max_{K\succeq 0}&\hspace*{0.5em}tr(K)\\ s.t. \hspace*{0.5em} \sum_{i,j}K_{ij}&=0,\\ K_{ii}+K_{jj}-K_{ij}-K_{ji}&=G_{ii}+G_{jj}-G_{ij}-G_{ji}, \\ &\text{ for any connected $x_i$ and $x_j$.} \end{align*} There exists a wealth of literature for solving SDPs efficiently. Suppose $K^*$ is the optimizer of the semidefinite programming problem. It is a Gram matrix by the constraint and thus we can decompose it by the spectral decomposition.\\\\ In particular, we have $y_i=(\sqrt{\lambda_1}\cdot v_1(i),\dots,\sqrt{\lambda_d}\cdot v_d(i))$. \subsection{LTSA (2004, Z.-Y. Zhang and H.-Y. Zha)} This algorithm collects the local information by Method B (Local PCA) in Section 2.2.1. Local PCA method collects an orthogonal basis of the tangent space at each point. For each point $x_i$ in the data set, the neighbor points set $\{x_{i_1},\dots,x_{i_k}\}$ is denoted as $N(x_i)$. We reduce the translation of the neighbor points set $M_i:=(x_{i_1}-\bar{x},\dots, x_{i_k}-\bar{x})$ by SVD method and get \begin{align} x_{i_j} =\bar{x_i} +V_i \beta_{i_j}+\xi_j^i \hspace*{1em} j\in\{1,\dots,k\}, \end{align} where $\bar{x_i}$ is the mean of $N(x_i)$, $V_i$ is belong to $\mathcal{V}_d(\mathbb{R}^D)$, $\beta_{i_j}$ is the coordinates for $x_{i_j}$ on Stiefel manifold and $\xi_j^i$ is the reconstruction error written as $(I-V_i V_i^T)\cdot (x_{i_j}-\bar{x_i})$. \\\\ The global coordinates $\tau_i$ should be equal to the local coordinate coefficients $\beta_i$. Comparing with equation (2.3.3), we have \begin{align} \tau_{i_j} =\bar{\tau_i} +L_i \beta_{i_j}+\epsilon_j^i \hspace*{1em} j=1,\dots,k \end{align} In a language of matrices, suppose the $d\times k$ global coordinate matrix $G_i=[\tau_{i_1},\dots, \tau_{i_k}]$ and the local reconstruction error matrix $E_i=[\epsilon_1^i,\dots,\epsilon_k^i]$. Then equation (2.3.4) can be written as \begin{align*} G_i=\frac{1}{k}G_i\cdot 1\cdot 1^T+L_i\beta_i+E_i \end{align*} To minimize the reconstruction error $E_i$, we consider \begin{align} \sum_{i=1}^N ||E_i||^2=\sum_{i=1}^N ||G_i(I_d-\frac{1}{k}1\cdot 1^T)-L_i \beta_i||^2. \end{align} There are two variables $G_i$ and $L_i$ in (2.3.5). Firstly, we fix $G_i$ and solve for $L_i$. The explicit solution to $L_i$ and $E_i$ written in Moor-Penrose generalized inverse of $\beta_i$ are \begin{align*} L_i&=G_i(I_d-\frac{1}{k}1\cdot 1^T)\beta_i^+ = G_i \beta_i^+, \\ E_i&=G_i(I_d-\frac{1}{k}1\cdot 1^T)(I-\beta_i^+\beta_i). \end{align*} Define the $d\times N$ global coordinates matrix $G$ and the $N\times k$ selection matrices $S_i$ such that \begin{align*} G\cdot S_i = G_i \hspace*{1em} i=\{1,\dots,N\}. \end{align*} Then we denote the global selection matrix $(S_1,\dots,S_N)$ as $S$ and the global reconstruction error matrix $\text{diag}(W_1,\dots,W_N)$ as $W$, where $W_i=(I_d-\frac{1}{k}1\cdot 1^T)(I-\beta_i^+\beta_i)$. Finally, we need to determine $G_i$ by solving the following optimization problem.\\\\ Notice that \begin{align*} \sum_{i=1}^N ||E_i||_F^2=||GSW||_F^2. \end{align*} Then $G_i$ can be solved by the optimization problem with orthogonal constraints \begin{align*} \max_{G^T\in \mathcal{V}_d(\mathbb{R}^N)} &\hspace*{0.5em}tr(G[SWW^TS^T]G). \end{align*} For the optimization problem with orthogonal constraints, please see Section A.3 in Appendix A. \subsection{Diffusion Maps (2004, S. Lafon)} Similar with EigenMap, we generate a graph $G=(V, E, w)$ by the data set. Diffusion Maps utilizes the probability that one walks from a node to the others randomly on a graph as the distance between a pair of points in the feature space. Let $P$ be the transition matrix for the data graph $G$ and $P^t$ as the $t$\textsuperscript{th} step transition matrix. We can write $P=D^{-1}W$, where the weight matrix $W$ has entry $w(u,w)$ and the diagonal matrix $D$ has diagonal entry $w(u)$. See Section E.2 of the Appendix E for the notations and conventions of the random walk on a graph. \\\\ Consider the symmetric matrix $S:=D^{-\frac{1}{2}}\cdot P\cdot D^{\frac{1}{2}}$. We decompose $S$ by the spectral decomposition \begin{align*} S=V \cdot \Lambda \cdot V^T, \end{align*} where $V^T\cdot V=I_N$ and the diagonal matrix $\Lambda$ has a descending order diagonal entries $\lambda_1\geq \dots \geq \lambda_N$. \\\\ Note that \begin{align*} P=(D^{-\frac{1}{2}}V)\cdot \Lambda \cdot (D^{\frac{1}{2}}V)^T. \end{align*} Then we reduce matrix $P$ by SVD, so that \begin{align*} P=\Phi \cdot \Lambda \cdot \Psi^T, \end{align*} which implies $\Phi:=[\phi_1,\dots,\phi_N]=D^{-\frac{1}{2}}V$ and $\Psi:=[\varphi_1,\dots,\varphi_N]=D^{\frac{1}{2}}V$.\\\\ We can write $P$ as the sum of rank 1 matrices \begin{align*} P=\sum_{k=1}^N [\lambda_k\cdot \phi_k] \varphi_k^T, \end{align*} It follows that the $t$\textsuperscript{th} step transition matrix $P^t=\sum_{k=1}^N [\lambda_k^t\cdot \phi_k] \varphi_k^T$. And then, the diffusion map $\mathcal{D}_t$ is given as follows, \begin{align*} [\mathcal{D}_t](u):=(\lambda_1^t\cdot \phi_1(u), \dots, \lambda_n^t\cdot \phi_n(u)). \end{align*} \textbf{Note} \begin{itemize} \item We can truncate the first coordinate $\lambda_1^t\cdot \phi_1$ because the $k$\textsuperscript{th} step transition matrix $P^k$ always has the biggest simple eigenvalue 1 and thus $\lambda_1^t\cdot \phi_1(u)=1$ for any node $u\in V$. The truncated diffusion map with $d$ dimensions is the $d$ leading coordinates of the diffusion map. \item The Diffusion map $[\mathcal{D}_t]$ has the inner product in the feature space \begin{align*} \langle [\mathcal{D}_t](u), [\mathcal{D}_t](v)\rangle_{\mathbb{R}^d}=\sum_{k=1}^n \left(\frac{P^t(u,s)}{\sqrt{w(s)}}\cdot \frac{P^t(v,s)}{\sqrt{w(s)}}\right). \end{align*} \item The diffusion distance $d_{\text{Diffusion, t}}^2(u,v)$ is given by \begin{align*} d_{\text{Diffusion, t}}^2(u,v) =\sum_{s\in G} \frac{(P^t(u,s)-P^t(v,s))^2}{w(s)}. \end{align*} \end{itemize} \subsection{Vector Diffusion Maps (2011, A. Singer and H.-T. Wu)} This algorithm collects the local information by Method B (Local PCA) in Section 2.2.1. Then Singer and Wu computes the optimal orthogonal transformation between bases. It can be regarded as a numerical approximation to the parallel transport operator between the tangent spaces. \\\\ Firstly, we collect the base matrix $O_i \in \mathcal{V}_d(\mathbb{R}^N)$ by the local PCA. It is an approximation to the orthogonal basis for $T_{x_i}M$. Pick a small distance parameter $\epsilon$ but the parameter $\epsilon$ is much bigger than the scale parameter $\epsilon_{\text{PCA}}$ in the local PCA method (see Section 2.2.1). If points $x_i$ and $x_j$ satisfies $||x_i-x_j||_{\mathbb{R}^D}^2<\epsilon$, we compute the approximation matrix $O_{ij}$ as a transport vectors from $T_{x_j}M$ to $T_{x_i}$ by \begin{align} O_{ij}:=\arg \min_{O\in O(d)}||O-O_i^T\cdot O_j||_{HS}, \end{align} where $O(d)$ denotes the orthogonal group and the norm in (2.3.6) is called the Hilbert-Schmidt norm, i.e. \begin{align*} ||A||_{HS}:=tr(A\cdot A^T). \end{align*} The optimizer of (2.3.6) is given by$U\cdot V^T$, where $U$ and $V$ are the left and right eigenvectors of $O_i^TO_j$ by SVD. \\\\ Now, we consider a weighted graph. The node of the graph is data and the edge is connected if two nearby data has $\epsilon$ Euclidean distance. The weights $w_{ij}$ of the graph is given by \begin{align*} w_{ij}=K\left(\frac{||x_i-x_j||_{\mathbb{R}^N}}{\sqrt{\epsilon}}\right), \end{align*} where $K(\cdot)$ is the Gaussian kernel.\\\\ Construct an $N\times N$ block matrix $S$. Each block of matrix $S$ is $d\times d$ submatrix, i.e. \begin{align*} S(i,j)= \begin{cases} w_{ij}O_{ij} & w_{ij}>0\\ 0_d & w_{ij}=0, \end{cases} \end{align*} The diagonal $d\times d$ block matrix $D$ is defined by \begin{align*} D(i,i)=w(i)\cdot I_d. \end{align*} Note that the matrix $S$ and matrix $D$ has the same size $Nd\times Nd$. Consider a symmetric form $\bar{S}$ for matrix $S$ as \begin{align*} \bar{S}=D^{-\frac{1}{2}} S D^{-\frac{1}{2}}. \end{align*} Then we decompose $\bar{S}$ by the spectral decomposition with the eigenvalues $\lambda_1,\dots, \lambda_{Nd}$ in a descending order and the corresponding eigenvectors are $\phi_1,\dots, \phi_{Nd}$. We have \begin{align*} \bar{S}(i,j)&=\sum_{k=1}^{Nd}[\lambda_k \cdot \phi_k(i)]\phi_k(j)^T\\ \bar{S}^{2t}(i,j)&=\sum_{k=1}^{Nd}[\lambda_k^{2t}\cdot \phi_k(i)]\phi_k(j)^T, \end{align*} where $\phi_k(i) \in \mathbb{R}^d$ for $i, j=1,\dots,N$ and $k=1,\dots,Nd$.\\\\ Then the vector diffusion map $[\mathcal{VD}_t]: \mathbb{R}^N\rightarrow \mathbb{R}^{(Nd)^2}$ is given by \begin{align*} [\mathcal{VD}_t](x_i):=\left( (\lambda_k\cdot \lambda_m)^t \cdot \langle \phi_k(i), \phi_m(i)\rangle_{\mathbb{R}^d}\dots \right)_{k, m=1}^{Nd}. \end{align*} \textbf{Note:} \begin{itemize} \item The vector diffusion map $[\mathcal{VD}_t](x_i)$ is invariant to the choice of the basis of $T_{x_i} M$ since the inner product $\langle \phi_k(i), \phi_m(i)\rangle_{\mathbb{R}^d}$ preserves the value under the orthogonal transformations. \item The inner product $\langle [\mathcal{VD}_t](x_i), [\mathcal{VD}_t](x_j)\rangle_{\mathbb{R}^{(Nd)^2}}$ gives a vector diffusion distance on $\mathbb{R}^{(Nd)^2}$ and we have \begin{align*} \langle [\mathcal{VD}_t](x_i), [\mathcal{VD}_t](x_j)\rangle_{\mathbb{R}^{(Nd)^2}} = ||\bar{S}^{2t}(i,j)||_{HS}^2 \end{align*} \end{itemize} \clearpage \section{Comparison} The comparison of the data reduction algorithms includes several factors as follows \cite{wittman}: \begin{itemize} \item Cspeed: The computational speed for the algorithms to solve the problems. (Very fast $>$ Fast $>$ Median $>$ Slow $>$ Very slow) \item Geometry: Whether the new representation of the data holds the original geometric relations. (Yes/ No) \item Noise: The ability for the algorithm to deal with the noise data which is meaningless data caused by hardware failures, programming errors or other reasons. (Good $>$ Median $>$ Bad) \item Distribution: The performance of the algorithm under the different probability distribution. (Any type/ Uniform) \item Clustering: The ability of the algorithm to hold the data in the same group after the reduction. (Good $>$ Median $>$ Bad) \item Hdimension: The ability of the algorithm to deal with data of a high dimension. (Very good $>$ Good $>$ Median $>$ Bad $>$ Very Bad) \item Sensitivity: The algorithm is sensitive to changing of the parameters. (Very $>$ Yes $>$ No) \end{itemize} The factors listing above is suggested by most of manifold learning methods in numerical experiments. In the following section, we make two tables. Table \ref{Tab1} records the performance of seven algorithms according to the above seven factors. We run the experiments on a MATLAB graphical user interface (GUI) called MANI GUI created by Todd Wittman. The datasets includes Swiss Roll, Toroidal Helix, Corner Planes and Punctured Sphere. In particular, we choose three dimensional data sets and reduce them to the two dimensional plane. Table \ref{Tab2} records the decomposed matrices of each algorithm in the first column. The decomposed matrix means the matrix we need to decompose by SVD method in each algorithm. The second column records the truncated coordinates of the new representations of data in feature space. We take the $d$ coordinates except the Vector Diffusion Map algorithm. \begin{sidewaystable} \renewcommand{\arraystretch}{1.5} \centering \begin{tabular}{ |p{4cm}||p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|} \hline Algorithm Name & Cspeed & Geometry & Noise & Distribution & Clustering & Hdimension & Sensitivity\\ \hline PCA &Very fast&No&Good&Any type&Good&Good&No \\ \hline ISOMAP &Very slow &Yes&Median&Any type&Good&Best&Yes \\ \hline LLE &Fast &Yes&Bad&Any type&Good&Very bad&Yes \\ \hline EigenMap &Fast &Yes&Good&Uniform&Bad&Bad&Yes\\ \hline Hessian EigenMap &Slow&Yes&Good&Any type&Bad&Very bad&Yes \\ \hline LTSA &Fast &Yes&Good&Any type&Good&Good&Yes \\ \hline Diffusion Map &Fast &No &Good &Any type &Good& Good&Very \\ \hline \end{tabular} \caption{\label{Tab1} Comparison of the Algorithms} \end{sidewaystable} \begin{table} \renewcommand{\arraystretch}{1.5} \centering \begin{tabular}{ |p{4cm}||p{5cm}|p{7cm}|} \hline Algorithm Name & Decomposed Matrix &Truncated Coordinators\\ \hline PCA & $\Sigma_N$ & ${[v_1,\dots,v_d]}^T\times (x_i-\bar{x})$ \\ \hline ISOMAP & $G_g=C_N\cdot (-\frac{1}{2}d_G^2(i, j))\cdot C_N$ & $(\sqrt{\lambda_1}\cdot v_1(i),\dots,\sqrt{\lambda_d}\cdot v_d(i))$ \\ \hline LLE & $M=(I-W)^T\cdot (I-W)$ & $\left(v_1(i),\dots,v_d(i)\right)$ \\ \hline EigenMap & $L=D-W$ & $\left(f_1(i), \dots, f_d(i)\right)$ \\ \hline Hessian EigenMap & $H:=\sum_i H\left(N(i),N(i)\right)$ & $\left(v_1(i),\dots,v_d(i)\right)$\\ \hline MVU & $K^*$ &$\left(\sqrt{\lambda_1}\cdot v_1(i),\dots,\sqrt{\lambda_d}\cdot v_d(i)\right)$ \\ \hline LTSA & $S\cdot WW^T\cdot S^T$ &$\left(\sqrt{\lambda_1}\cdot v_1(i),\dots,\sqrt{\lambda_d}\cdot v_d(i)\right)$ \\ \hline Diffusion Map & $P^t$ & $\left(\lambda_1^t\cdot \phi_1(u), \dots, \lambda_n^t\cdot \phi_d(u)\right)$ \\ \hline Vector Diffusion Map & $\bar{S}=D^{-\frac{1}{2}} \cdot S \cdot D^{-\frac{1}{2}}$ & $\left( (\lambda_k\lambda_m)^t \cdot \langle \phi_k(i), \phi_m(i)\rangle_{\mathbb{R}^d} \dots \right)_{k, m=1}^{Nd}$ \\ \hline \end{tabular} \caption{\label{Tab2}Manifold Learning Algorithm} \end{table} \chapter{Convergence Issues} In differential geometry, a topological manifold is an abstract set (topological space) which is homeomorphic to the Euclidean space locally. People assign some differential structure to it and then it becomes a differential manifold. In 1851, Riemann firstly described his idea of Riemannian metric in his defense for the habilitation, which began a new era in geometry. However, it is not until Whitney's work in 1936 that mathematicians got a clear understanding of the abstract manifold, which is just a submanifold embedded in Euclidean space \cite{whitney1934analytic}. Later in 1954 and 1956, Nash discovered the amazing result of the $C^1$ and $C^k$ isometric embedding of Riemannian manifolds into some Euclidean space (\cite{nash1956imbedding}, \cite{nash1954c1} respectively).\\\\ In the EigenMap, Diffusion Map and Vector Diffusion Map, we assume the embedding is (Riemannian) isometric. i.e. suppose $\iota=(\iota_1,\dots,\iota_D) : M^d \hookrightarrow \mathbb{R}^D$ is a smooth Riemannian submanifold isometrically embedded in $\mathbb{R}^D$ with the induced metric $g_M$ from the canonical metric on ($\mathbb{R}^D$, can). Then the isometric embedding map $\iota$ satisfies \begin{align*} g_{ij}=\langle D\iota(\frac{\partial}{\partial x_i}), D\iota(\frac{\partial}{\partial x_j})\rangle_{\mathbb{R}^D}. \end{align*} In local coordinates, this is \begin{align} g_{ij}= \sum_{r=1}^D \frac{\partial \iota_r}{\partial x_i} \cdot \frac{\partial \iota_r}{\partial x_j}. \end{align} In differential geometry, the isometric embedding problem is to find a one-to-one function $\iota$ satisfying equation (3.0.1). Our data is isometrically embedded into Euclidean space and thus the aim is to find a representation of the data in the feature space which is low dimensional Euclidean space. In general, we collect a finite number of samples of the high-dimensional data and assume they are on or near a manifold with an unknown dimension. Then, we reduce the data to a low dimension as written in Chapter 2. In this section, we talk about the convergence issue of three manifold learning algorithms. Notice that we always use the Einstein summation convention in this chapter.\\\\ In general, the strategy of the convergence issue has two steps. The first step is to construct a convergence relationship between the averaging operator and the (normalized/unnormalized) discrete graph Laplacian, since the information we can collect is from the discrete graph structure generated by the finite data samples in the sample space. The second step is to show the averaging operator converges to the Laplace-Beltrami operator as the time parameter goes to $0^+$. This step mainly utilizes the basic technique of the heat kernel estimation on manifolds and general operator theory. With these two steps, we can reduce the bound of the difference between the discrete graph Laplacian and the Laplace-Beltrami operator which is called the \emph{bias} term and \emph{variance} term. We will discuss this further in Section 3.3. \section{Embedding Relation} This section is about the pure geometric results which expose the geometric relations between the intrinsic quantities on a manifold and the extrinsic Euclidean quantities in the ambient space. These relations are very important technical results often used in replacing the Euclidean distance by the geodesic distance on a manifold which includes some higher-order terms like curvature term. It is also helpful in deducing an asymptotic expansion for the (heat) operator. \\\\ Let $\iota: M^d \hookrightarrow \mathbb{R}^D$ be a connected compact smooth Riemannian submanifolds isometrically embedded in $\mathbb{R}^D$ with the induced metric $g$ from the canonical metric on ($\mathbb{R}^D$, can). Recall that in the Riemannian normal coordinate system, we can expand the Taylor series of the metric to higher order terms at any point $p \in M$, i.e. \begin{align} g_{ij}(x(p))\sim \delta_{ij}-\frac{1}{3}R_{iklj}x^kx^l-\frac{1}{6}R_{iklj,m} x^kx^lx^m, \end{align} where the curvature tensor $R$ denoted as \begin{align*} R_{iklj}&:=g\big(R(\frac{\partial}{\partial x_l},\frac{\partial}{\partial x_j})\frac{\partial}{\partial x_k}, \frac{\partial}{\partial x_i}\big),\\ R_{iklj,m}&:=\nabla_{\frac{\partial}{\partial x_m}} R_{iklj}. \end{align*} Let $(W_p, \text{exp}_p)$ be the normal coordinate system around $p\in M^d$, i.e. \begin{align*} \text{exp}_p : W_p &\rightarrow M\\ w & \mapsto \gamma_w(1), \end{align*} where $\gamma_w$ is the geodesic of $M$ with $c(0)=p$ and $\dot{c}(0)=w$, and $W_p:=\{w\in T_p M: \gamma_w $ is defined on $[0,1]\}$.\\\\ One relationship based on (3.1.1) between the geodesic distance on a manifold and the Euclidean distance in the embedding space is described in \cite[Prop 1]{smolyanov2000brownian}. Note that $d\text{exp}_p$ is nonsingular around $p$. Then there exists a neighborhood $U_p \subset M$ such that $\text{exp}_p^{-1}$ is diffeomorphical onto a neighborhood $V \subset T_p M\cong \mathbb{R}^d$. Thus, we have the following embedding relation, for all $v \in V$ \begin{align*} ||v||_{\mathbb{R}^d}^2 \overset{(1)}{=} d_M^2(p,\text{ exp}_p(v))\overset{(2)}{=} ||\iota \circ \text{exp}_p(v)-\iota(p)||_{\mathbb{R}^D}^2+ O(||v||_{\mathbb{R}^d}^4), \end{align*} where equality (1) is deduced from the definition of exponential map, and equality (2) follows from the properties of the normal coordinate system.\\\\ For any $v, w \in V \subset T_p M$, we have more specific embedding equalities mentioned in \cite[Lemma B.7 B.8 \& B.9]{singer2012vector} \begin{align} \iota\circ \text{exp}_p(v) - \iota(p) &= d\iota(v)+\frac{1}{2}\Pi(v, v) +\frac{1}{6}\Pi(v,v) + O(||v||_{\mathbb{R}^d}^4), \\ d [\iota\circ \text{exp}_p](v)(w)-d[ \iota\circ \text{exp}_p ](0)(w) &= \Pi(v, w)+\frac{1}{6}\nabla_v \Pi(v,w)+\frac{1}{3}\nabla_w \Pi(v,v) + O(||v||_{\mathbb{R}^d}^3), \end{align} where $\Pi$ is the second fundamental form of the embedding manifolds $M^d\hookrightarrow \mathbb{R}^D$. Equalities (3.1.2) and (3.1.3) provide a new estimate of $||v||_{\mathbb{R}^d}$: suppose $h:=||\iota\circ \text{exp}_p(v) - \iota(p)||_{\mathbb{R}^D}$ and $\theta:=v/||v||$. For a small $||v||_{\mathbb{R}^d}^2$, we have \begin{align*} ||v||_{\mathbb{R}^d} =||\iota \circ \text{exp}_p(v)-\iota(p)||_{\mathbb{R}^D}+\frac{1}{24}||\Pi(\theta,\theta)||_{T_p\mathbb{R}^D}^2\cdot h^3 + O(h^4). \end{align*} In the normal coordinate system $(U_p, \text{ exp}_p; \hspace*{0.5em} x_1,\dots, x_d)$, let $\{\frac{\partial}{\partial x_l}\}_{l=1}^d$ be the normal coordinate vector field on $U_p$. For any $q \in U_p$ with $q:=\text{exp}_p(v)$, where $v \in V \subset T_p M$, we have a relation of orthogonal bases under the parallel transportation from $p$ to $q$ \begin{align*} \iota_* P_{q,p} \frac{\partial}{\partial x_l}(p) =& \iota_* \frac{\partial}{\partial x_l}(p) + ||v||\cdot \Pi(\theta, \frac{\partial}{\partial x_l}(p)) + \frac{||v||^2}{6} \cdot \nabla_{\theta} \Pi(\theta, \frac{\partial}{\partial x_l}(p)) \\ &+\frac{||v||^2}{3} \cdot \nabla_{ \frac{\partial}{\partial x_l}(p)} \Pi(\theta,\theta) - \frac{||v||^2}{6} \cdot \iota_*P_{q,p}\big(R(\theta, \frac{\partial}{\partial x_l}(p) )\theta\big)+ O(||v||_{\mathbb{R}^d}^3). \end{align*} \section{Formulation of the Algorithms via Operator Theory} In Chapter 2, we has derived the three algorithms EigenMap, Diffusion Map and Vector Diffusion Map in the language of matrix theory so that people can compute eigenvalues and eigenfunctions of the discrete graph Laplacian generated by the data samples. In this chapter, we introduce a theoretical formulation for these three algorithms in the language of operator theory on manifolds. We will not mention the conventions and notations in Chapter 2 agian. The references include EigenMap \cite{belkin2003problems, belkin2003laplacian, von2008consistency}, Diffusion Map \cite{lafon2004diffusion, coifman2006diffusion} and Vector Diffusion Map \cite{singer2012vector}. \subsection{EigenMap (2003, M. Belkin and P. Niyogi)} Suppose $f\in C^2(M)$. We have an inequality that bounds how far $f$ can map two points $x, y \in M$ from each other. This is \begin{align*} |f(y)-f(x)| \leq ||\nabla f(x)||_{T_x M}\cdot ||y-x||_{\mathbb{R}^D}+o\big(||y-x||_{\mathbb{R}^D} \big) \end{align*} The aim of the EigenMap is to look for a map satisfying \begin{align} \mathop{\argmin}_{||f||_{L^2(M)}=1} \int_M ||\nabla f(x)||_{T_p M}^2, \end{align} which means that the close data will be as close as possible after the mapping. \\\\ Note that \begin{align*} & \int_M ||\nabla f(x)||_{T_p M}^2\\ =& \int_M \langle \nabla f, \nabla f \rangle_{T_p M}^2 \\ =& \int_M \mathcal{L}(f)\cdot f\\ =& \lambda \cdot \int_M f^2 \\ =& \lambda \cdot ||f||_{L^2(M)}. \end{align*} Thus, to minimize (3.2.1) is to spectral decompose the Laplace-Beltrami operator $\mathcal{L}$, which only picks the discrete eigenvalues $0=\lambda_0 \leq \lambda_1 \leq \lambda_2 \dots \rightarrow \infty$. \\\\ Note that there is a big relationship between the heat equation and the Laplace-Beltrami operator on manifolds. Thus, we introduce the heat equation here with the aim of approximating the heat operator by the graph Laplacian. Consider the homogeneous heat equation on the manifolds \begin{align*} (\Delta+\partial_t )u(x,t)&=0 \hspace*{2em} (x,t)\in M\times(0,\infty),\\ u(x,0)&=f(x) \hspace*{1.2em} \hspace*{1em} x\in M. \end{align*} Then the general solution is given by \begin{align*} u(x, t)= \int_{M(y)} u_y(x, t)f(y), \end{align*} where $u_y(x, t)$ is the fundamental solution. \\\\ Note that \begin{align*} [\mathcal{L}f](x):&=(\Delta+\partial_t )f(x)\\ &= (\Delta+\partial_t )u(x,0)\\ &=- [\frac{\partial}{\partial t} \int_{M(y)} u_y(x, t)f(y)]\big|_{t=0}\\ &\overset{(*)}\approx \lim_{t\rightarrow 0^+}-[(4\pi t)^{-\frac{d}{2}}\int_{M(y)} e^{-\frac{d_g^2(x,y)}{4t}}f(y)-f(x)]/t. \end{align*} The approximation step $(*)$ follows from two facts. One is that the fundamental solution $u_y(x,t)$ tends to the Dirac distribution $\delta_y(x)$ as $t$ tends to $0^+$, i.e. \begin{align*} \lim_{t\rightarrow{0^+}} \int_{M(y)} u_y(x,t)f(y) = f(x) \hspace*{0.5em} \text{ for all } x \in M. \end{align*} The other follow from the fact that the fundamental solution $u_y(x,t)$ has an expansion when data $x$ and $y$ are close on the manifold and time $t$ is very small, i.e. \begin{align*} u_y(x,t)\approx (4\pi t)^{-\frac{d}{2}}e^{-\frac{d_g^2(x,y)}{4t}}, \end{align*} which is known as Varadhan's large deviation formula relating the heat kernel and geodesic distance on a Riemannian manifold \cite{saloff2010heat}.\\\\ In practice, since the number of the sample is finite, we can only construct the discrete graph Laplacian $\bar{\mathcal{L}}$ based on the data information, i.e. \begin{align*} [\bar{\mathcal{L}}f](x_i) \approx \lim_{t\rightarrow 0^+}-[\frac{1}{N}(4\pi t)^{-\frac{d}{2}}\cdot \sum_{x_j} e^{-\frac{d_g^2(x_i-x_j)}{4t}}f(x_j)-f(x_i)]/t \end{align*} where $x_j \in \{x: 0<d_g(x_i-x)<\epsilon\}$. \subsection{Diffusion Maps (2004, S. Lafon)} In this section, the formulation of the algorithm is still in a discrete sense but we define the Diffusion Map using the language of operator theory on manifolds. Suppose the data samples are distributed on the measure space $(M, \mathcal{B}(M), \omega_g)$ of the manifold $(M, g)$ and we use the kernel $K(x,y)$ to represent the dissimilarity between two data point $x$ and $y$. In general, we need the kernel function to be symmetric, positivity-preserving and positive semi-definite, i.e. \begin{itemize} \item Symmetric: $K(x,y)=K(y,x)$ \item Positivity-preserving: $K(x,y)\geq 0$ for any $x$ and $y$ in $M$ \item Positive semi-definite: for all bounded function $f$ defined on $M$ \begin{align*} \int_{M(x)} \int_{M(y)} K(x,y) f(x) f(y) \geq 0. \end{align*} \end{itemize} The kernel function satisfying the conditions above is called the \emph{admissible kernel}. Then a routine in the kernel-based method is to normalize the kernel by introducing a constant $v^2(x)$ defined as \begin{align*} v^2(x) :=\int_{M(y)} K(x,y). \end{align*} The normalizing routine of the admissible kernel is to transform the original kernel to a Markov kernel by $\tilde{a}(x,y):=\frac{K(x,y)}{v^2(x)}$ on the data graph. Since the Markov chain exists for any Markov kernel \cite[Prop 1.5]{grigoryan2009analysis}, there always exists a random walk on $M$ for any admissible kernel. Thus we have a computational version of this algorithm starting directly from the random walk in Chapter 1. \\\\ Define the discrete averaging operator $\mathcal{A}: L^2(M)\rightarrow L^2(M)$ \begin{align*} [\mathcal{A}f](x)=\int_{M(y)} a(x,y)f(y) \end{align*} where the entries of the operator $\mathcal{A}$ are given by \begin{align*} a(x,y):=\frac{K(x,y)}{v(x)v(y)}. \end{align*} According to the construction above, the averaging operator $\mathcal{A}$ is bounded, symmetric and positive semi-definite with the supremum norm 1 on $L^2(M, \omega_g)$. In general, we say a densely defined operator $\mathcal{A}:D(\mathcal{A})\subset \mathcal{H}\rightarrow \mathcal{H}$ is \emph{symmetric} if $\mathcal{A}^*$ is an extension of $\mathcal{A}$, i.e. $\mathcal{A}\subset \mathcal{A}^*$ and \emph{self-adjoint} if $\mathcal{A}=\mathcal{A}^*$. If $\mathcal{A}$ is continuous and has domain $D(\mathcal{A})=\mathcal{H}$, symmetry of $\mathcal{A}$ implies self-adjointness of $\mathcal{A}$. Since the averaging operator $\mathcal{A}$ is bounded and self-adjoint, the spectral decomposition theorem implies \begin{align*} a(x,y)=\sum_{i\geq 0}^{N-1} \lambda_i \phi_i(x) \phi_i(y), \end{align*} where the eigenvalue $\lambda_i$ are non-increasing and non-negative satisfying \begin{align*} \mathcal{A}\phi_i(x)=\lambda_i \phi_i(x). \end{align*} Moreover, the $t$ th-step kernel $\mathcal{A}^t$ satisfies \begin{align*} a^{t}(x,y)=\sum_{i\geq 0}^{N-1} \lambda_i^m \phi_i(x) \phi_i(y). \end{align*} \\\\ Finally, the diffusion map $[\mathcal{D}]: M \rightarrow l^2(\mathbb{N})$ is given by \begin{align*} [\mathcal{D}]: x\mapsto \left(\phi_0(x), \dots, \phi_{N-1}(x)\right), \end{align*} and a family of semi-metric $\{ d_{\text{Diffusion, t}} \}_{t\geq 1}$ on $M$ is defined by \begin{align*} d_{\text{Diffusion, t}} (x, y):=\sqrt{a^{t}(x,x)-2\cdot a^{t}(x,y)+a^{t}(y,y)}. \end{align*} \subsubsection{Note} \begin{itemize} \item If the kernel function $K(x,y)$ is strictly positive definite, the $\{d_{\text{Diffusion, t}} \}_{t\geq 1}$ is the true metric. \item $d_{\text{Diffusion, 2t}}^2(x, y)$ is the Euclidean distance between the columns of indices $x$ and $y$ of $\mathcal{A}^m$, i.e. \begin{align*} d_{\text{Diffusion, 2t}}^2(x, y) &= \int_\Gamma |a^{t}(x,z)-a^{t}(y,z)|^2 d\mu(z) = ||a^{t}(x,\cdot)-a^{t}(y,\cdot)||^2. \end{align*} \item The diffusion metric $d_{\text{Diffusion, t}}$ is equal to the weighted Euclidean distance in the embedding space with the weights $\lambda_i^t$, i.e. \begin{align*} d_{\text{Diffusion, t}}^2 (x, y)&= \sum_{i\geq 0}^{N-1} \lambda_i^t \big(\phi_i(x)-\phi_i(y)\big)^2. \end{align*} \end{itemize} \subsection{Vector Diffusion Maps (2011, A.Singer and H.-T. Wu)} The Laplacian operator $\Delta$ can be extended to act on the tangent bundle $TM$ of the Riemannian manifold $(M^d, g)$. It is defined as the trace of the second covariant derivative with the metric $g$. Mathematically, for any tensor field $F \in \Gamma_l^k(M)$ \begin{align*} \Delta F:= \text{tr } \nabla^2 F \end{align*} where $\nabla^2$ is the second covariant derivative, i.e. for any vector field $X$ and $Y$ \begin{align*} \nonumber \nabla^2 F(\omega^1,\dots, \omega^l, Y_1, \dots, Y_k, X, Y)=& \nabla_X \big( \nabla_Y F(\omega^1,\dots, \omega^l, Y_1, \dots, Y_k)\big)-\\ & \nabla_{\nabla_X Y}F(\omega^1,\dots, \omega^l, Y_1, \dots, Y_k). \end{align*} Thus we have \begin{align*} \Delta F = \sum_{i=1}^d \nabla^2 F(\dots, E_i, E_i). \end{align*} \\\\ In the classical elliptic theory, $e^{t\Delta}$ has kernel of the following form \begin{align*} k_t(x,y)=\sum_{i=0}^\infty e^{-\lambda_it} X_i(x) \cdot \overline{X_i(y)} \end{align*} where $0\leq \lambda_0\leq \lambda_1 \dots $ and $X_i$ are the associated eigenvector fields satisfying \begin{align*} \Delta X_i = -\lambda_i X_i. \end{align*} Moreover, the eigenvector fields $X_i$ for the Laplacian operator $\Delta$ form an orthonormal basis of $L^2(TM)$. Note that the Laplacian defined on a tangent bundle holds the positive trace and thus all the signs for the equations are opposite to those in Appendix C \& D. \\\\ Define the vector diffusion map $[\mathcal{VD}_t]: M \rightarrow l^2$ \begin{align*} [\mathcal{VD}_t]: x \mapsto \big(e^{\frac{(\lambda_i+\lambda_j)t}{2}}\langle X_i(x), X_j(x)\rangle \big)_{i,j=0}^\infty \end{align*} \subsubsection{Note} \begin{itemize} \item The vector diffusion map is a diffeomorphic embedding of $M$ into $l^2$. \item The vector diffusion distance is given by \begin{align*} d_\text{VDM,t}(x,y):=\big|\big| [\mathcal{VD}_t](x)- [\mathcal{VD}_t](y)\big|\big|_{l^2}, \end{align*} which has an asymptotic expansion. For any $x, y \in M$ with $y=\text{exp}_x v$, where $v\in T_x M$ and $||v||^2 < t< 1$, then \begin{align*} d_\text{VDM,t}^2(p,q) =\frac{d}{4\pi^{d}} \frac{||v||^2}{t^{d+1}}+ O\left(\frac{1}{t^{d}}\right). \end{align*} \end{itemize} \section{Approximation to the Laplace-Beltrami Operator} In this section, we discuss the core techniques of the convergence issue for the three algorithms. In the literature, the difference between the graph Laplacian operator and the Laplace-Beltrami operator contains two parts, the \emph{variance term} and the \emph{bias term}. Variance term establishes the convergence of the graph Laplacian to some continuous operator called the averaging operator and the bias term establishes the convergence of this continuous operator to the Laplace-Beltrami operator on manifold. The two terms are related to the time parameter and the quantities of the data samples. The following diagram exposes this relation \begin{align*} \text{Graph Laplacian } \bar{\mathcal{L}}_{\epsilon, N} \overset{N\rightarrow \infty}{\longrightarrow} \text{Averaging } \mathcal{A}_\epsilon \overset{\epsilon \rightarrow 0^+}{\longrightarrow}\text{Laplace-Beltrami } \mathcal{L} (\text{or }\Delta). \end{align*} Thus, to show the convergence is to reduce the \emph{variance} term and the \emph{bias} term. In the following section, we will show the idea of the convergence issue of each algorithm one by one. The reference includes EigenMap \cite{belkin2003problems, belkin2003laplacian, von2008consistency}, Diffusion Map \cite{lafon2004diffusion, coifman2006diffusion} and Vector Diffusion Map \cite{singer2012vector}. \subsection{EigenMap (2003, M.Belkin and P.Niyogi)} Let the Laplace-Beltrami operator $\mathcal{L}^t$ at time $t$ be \begin{align*} [\mathcal{L}^t f](p) = (4\pi t)^{-\frac{d+2}{2}}\cdot \int_{M(q)} e^{-\frac{||p-q||^2}{4t}}[f(p)-f(q)] \end{align*} and, the graph Laplacian operator $\mathcal{L}_N^t$ at time $t$ \begin{align*} [\mathcal{L}_N^t f](p) = \frac{(4\pi t)^{-\frac{d+2}{2}}}{N}\cdot \sum_{x_i} e^{-\frac{||p-x_i||^2}{4t}}[f(p)-f(x_i)] \end{align*} where $x_i\in \{x:0<||p-x||<\epsilon\}$.\\\\ The main structural result of this algorithm is as follows \begin{mdframed}[backgroundcolor=blue!5] \vskip 0.2cm \textbf{Main Result:} Suppose the data $\{x_i\}$ is i.i.d and uniformly distributed on $M$. Then \begin{align} \text{Eigen } \mathcal{L}_N^t \overset{N\rightarrow \infty}{\longrightarrow} \text{Eigen } \mathcal{L}^t \overset{t\rightarrow 0^+}{\longrightarrow}\text{Eigen } \mathcal{L} \end{align} where the first approximation means that the eigenfunctions and the associated eigenvectors of $\mathcal{L}_N^t$ approach to the ones of $\mathcal{L}^t$ almost surely as the number of samples blows up, and, the second means that the eigenvalues and the associated eigenfunctions of $\mathcal{L}^t$ approach to those of $\mathcal{L}$ as time $t$ approaches to $0^+$. \end{mdframed} \vskip 0.5cm Let $\{\lambda_i\}$, $\{\lambda_{i}^t\}$ and $\{\lambda_{N,i}^t\}$ be the eigenvalues for $\mathcal{L}$, $ \mathcal{L}^t $ and $\mathcal{L}_N^t$ respectively. And, $\{\phi_i\}$, $\{\phi_{i}^t\}$ and $\{\phi_{N,i}^t\}$ are the associated eigenvectors with respect to $\{\lambda_i\}$, $\{\lambda_{i}^t\}$ and $\{\lambda_{N,i}^t\}$ respectively. Then the main result above says for all $i$, we have almost surely \begin{align*} \lim_{t\rightarrow 0} \lim_{N\rightarrow \infty} &|\lambda_{N,i}^t-\lambda_i|=0,\\ \lim_{t\rightarrow 0} \lim_{N\rightarrow \infty} &||\phi_{N,i}^t-\phi_i||_{L^2(M)}=0. \end{align*} \emph{Basic Idea of Proof:}\\\\ Denote the heat operator $\mathcal{H}^t$ at time $t$ as \begin{align*} [\mathcal{H}^tf](x):=\int_{M(y)} u_y(x,t) f(y), \end{align*} and recall that the Laplace-Beltrami operator $\mathcal{L}$ is \begin{align*} [\mathcal{L}f](x)&= \lim_{t\rightarrow 0^+} [f(x)-\int_{M(y)} u_y(x, t)f(y)]/t \\ &=\lim_{t\rightarrow 0^+} [\frac{1-\mathcal{H}^t}{t}f](x). \end{align*} The approximate operator $\frac{1-\mathcal{H}^t}{t}$ does not converge uniformly to $\mathcal{L}$ in the sense that\begin{align*} \sup_{||f||_{L^2}=1} ||[\frac{1-\mathcal{H}^t}{t}f]-[\mathcal{L}f]||_{L^2(M)} \not\rightarrow 0. \end{align*} Consider a perturbation operator $\mathcal{R}^t: L^2(M)\rightarrow L^2(M)$ at time $t$ \begin{align*} \mathcal{R}^t:=\frac{1-\mathcal{H}^t}{t}-\mathcal{L}^t. \end{align*} By the result in \cite[Theorem 4.1]{belkin2003laplacian}, we have \begin{align*} \lim_{t\rightarrow 0^+} \sup_{||f||_{L^2}=1} \frac{\langle \mathcal{R}^tf, f \rangle}{\langle \frac{1-\mathcal{H}^t}{t}f, f \rangle}=0, \end{align*} which implies the eigenvalues and associated eigenfunctions of the approximate operator $\frac{1-\mathcal{H}^t}{t}$ converge to the ones of $\mathcal{L}^t$. Observe that $\mathcal{L}$ and $\frac{1-\mathcal{H}^t}{t}$ share the same eigenfunctions. Thus we get the second approximation of the main result, i.e. Eigen $\mathcal{L}^t \overset{t\rightarrow 0^+}{\longrightarrow}\text{Eigen } \mathcal{L}$. The variance term part can be found in \cite{von2008consistency}. \subsection{Diffusion Maps (2004, S. Lafon)} Consider the rotation invariant kernel, i.e. \begin{align*} k(x, y)=h(||(x,y)||^2) \end{align*} where the map $u\mapsto h(u^2)$ must be chosen as the Fourier transform of a finite positive measure by the Bochner's theorem which guarantees the positivity of the kernel \cite{bochner1941hilbert}. Define the $\epsilon$-kernel $k_\epsilon(x,y)$ by \begin{align} k_\epsilon(x, y):= h\left(\frac{||x-y||^2}{\epsilon}\right). \end{align} \\\\ Suppose we are given a class $\{E_K\}_{K>0}$ of functions $f \in C^\infty(M)$ satisfying \begin{itemize} \item For all multiple index $\alpha=(\alpha_1,\dots, \alpha_d)$ \begin{align*} ||\frac{\partial^{|\alpha|} f}{\partial x_1^{\alpha_1} \dots \partial x_d^{\alpha_d}}||_{L^2(M)}\leq K^{|\alpha|} \cdot ||f||_{L^2(M)}. \end{align*} \item For all $x \in \partial M$ \begin{align*} \frac{\partial f}{\partial r}(x) =0, \end{align*} where $r$ is a tangent vector at $x$ that is normal to $\partial M$. \end{itemize} One property of $\{E_K\}_{K>0}$ is as follows \begin{align*} \overline{\bigcup_{K>0} E_K}=L^2(M). \end{align*} \\ In the original paper \cite{lafon2004diffusion}, the authors approximate the Laplace-Beltrami operator step by step. The first infinitesimal generator $G_\epsilon$ consists of curvature potential term. Then, the authors normalize the graph Laplacian, which works well for the uniformly distributed data on $M$. Eventually, they modify the kernel and the averaging operator by separating the geometry of $M$ from the distribution of the points and thus get it. \subsubsection{Step 1: The infinitesimal generator $G_\epsilon$} Consider an infinitesimal generator $G_\epsilon$ \begin{align*} [G_\epsilon f](x):=\frac{1}{\epsilon^{\frac{d}{2}}} \int_{M(y)} k_\epsilon(x,y) f(y) \end{align*} which has an asymptotic expansion, i.e. for any $x\in M/\partial M$ \begin{align*} [G_\epsilon f] (x) = \left( \int_{\mathbb{R}^d} h(||u||^2)du\right) f(x) + \frac{\epsilon \cdot \int_{\mathbb{R}^d}u_i^2 \cdot h(||u||^2)du}{2} \big(E(x)f(x)-\nabla f(x)\big) + O(\epsilon^{\frac{3}{2}}) \end{align*} where $a_i(x)$ is the curvature function of the coordinate geodesics at any point $x \in M$ and \begin{align*} E(x)= \sum_{i=1}^d [a_i(x)^2-\sum_{j \neq i}a_i(x)\cdot a_j(x)]. \end{align*} \subsubsection{Note} \begin{itemize} \item The infinitesimal generator $G_\epsilon$ combines the intrinsic geometry (the Laplace-Beltrami operator) and the extrinsic geometry (the curvature potential). \item The curvature potential term $E(x)$ of the infinitesimal generator $G_\epsilon$ is zero when the manifold is a vector subspace of $\mathbb{R}^D$. \end{itemize} \subsubsection{Step 2: The Averaging Operator $\mathcal{A_\epsilon}$} Suppose $p(y)$ is the density function for the measure $\omega_g$ on $M$, i.e. $\omega_g(y) =p(y) dy$. We then introduce the averaging operator $\mathcal{A_\epsilon}$ with the parameter $\epsilon$ via the general normalizing routine of the graph Laplacian \begin{align*} [A_\epsilon f](x) := \frac{1}{v_\epsilon^2(x)}\int_{M(y)} k_\epsilon(x,y)f(y) \cdot p(y)dy, \end{align*} where \begin{align*} v_\epsilon^2(x) = \int_{M(y)} k_\epsilon (x,y)\cdot p(y)dy, \end{align*} which has an asymptotic expansion: for any $f\in E_K$ and $x\in M/ \partial M$ \begin{align*} [\mathcal{A}_\epsilon f](x) =f(x) + \frac{\epsilon \cdot \int_{\mathbb{R}^d}u_i^2 \cdot h(||u||^2)}{2\cdot \int_{\mathbb{R}^d} h(||u||^2) } \cdot \left(\frac{\Delta p(x)}{p(x)}f(x)-\frac{\Delta (p\cdot f)(x)}{p(x)}\right) +O(\epsilon^{\frac{3}{2}}). \end{align*} \\\\ Define the graph Laplacian operator $\bar{\mathcal{L}}_\epsilon$ with the parameter $\epsilon$ as \begin{align*} \bar{\mathcal{L}}_\epsilon:=\frac{I-A_\epsilon}{\epsilon}. \end{align*} On the space $E_K$, we have \begin{align*} \lim_{\epsilon \rightarrow 0^+} \bar{\mathcal{L}}_\epsilon = \mathcal{H}, \end{align*} where \begin{align*} [\mathcal{H} f](x) &:=\frac{ \int_{\mathbb{R}^d}u_i^2 \cdot h(||u||^2)}{2\cdot \int_{\mathbb{R}^d} h(||u||^2)} \cdot \left(\frac{\Delta (p\cdot f)(x)}{p(x)}-\frac{\Delta p(x)}{p(x)}f(x)\right)\\ &=\frac{ \int_{\mathbb{R}^d}u_i^2 \cdot h(||u||^2)}{2\cdot \int_{\mathbb{R}^d} h(||u||^2)} \cdot \left( \Delta f(x) +2 \langle \frac{\nabla p(x)}{p(x)}, \nabla f(x) \rangle \right). \end{align*} \subsubsection{Note} \begin{itemize} \item When the data is uniformly distributed over $M$, the limit operator $\mathcal{H}$ is a multiple of the Laplace-Beltrami operator on $M$. \item The (weighted) graph Laplacian will not approximate the Laplace-Beltrami operator in the case of non-uniform densities. \end{itemize} \subsubsection{Step 3: Modified Averaging Operator $\mathcal{A}_\epsilon$} Construct the approximation density $p_\epsilon (x)$ with parameter $\epsilon$ by \begin{align*} p_\epsilon (x) = \int_{M(y)} k_\epsilon (x, y). \end{align*} Now replace $k_\epsilon$ by \begin{align*} \tilde{k}_\epsilon(x,y):=\frac{k_\epsilon(x,y)}{p_\epsilon(x)\cdot p_\epsilon(y)}, \end{align*} and let \begin{align*} v_\epsilon^2(x) = \int_{M(y)} \widetilde{k_\epsilon}(x,y). \end{align*} Then the modified averaging operator is $\mathcal{A}_\epsilon : L^2(M)\rightarrow L^2(M)$, \begin{align*} [\mathcal{A_\epsilon}f](x):=\frac{1}{v_\epsilon^2(x)} \int_{M(y)} \tilde{k}_\epsilon(x,y) f(y) \end{align*} By the Laplace operator $\mathcal{L}_\epsilon$ with the parameter $\epsilon$ on $M$ is defined \begin{align*} \mathcal{L}_\epsilon := \frac{I-A_\epsilon}{\epsilon}, \end{align*} which has an asymptotic expansion: for any $f\in E_M$ and $x\in M/\partial M$, then \begin{align*} [\mathcal{A_\epsilon}f](x)=f(x)- \frac{\epsilon \cdot \int_{\mathbb{R}^d}u_i^2 \cdot h(||u||^2)}{2\cdot \int_{\mathbb{R}^d} h(||u||^2)} \Delta f(x) +O(\epsilon^{\frac{3}{2}}), \end{align*} and on $E_K$, we have \begin{align*} \lim_{\epsilon \rightarrow 0^+} \mathcal{L}_\epsilon = \frac{2 \cdot \int_{\mathbb{R}^d}u_i^2 \cdot h(||u||^2)}{\int_{\mathbb{R}^d} h(||u||^2)} \cdot \Delta (:=\Delta_0). \end{align*} Moreover, since the modified operator $A_\epsilon$ is compact, we have \begin{align*} \lim_{\epsilon \rightarrow 0^+} \mathcal{A_\epsilon}^{-\frac{t}{\epsilon}} = e^{-t\Delta_0}=\sum_{i\geq 0} \lambda_{\epsilon, i}^\frac{t}{\epsilon} P_{\epsilon, i}, \end{align*} where $P_{\epsilon, i}$ is the orthogonal projector on the eigenspace associated to the eigenvalues $\lambda_{\epsilon, i}$. \\\\ In other words, the heat kernel $u_y(x,t)$ on $M$ can be approximated by $a_\epsilon^\frac{t}{\epsilon}(x,y)$ and we get \begin{align*} \lim_{\epsilon \rightarrow 0+} \lambda_{\epsilon, i}^\frac{t}{\epsilon} &= e^{-t\lambda_i},\\ \lim_{\epsilon \rightarrow 0+} P_{\epsilon, i} &=P_i \end{align*} which implies the eigenvalues and eigenfunctions of the Laplace-Beltrami operator coincide with those of the limit of the modified averaging operator. \subsection{Vector Diffusion Maps (2011, A. Singer and H.-T. Wu)} Let the data $\{x_i\}_{i=1}^N$ be i.i.d. with respect to a uniformly bounded probability density function $p(x)$ supported on $M$, i.e. $0< a \leq p(x) \leq b < \infty$ for any $x \in M$. In this part, we use the convention $\iota(x_i)$ to represent the data $x_i$ in the embedding space. \subsubsection{Step 1: Approximation to the Parallel Transport Operator} The authors of this algorithm collect the basis of the local tangent space via the local PCA and then they align them to approximate the parallel transport operator on manifolds. \\\\ Recall Section 2.2 of Chapter 2. If we pick the parameter $\epsilon_{\text{PCA}} = O(N^{-\frac{2}{d+2}})$ of the method of the local PCA, we consider $x_i, x_j \not\in M_{\sqrt{\epsilon_{\text{PCA}}}}=\{x\in M: \min_{y\in \partial M}d_g(x,y) \leq {\sqrt{\epsilon_{\text{PCA}}}}$ but $d_g(x_i, x_j)=O(\sqrt{\epsilon})$. Then the $d\times d$ orthogonal transformation $O_{ij}(:=U V^T$, with the SVD of $O_i^T O_j=U \Sigma V^T$) will approximate$P_{x_i, x_j}$ in the following sense: for any $X\in C^3(TM)$ \begin{align*} O_{ij}\left(\langle \iota_*X(x_j), u_l(x_i) \rangle \right)_{l=1}^d = \left(\langle \iota_*P_{x_i, x_j} X(x_j), u_l(x_i) \rangle \right)_{l=1}^d + O\left(\epsilon_{\text{PCA}}^{\frac{3}{2}}+\epsilon^{\frac{3}{2}}\right), \end{align*} where $\{u_l(x_i)\}_{l=1}^d$ is an orthonormal basis determined by the local PCA. For $x_i, x_j \in M_{\sqrt{\epsilon_{\text{PCA}}}}$, we have that for any $X\in C^3(TM)$, \begin{align*} O_{ij}\left(\langle \iota_*X(x_j), u_l(x_i) \rangle \right)_{l=1}^d = \left(\langle \iota_*P_{x_i, x_j} X(x_j), u_l(x_i) \rangle \right)_{l=1}^d + O\left(\epsilon_{\text{PCA}}^{\frac{1}{2}}+\epsilon^{\frac{3}{2}}\right). \end{align*} \subsubsection{Step 2: Normalized Kernel and Normalized Connection-Laplacian of the Graph} The following steps are as a routine as in Diffusion Map. Firstly, we need to introduce the normalized kernel. Given the local information of a submanifold, define $K_\epsilon (x_i, x_j)$ by \begin{align*} K_\epsilon (x_i, x_j) := K \left( \frac{||\iota(x_i)-\iota(x_j)||_{\mathbb{R}^D}}{\sqrt{\epsilon}} \right), \end{align*} where $||\iota(x_i)-\iota(x_j)||_{\mathbb{R}^D}<\sqrt{\epsilon}$. Then, we define an estimated probability density distribution by \begin{align*} p_\epsilon(x_i):=\sum_{j=1}^N K_\epsilon(x_i, x_j) \end{align*} and the $\alpha$-normalized kernel $K_{\epsilon, \alpha}$ $(0\leq \alpha \leq 1)$ by \begin{align*} K_{\epsilon, \alpha}(x_i, x_j) := \frac{K_\epsilon(x_i, x_j)}{p_\epsilon^\alpha(x_i)\cdot p_\epsilon^\alpha(x_j)}. \end{align*} \\\\ Denote the averaging operator for the vector fields, for a fixed $\epsilon$ by \begin{align*} [D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}](\bar{{X}_i}):= \frac{\sum_{j=1}^N K_{\epsilon,\alpha}(x_i, x_j)O_{ij}\bar{X}_j}{\sum_{j=1}^N K_{\epsilon, \alpha}(x_i, x_j)}, \end{align*} which can be regarded as the transportation of the vector fields from $T_{x_j}M$ to $T_{x_i}M$ and then averaging them at $T_{x_i}M$. Thus, the \textbf{normalized connection-Laplacian} $[D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}-I]$ on the data graph is defined by \begin{align*} [D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}-I](\bar{{X}_i})= \frac{\sum_{j=1}^N K_{\epsilon,\alpha}(x_i, x_j)O_{ij}\bar{X}_j}{\sum_{j=1}^N K_{\epsilon, \alpha}(x_i, x_j)}-\bar{{X}_i}. \end{align*} Recall the normalized Laplacian is formally denoted as \begin{align*} L_{\text{RW}}:=D^{-1}L=D^{-1}(D-W)=I-D^{-1}W, \end{align*} where $D$ and $W$ is the diagonal and weight matrix on a graph respectively. \subsubsection{Step 3: Approximation to the Heat Kernel of the Connection-Laplacian} Define the averaging operator $\mathcal{A}_{\epsilon, \alpha}$ as \begin{align*} [\mathcal{A}_{\epsilon, \alpha}X](x):= \frac{\int_{M(y)} K_{\epsilon, \alpha}(x,y)P_{x, y}X(y)}{\int_{M(y)} K_{\epsilon, \alpha}(x,y)}, \end{align*} which has an asymptotic expansion: for $X\in C^3(TM)$ and $x \not\in M_{\sqrt{\epsilon_{\text{PCA}}}}$, then \begin{align*} [\mathcal{A}_{\epsilon, \alpha}X](x) = X(x) + \frac{\epsilon \cdot m_2}{2d \cdot m_0}\left\{ \Delta X(x) + d\cdot \frac{\int_{S^{d-1}}\nabla_\theta X(x)\cdot \nabla_\theta(p^{1-\alpha})(x)d\theta}{p^{1-\alpha}(x)} \right\} +O(\epsilon^2), \end{align*} where $m_l = \int_{\mathbb{R}^d} ||x||^l \cdot K(||x||)dx$. \\\\ In particular, \begin{align*} [\mathcal{A}_{\epsilon, 1}X](x) = X(x) + \frac{\epsilon \cdot m_2}{2d \cdot m_0}\Delta X(x) +O(\epsilon^2). \end{align*} The asymptotic expansion of the averaging operator $\mathcal{A}_{\epsilon, \alpha}$ contains the connection-Laplacian and potential term, and when $\alpha=1$, the potential term vanishes. \\\\ The theorem in \cite[Theorem 5.3]{singer2012vector} implies that the averaging operator approximates the heat kernel $e^{-t\Delta}$ in $L^2(M)$, i.e. \begin{align*} \lim_{\epsilon \rightarrow 0^+} \mathcal{A}_{\epsilon, 1}^{\frac{t}{\epsilon}} = e^{-t\Delta}. \end{align*} \subsubsection{Step 4: Computation via the Connection-Laplacian Operator of Graph} In this step, we will prove the matrix $D_\alpha^{-1}S_\alpha-I$ where $0\leq \alpha \leq 1$ converges to the connection-Laplacian operator and the potential term. In particular, $D_1^{-1} S_1-I$ converges to the connection-Laplacian operator called the connection-Laplacian on a graph in the literature. According to the work of this step, we can compute the $i$\textsuperscript{th} eigenvector field of $D_1^{-1} S_1-I$, which is a discrete approximation of the $i$\textsuperscript{th} eigenvector field of the connection-Laplacian $\Delta$ over $M$. \\\\ The following equations describe the relations between the normalized connection-Laplacian on a graph and averaging operator. \begin{itemize} \item For $x_i \not\in M_{\sqrt{\epsilon_{\text{PCA}}}}$, we have \begin{align} [D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}-I](\bar{{X}_i})= \left(\langle \iota_*[\mathcal{A}_{\epsilon, \alpha}X](x_i) \cdot X(x_j), u_l(x_i) \rangle \right)_{l=1}^d + O(\frac{1}{N^{\frac{1}{2}}\epsilon^{\frac{d}{4}-\frac{1}{2}}}+\epsilon_{\text{PCA}}^{\frac{3}{2}}+\epsilon^{\frac{3}{2}}), \end{align} where $\bar{X}_i:=\left(\langle \iota_* X(x_i), u_l(x_i) \rangle \right)_{l=1}^d \in \mathbb{R}^d$. \item For $x_i \in M_{\sqrt{\epsilon_{\text{PCA}}}}$, we have \begin{align} [D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}-I](\bar{{X}_i}) = \left(\langle \iota_* [\mathcal{A}_{\epsilon, \alpha}X](x_i) \cdot X(x_j), u_l(x_i) \rangle \right)_{l=1}^d + O(\frac{1}{N^{\frac{1}{2}}\epsilon^{\frac{d}{4}-\frac{1}{2}}}+\epsilon_{\text{PCA}}^{\frac{1}{2}}+\epsilon^{\frac{3}{2}}), \end{align} where $\bar{X}_i:=\left(\langle \iota_* X(x_i), u_l(x_i) \rangle \right)_{l=1}^d \in \mathbb{R}^d$. \end{itemize} According to the operator relation (3.3.3) \& (3.3.4) and geometric relations in Section 3.1, we have the following structural results if the manifold has no boundary. \begin{itemize} \item For $\epsilon = O(N^\frac{2}{d+2})$ and $X \in C^3(TM)$, with high probability \begin{align*} \nonumber &\frac{1}{\epsilon}[D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}-I](\bar{{X}_i})\\\nonumber = & \frac{m_2}{2d\cdot m_0} \left( \langle \iota_* \left\{ \Delta X(x_i) + d\cdot \frac{\int_{S^{d-1}}\nabla_\theta X(x_i)\cdot \nabla_\theta(p^{1-\alpha})(x_i)d\theta}{p^{1-\alpha}(x_i)} \right\}, e_l(x_i) \rangle \right)_{l=1}^d \\ &+ O(\epsilon^{\frac{1}{2}}+N^{-\frac{3}{d+2}} \epsilon^{-1}+N^{-\frac{1}{2}}\epsilon^{-\frac{d}{4}+\frac{1}{2}}), \end{align*} where $\{e_l(x_i)\}_{l=1}^d$ is an orthonormal basis for $\iota_*T_{x_i}M$. \\\\ In particular, when $\alpha=1$ \begin{align*} &\frac{1}{\epsilon}[D_{\epsilon,1}^{-1}S_{\epsilon,1}-I](\bar{{X}_i})\\ =& \frac{m_2}{2d\cdot m_0} \left( \langle \iota_* \Delta X(x_i), e_l(x_i) \rangle \right)_{l=1}^d + O(\epsilon^{\frac{1}{2}}+ N^{-\frac{3}{d+2}}\epsilon^{-1}+N^{-\frac{1}{2}}\epsilon^{-\frac{d}{4}+\frac{1}{2}}). \end{align*} \item For $\epsilon = O(N^\frac{2}{d+4})$ and $X \in C^3(TM)$, almost surely \begin{align*} \lim_{N\rightarrow \infty} \frac{1}{\epsilon}&[D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}-I](\bar{{X}_i})\\ =& \frac{m_2}{2d\cdot m_0}\left( \langle \iota_* \left\{ \Delta X(x_i) + d\cdot \frac{\int_{S^{d-1}}\nabla_\theta X(x_i)\cdot \nabla_\theta(p^{1-\alpha})(x_i)d\theta}{p^{1-\alpha}(x_i)} \right\}, e_l(x_i) \rangle \right)_{l=1}^d. \end{align*} In particular, when $\alpha=1$, we have \begin{align*} \lim_{N \rightarrow \infty} \frac{1}{\epsilon}[D_{\epsilon,1}^{-1}S_{\epsilon, 1}-I](\bar{{X}_i}) = \frac{m_2}{2d\cdot m_0} \left( \langle \iota_* \Delta X(x_i), e_l(x_i) \rangle \right)_{l=1}^d. \end{align*} \end{itemize} When the manifold has boundary, we have for $x_i \in M_{\sqrt{\epsilon}}$ \begin{align*} &[D_{\epsilon,\alpha}^{-1}S_{\epsilon, \alpha}](\bar{{X}_i})\\ =&\left( \langle \iota_* P_{x_i, x_0} \left( X(x_0)+\frac{m_1^\epsilon}{m_0^\epsilon}\nabla_{\partial_r} X(x_0) \right), e_l(x_i) \rangle \right)_{l=1}^d +O(\epsilon+N^{-\frac{3}{2(d+1)}}+N^{-\frac{1}{2}}\epsilon^{-\frac{d}{4}-\frac{1}{2}}). \end{align*} where $x_0 =\argmin_{y\in\partial M}d(x_i,y)$, constant $m_1^\epsilon=O(\epsilon^{\frac{d}{2}})$ and constant $m_0^\epsilon=O(\epsilon^{\frac{d}{2}+\frac{1}{2}})$. The formal definition of $m_1^\epsilon$ and $m_0^\epsilon$ are in \cite[B 6]{singer2012vector}. The value $\partial_r$ is the normal direction to the boundary at $x_0$. \subsection{Framework under the Weighted Laplacian (2005, M. Hein, J-Y Audibert and U.V. Luxburg)} Observe that the bias term contains the potential term in the asymptotic expansion of the averaging operator. Thus Hein, Audibert and Luxburg consider a generalized version of the convergence via modifying the Laplacian to $\mu$-Laplacian $\Delta_\mu$. In their framework, they show the convergence of the averaging operator to the $\mu$-Laplacian.\\\\ Let $\mu$ be a measure on $M$ defined by \begin{align*} d\mu := h^2 \omega_g, \end{align*} where $h$ is a smooth positive function on $M$. Then, the Laplace operator $\Delta_\mu$ of $(M, \mathcal{B}(M), \omega_g)$ is \begin{align*} \Delta_\mu:=\text{div}_\mu \circ \nabla = \frac{1}{h^2} \text{div}(h^2 \nabla) =\Delta + 2\frac{\langle \nabla h, \nabla \rangle}{h}. \end{align*}\\ Since the $\mu$-Laplacian has all the properties as the Laplacian on manifolds (see \cite{grigor2006heat} for details), we could also define the averaging operator $\mathcal{A}_{\epsilon, \mu}$ approaching to the $\mu$-Laplacian $ \Delta_\mu$ when the parameter $\epsilon$ approaches $0^+$. Despite the generalized version of the Laplacian, the main achievement of their approach is that they reduce the bias and variance term simultaneously. For more details, please refer to \cite{hein2005graphs}. \chapter{Summary} In this survey, we talk about the some of the most popular techniques used today for nonlinear data reduction algorithms including ISOMAP, LLE, EigenMap, Hessian EigenMap, MVU, LTSA, Diffusion Maps and Vector Diffusion Maps. These algorithms are also called Manifold learning algorithms, since we assume the high dimensional data are located on an embedding submanifolds in higher dimensional Euclidean space and then develop the learning theory in this case. In Chapter two, we consider the features from these eight algorithms. We group them as geometric properties and topological properties. Firstly, we get the local information by the local linearity method and the local PCA method. Then, we patch all the local information to a global version. Each algorithm is designed for a special merit of the dimensionality reduction. In the last section, we compare each algorithm via the numerical experiments in the following aspects: computational speed, geometry, noise, distribution, clustering, high dimension, and parameter sensitivity. In Chapter three, we discuss the convergence issue including the algorithm EigenMap, Diffusion Maps and Vector Diffusion Map. We talk about the embedding relation in Section 3.1 and reformulate EigenMap, Diffusion Map and Vector Diffusion Map in the language of Operator theory. Section 3.3 talks about the convergence issue of these three algorithms. In light of the discussion in these notes, we provide a roughly procedure to acquire a good lower dimensional representation for the higher dimensional data. PCA should be regarded as the most efficient way since it has lowest computation complexity. It takes only seconds to run and can be performed in space with high dimensionality. However, for special data sets with some geometric structure, we should use the true manifold learning algorithms. It's still a question which the best algorithm are when we apply them to the special data set. There are several unknown parameters in the algorithms and there is no criteria for the procedure of picking parameters. For example, for several algorithms, how to guarantees the convergence issue to a solution in the limit of a large data set. In general, we have to run the algorithms one by one and pick the parameters by the experience and randomly in some sense. After the last algorithm (Vector Diffusion Maps) which is purposed in 2011, several new Manifold leaning algorithms came out, for example, t-SNE, Auto-encoder, XOM and etc. The new algorithms performs well in some cases but the major challenges still remain. Since of these challenges, this field or research are still active and charming for the new generation of mathematicians.
{'timestamp': '2022-03-22T01:30:01', 'yymm': '2008', 'arxiv_id': '2008.06853', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06853'}
arxiv
\section{Introduction} Sorting all values in $A+B$, where $A$ and $B$ are arrays of length $n$ and $A+B$ is the Cartesian product of these arrays under the $+$ operator, is nontrivial. In fact, there is no known approach faster than naively computing and sorting them which takes $O(n^2 \log(n^2))=O(n^2 \log(n))$\cite{bremner:necklaces}; however, Fredman showed that $O(n^2)$ comparisons are sufficient\cite{fredman:good}, though no $O(n^2)$ algorithm is currently known. In 1993, Frederickson published the first optimal $k$-selection algorithm on $A+B$ with runtime $O(n + k)$\cite{frederickson:optimal}. In 2018, Kaplan \emph{et al.} described another optimal method for $k$-selection on $A+B$, this time in terms of soft heaps\cite{kaplan:selection}\cite{chazelle:soft}. In 1978, Johnson and Mizoguchi \cite{johnson:selecting} extended the problem to selecting the $k^{th}$ element in $X_1 + X_2 + \cdots + X_m$ and did so with runtime $ O(m\cdot n^{\lceil\frac{m}{2}\rceil} \log(n))$; however, there has not been significant work done on the problem since. If only the $k^{th}$ value is desired then Johnson and Mizoguchi's method is the fastest known when $k > m\cdot n^{\lceil\frac{m}{2}\rceil}\log(n)$. Selection on $X_1 + X_2 + \cdots + X_m$ is important for max-convolution\cite{bussieck:fast} and max-product Bayesian inference\cite{serang:fast,pfeuffer:bounded}. Computing the $k$ best quotes on a supply chain for a business, when there is a prior on the outcome (such as components from different companies not working together) becomes solving the top values of a probabilistic linear Diophantine equation \cite{kreitzberg:toward} and thus becomes a selection problem. Finding the most probable isotopologues of a compound such as hemoglobin, $C_{2952}H_{4664}O_{832}N_{812}S_8Fe_4$, may be done by solving $C +H + O+N +S+Fe$, where $C$ would be the most probable isotope combinations of 2,952 carbon molecules (which can be computed via a multinomial at each leaf, ignored here for simplicity), $H$ would be the most probable isotope combinations of 4,664 hydrogen molecules, and so on. The selection method proposed in this paper has already been used to create the world's fastest isotopologue calculator\cite{kreitzberg:fast}. \subsection{Layer-ordered heaps} In a standard binary heap, the only known relationships are between a parent and a child: $A_i \leq A_{child(i)}$. A layer-ordered heap (LOH) has stricter ordering than the standard binary heap, but is able to be created in $\Omega\left(n\log(\frac{1}{\alpha-1})+\frac{n\cdot\alpha\cdot\log(\alpha)} {\alpha-1}\right) = \Omega(n)$ for constant $\alpha > 1$\cite{pennington:optimal}. $\alpha$ is the rank of the LOH and determines how fast the layers grow. A LOH partitions the array into several layers, $L_i$, which grow exponentially such that $\frac{|L_{i+1}|}{|L_{i}|}\approx \alpha$ and $|L_1|=1$. Every value in a layer $L_i$ is $\leq$ every value in proceeding layers $L_{i+1},L_{i+2}\ldots$ which we denote as $L_{i} \leq L_{i+1}$. If $\alpha = 1$ then all layers are size one and the LOH is sorted; therefore, to be constructed in $O(n)$ the LOH must have $\alpha > 1$. \subsection{Pairwise selection} Serang's method of selection on $A+B$ utilizes LOHs to be both optimal in theory and fast in practice. The method has four phases. Phase 0 is simply to LOHify (make into a layer-ordered heap) the input arrays. Phase 1 finds which layer products may be necessary for the $k$-selection. A layer product, $A^{(u)} + B^{(v)}$ is the Cartesian product of layers $A^{(u)}$ and $B^{(v)}$: $A_1^{(u)} + B_1^{(v)}, A_2^{(u)} + B_1^{(v)} , \ldots, A_1^{(u)} + B_2^{(v)}, \ldots$. Finding which layer products are necessary for the selection can be done using a standard binary heap. A layer product is represented in the binary heap in two separate ways: a min tuple $\lfloor (u,v)\rfloor = (min(A^{(u)} + B^{(v)}), (u,v), false)$ and a max tuple $\lceil (u,v)\rceil = (max(A^{(u)} + B^{(v)}), (u,v), true)$. Creating the tuples does not require calculating the Cartesian product of $A^{(u)} + B^{(v)}$ since $min(A^{(u)} + B^{(v)}) = min(A^{(u)}) + min(B^{(v)})$ which can be found in a linear pass of $A$ and $B$ separately. The same argument applies for $\lceil (u,v)\rceil$. $false$ and $true$ note that the tuple contains the minimum or maximum value in the layer, respectively. Also, let $false=0$ and $true=1$ so that a min tuple is popped before a max tuple even if they contain the same value. Phase 1 uses a binary heap to retrieve the tuples in sorted order. When a min tuple is popped, the corresponding max tuple and any neighboring layer product's min tuple is pushed (a set is used to ensure a layer product is only inserted once). When a max tuple is popped, a variable $s$ is increased by $|A^{(u)} + B^{(v)}|= |A^{(u)}| \cdot |B^{(v)}|$ and $(u,v)$ is appended to a list $q$. This continues until $s \geq k$. In phase 2 and 3 all max tuples still in the heap have their index appended to $q$, then the Cartesian product of all layer products in $q$ are generated. A linear time one-dimensional $k$-select is performed on the values in the Cartesian products to produce only the top $k$ values in $A+B$. The algorithm is linear in the overall number of values produced which is $O(k)$. In this paper we efficiently perform selection on $X_1 + X_2 + \cdots + X_m$ by combining the results of pairwise selection problems based on Serang's method. \section{Methods} In order to retrieve the top $k$ values from $X_1 + X_2 + \cdots + X_m$, a balanced binary tree of pairwise selections is constructed. The top $k$ values are calculated by selection on $X_1 + X_2, X_3 + X_4,\ldots$ then on $(X_1 + X_2) + (X_3 + X_4), (X_5 + X_6) + (X_7 + X_8),\ldots$. All data loaded and generated is stored in arrays which are contiguous in memory, allowing for great cache performance compared to a soft heap based method. \subsection{Tree construction} The tree has height $\lceil \log_2(m) \rceil$ with $m$ leaves, each one is a wrapper around one of the input arrays. Upon construction, the input arrays are LOHified in $O(n)$ time, which is amortized into the cost of loading the data. Each node in the tree above the leaves performs pairwise selection on two LOHs, one generated by its left child and one generated by its right child. All nodes in the tree generate their own LOH, but this is done differently for the leaves vs the pairwise selection nodes. When a leaf generates a new layer it simply allows its parent to have access to the values in the next layer of the LOHified input array. For a pairwise selection node, generating a new layer is more involved. \subsection{Pairwise selection nodes} Each node above the leaves is a pairwise selection node. Each pairwise selection node has two children which may be leaves or other pairwise selection nodes. In contrast to the leaves, the pairwise selection nodes will have to calculate all values in their LOHs by generating an entire layer at a time. Generating a new layer requires performing selection on $A+B$, where $A$ is the LOH of its left child and $B$ is the LOH of its right child. Due to the combinatorial nature of this problem, simply asking a child to generate their entire LOH can be exponential in the worst case so they must be generated one layer a time and only as necessary. The pairwise selection performed is Serang's method with a few modifications. The size of the selection is always the size of the next layer, $k=|L_i|$, to be generated by the parent. The selection begins in the same way as Serang's: a heap is used to pop min and max layer product tuples. When a min tuple, $\lfloor (u,v) \rfloor$ is popped the values in the Cartesian product are generated and appended to a list of values to be considered in the $k$-selection. The neighboring layer products inserted into the heap are determined using the scheme from Kaplan \emph{et al.} which differs from Serang's method. $\lceil (u,v) \rceil, \lfloor (u, 2v) \rfloor$, and $\lfloor (u,2v+1) \rfloor$ are always inserted and, if $v = 1$, $\lfloor (2u, v) \rfloor, \lfloor (2u+1,v) \rfloor$ are inserted as well. This insertion scheme will not repeat any indices and therefore does not require the use of a set to keep track of the indices in the heap. When any min tuple is proposed, the parent asks both children to generate the layer if it is not already available. If one or both children are not able to generate the layer (\emph{i.e.} the index is larger the full Cartesian product of the child's children) then the parent does not insert the tuple into its heap. The newly generated layer is simply appended to the parent's LOH and may now be accessed by the parent's parent. The dynamically generated layers should be kept in individual arrays, then a list of pointers to the arrays may be stored. This avoids resizing a single array every time a new layer is generated. Theorem 1 in \cite{serang:optimal} proves that the runtime of the selection is $O(k)$. Lemma 6 and 7 show that the number of items generated in the layer products is $O(n + k)$; however, lemma 7 may be amended to show that any layer product of the form $(u,1)$ or $(1,v)$ will generate $\leq \alpha\cdot |(u-1,1)| \in O(k)$ or $\leq \alpha\cdot |(1,v-1)| \in O(k)$ values, respectively, to show that the total values generated is $O(k)$. Thus the total number of values generated when a parent adds a new layer $L_i$ is $O(|L_i|)$. \begin{figure}[H] \centering \includegraphics[width=.45\textwidth]{figs/layer-products.pdf} \caption{\textbf{Left: Nine layer products of $A+B$. Right: The order in which the layer product tuples would pop from heap.} The two axes are LOHs generated by the left and right children. The values of all 18 possible layer product tuples are shown (nine min tuples in blue and nine max tuples in green). If $k=10$ then the tuples will be popped in the order shown on the right. After $(20, (3,1), true)$ is popped the total number of items in the Cartesian product of all max tuples is $\geq 10$. Note that the values in the layers are not necessarily in sorted order. \label{fig:layer-product}} \end{figure} \subsection{Selection from the root} In order to select the top $k$ values from $X_1 + X_2 + \cdots + X_m$, the root is continuously asked to generated new layers until the cumulative size the layers in their LOH exceeds $k$. Then a $k$-selection is performed on the layers to retrieve only the top $k$. The Cartesian product tree is constructed in the same way as the FastSoftTree\cite{kreitzberg:selection} and both dynamically generate new layers in a similar manner with the same theoretical runtime. The pairwise selection methods in both methods create at most $O(\alpha^2k)$. Thus the theoretical runtime of both methods is $O(n\cdot m + k\cdot m^{\log_2(\alpha^2)}$ with space usage $O(n\cdot m + k\log(m))$. \subsection{Wobbly version} In Serang's pairwise selection, after enough layer product tuples are popped from the heap to ensure they contain the top $k$ values, there is normally a selection performed. Strictly speaking, this selection is not necessary anywhere on the tree except for the root when the final $k$ values are returned. When the last max tuple $\lceil (u,v) \rceil$ is popped from the heap, $max(A^{(u)} + B^{(u)})$ is an upper bound on the $k^{th}$ value in the $k$-selection. Instead of doing a $k$-selection and returning the new layer, which requires a linear time selection followed by a linear partition, we can simply do a value partition on $max(A^{(u)} + B^{(u)})$. A new layer generated from only a value partition and not a selection is not guaranteed to be size $k$, it is at least size $k$ but contains all values $\leq max(A^{(u)} + B^{(u)})$. In the worst case, this may cause layer sizes to grow irregularly with a larger constant than $\alpha$. For example, if $k=2$ and $|L_1|=|L_2|=1$ then in the worst case every parent will ask their children to each generate two layers and the value partition will not remove any values. Each leaf will generate two values, their parents will then have a new layer of size $2^2=4$, their parent will have a new layer of size $(2^2)^2=8$, etc. Thus the root will have to perform a $2$-selection on $2^m$ values which will be quite costly. In an application like calculating the isotopologues of a compound, this version can be quite beneficial. For example, to generate a significant amount of the isotopologues of the titin protein may require $k$ to be hundreds of millions. Titin is made of only carbon, hydrogen, nitrogen, oxygen, and sulfur so it will only have five leaves and a tree height of three. The super-exponential growth of the layers for a tree with height three is now preferential because it will still not create so many more than $k$ values but it will do so in many fewer layers with only value partitions and not the more costly linear selections. We call this the ``wobbly'' Cartesian product tree. \section{Results} All experiments were run on a workstation equipped with 256GB of RAM and two AMD Epyc 7351 processors running Ubuntu 18.04.4 LTS. \begin{table} \begin{tabular}{r|ll} k & Cartesian product tree & FastSoftTree \\ \hline \\ $2^{2}$ & $1.404\times 10^{-03}$ & $3.146\times 10^{-03}$ \\ $2^{3}$ & $1.504\times 10^{-03}$ & $2.855\times 10^{-03}$ \\ $2^{4}$ & $1.521\times 10^{-03}$ & $3.163\times 10^{-03}$ \\ $2^{5}$ & $1.592\times 10^{-03}$ & $2.618\times 10^{-03}$ \\ $2^{6}$ & $1.689\times 10^{-03}$ & $4.172\times 10^{-03}$ \\ $2^{7}$ & $1.718\times 10^{-03}$ & $4.830\times 10^{-03}$ \\ $2^{8}$ & $1.881\times 10^{-03}$ & $8.864\times 10^{-03}$ \\ $2^{9}$ & $2.080\times 10^{-03}$ & $0.01143$ \\ $2^{10}$ & $1.745\times 10^{-03}$ & $0.01792$ \\ $2^{11}$ & $2.217\times 10^{-03}$ & $0.02362$ \\ $2^{12}$ & $3.123\times 10^{-03}$ & $0.04459$ \\ $2^{13}$ & $3.318\times 10^{-03}$ & $0.07026$ \\ $2^{14}$ & $5.099\times 10^{-03}$ & $0.111$ \\ $2^{15}$ & $6.240\times 10^{-03}$ & $0.2296$ \\ $2^{16}$ & $8.724\times 10^{-03}$ & $0.4952$ \\ $2^{17}$ & $0.01266$ & $0.9609$ \\ $2^{18}$ & $0.01663$ & $1.610$ \\ $2^{19}$ & $0.02684$ & $12.77$ \\ $2^{20}$ & $0.0405$ & $25.53$ \\ \end{tabular} \caption{{\bf Runtimes for Cartesian product tree vs FastSoftTree with $n=32$, $m=256$ and $\alpha=1.1$.} The runtime is averaged over 20 iterations. For small problems the soft heap based tree is competitive with the Cartesian product tree; however, for large enough $k$ the cache performance of the LOH significantly outperforms the soft heap resulting in a $630.4\times$ speedup for $k=2^{20}$.} \label{table:standard-vs-fst} \end{table} In a Cartesian product tree, replacing the pairwise X+Y selection steps from Kaplan \emph{et al.}'s soft heap-based algorithm with Serang's optimal LOH-based method provides the same $o(n\cdot m + k\cdot m)$ theoretical performance for the Cartesian product tree, but is practically much faster (Table~\ref{table:standard-vs-fst}. This is particularly true when $k\cdot m^{\log2(\alpha^2)} \gg n\cdot m$, where popping values dominates the cost of loading the data. When $k \geq 2^{10}$, $k\cdot m^{0.2750} < n\cdot m$ which is reflected in our results where for $k=2^{20}$ we get a $630.4\times$ speedup, significantly larger than for $k = 2^{10}$ which only has a $10.27\times$ speedup. \begin{table} \begin{tabular}{r|ll} k & Standard version & Wobbly version \\ \hline $2^{2}$ & $1.544\times 10^{-04}$ & $1.777\times 10^{-04}$ \\ $2^{3}$ & $1.754\times 10^{-04}$ & $1.468\times 10^{-04}$ \\ $2^{4}$ & $2.086\times 10^{-04}$ & $1.846\times 10^{-04}$ \\ $2^{5}$ & $2.386\times 10^{-04}$ & $2.046\times 10^{-04}$ \\ $2^{6}$ & $2.080\times 10^{-04}$ & $1.935\times 10^{-04}$ \\ $2^{7}$ & $3.060\times 10^{-04}$ & $2.672\times 10^{-04}$ \\ $2^{8}$ & $3.481\times 10^{-04}$ & $3.225\times 10^{-04}$ \\ $2^{9}$ & $4.289\times 10^{-04}$ & $2.978\times 10^{-04}$ \\ $2^{10}$ & $6.119\times 10^{-04}$ & $4.087\times 10^{-04}$ \\ $2^{11}$ & $7.976\times 10^{-04}$ & $4.585\times 10^{-04}$ \\ $2^{12}$ & $1.000\times 10^{-03}$ & $7.263\times 10^{-04}$ \\ $2^{13}$ & $1.711\times 10^{-03}$ & $1.189\times 10^{-03}$ \\ $2^{14}$ & $2.344\times 10^{-03}$ & $1.465\times 10^{-03}$ \\ $2^{16}$ & $7.531\times 10^{-03}$ & $4.890\times 10^{-03}$ \\ $2^{15}$ & $3.919\times 10^{-03}$ & $2.578\times 10^{-03}$ \\ $2^{17}$ & $0.0113 $ & $9.090\times 10^{-03}$ \\ $2^{18}$ & $0.01741$ & $0.01583$ \\ $2^{19}$ & $0.02777$ & $0.02511$ \\ $2^{20}$ & $0.04904$ & $0.04228$ \\ $2^{21}$ & $0.08572$ & $0.07773$ \\ $2^{22}$ & $0.1623$ & $0.1424$ \\ $2^{23}$ & $0.3274$ & $0.234$ \\ $2^{24}$ & $0.636$ & $0.4838$ \\ $2^{25}$ & $1.210$ & $1.029$ \\ $2^{26}$ & $2.306$ & $1.588$ \\ $2^{27}$ & $4.993$ & $3.487$ \\ $2^{28}$ & $9.995$ & $8.441$ \\ $2^{29}$ & $19.7$ & $14.31$ \\ $2^{30}$ & $43.45$ & $24.33$ \\ \end{tabular} \caption{{\bf Runtimes for standard Cartesian product tree vs wobbly Cartesian product tree with $n=256$, $m=5$ and $\alpha=1.1$.} The runtime averaged over 20 iterations for the two methods. With $m=5$ the tree only has three layers and so the super-exponential growth of the layers as they go from the leaves to the roots does not become intractable. As $k$ becomes extremely large the ability of the wobbly tree to generate huge layers at the root without performing any selections significantly reduces the runtime resulting in a $1.786 \times$ speedup.} \label{table:standard-vs-wobbly} \end{table} As we see in Table~\ref{table:standard-vs-wobbly}, for small $m$ the Cartesian product tree can gain significant increases in performance when there are no linear selections performed in the tree and the layers are allowed to grow super-exponentially. As $k$ grows, the speedup of the wobbly version continues to grow, resulting in a $1.786 \times$ speedup for $k=2^{30}$. When $m\gg 5$ the growth of the layers near the root start to significantly hurt the performance. For example, if $n=32, m=256$ and $k=256$ the wobbly version takes $0.5805$ seconds and produces 149,272 values at the root compared to the non-wobbly version which takes $1.8810\times 10^{-03}$ seconds and produces just 272 values at the root. \section{Discussion} Replacing pairwise selection which uses a soft heap with Serang's optimal method provides a significant increase in performance. Since both methods LOHify the input arrays (using the same LOHify method) the most significant increases are seen when $k\cdot m^{\log2(\alpha^2)} \gg n\cdot m$. For small $m$, the performance can boosted using the wobbly version; however for large $m$ the super-exponentially sized layers can quickly begin to dampen performance. It may be possible to limit the layer sizes in the wobbly version by performing selections only at certain layers of the tree: either by performing the selection on every $i^{th}$ layer or only on the top several layers. Any method reminiscent of the Kaplan \emph{et al.} proposal scheme, which uses a scheme whereby each value retrieved from the soft heap inserts a constant number, $c\geq 1$, of new values into the soft heap, requires implicit construction of a LOH. Optimal, online computation of values requires retrieving the top $k_1$ values and then top $k_2$ remaining values and so on. The number of corrupt values is bounded by $\epsilon\cdot I$, where $I$ insertions have been performed to date; therefore, there are at most $\epsilon\cdot c\cdot k_1$ corrupt values. The top $k_1$ values can be retrieved by popping no more than $k_1+\epsilon\cdot c\cdot k_1$ values from the soft heap and then performing $k_1$-selection (via median-of-medians) on the resulting popped values. The $\epsilon \cdot k_1$ corrupt values are reinserted into the soft heap, bringing the total insertions to $k_1\cdot\epsilon\cdot(1 + c)$. To retrieve the top $k_2$ remaining values, $k_2+\epsilon\cdot k_1\cdot\epsilon\cdot(1 + c)\in \Omega(k_2+k_1)$ values need to be popped. These top $k_2$ values can be retrieved in optimal $O(k_2)$ time if $k_2 \in \Theta(k_1)$. Likewise, $k_3\in \Theta(k_1+k_2)$, and so on. Thus, the sequence of $k$ values must grow exponentially. Rebuilding the soft heap (rather than reinserting the corrupted values into the soft heap) instead does not alleviate this need for exponential growth in $k_1, k_2, \ldots$ required to achieve optimal $O(k_1 + k_2 + \cdots)$ total runtime. When rebuilding, each next $k_j$ must be comparable to the size of the entire soft heap (so that the cost of rebuilding can be amortized out by the optimal $\Theta(k_j)$ steps used to retrieve the next $k_j$ values). Because $c\geq 1$, the size of the soft heap is always $\geq k_1+k_2+\cdots+k_{j-1}$ for the selections already performed, and thus the rebuilding cost is $k_1+k_2+\cdots+k_{j-1}$, which must be $\in\Theta(k_j)$. This likewise requires exponential growth in the $k_j$. This can be seen as the layer ordering property, which guarantees that a proposal scheme such as that in Kaplan \emph{et al.} does not penetrate to great depth in the combinatorial heap, which could lead to exponential complexity when $c>1$. In this manner, the $k_1, k_2,\ldots$ values can be seen to form layers of heap, which would not require retrieving further layers before the current extreme layer has been exhausted. This method has already proved to be beneficial in generating the top $k$ isotopologues of chemical compounds, but it is not limited to this use-case. It is applicable to fast algorithms for inference on random variables $Y=X_1+X_2+\cdots+X_m$ in the context of graphical Bayesian models. It may not generate a value at every index in a max-convolution, but it may generate enough values fast enough to give a significant result.
{'timestamp': '2020-08-18T02:21:13', 'yymm': '2008', 'arxiv_id': '2008.07023', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07023'}
arxiv
\section{Introduction} \vspace{-4pt} Human 2D pose estimation targets at localizing anatomical keypoints of individuals from images. Accurate pose estimation plays an essential role in understanding human behaviors. This paper focuses on pose estimation for single person, which can be a cornerstone for downstream tasks including action recognition \cite{rodriguez2008action,ryoo2009spatio,schuldt2004recognizing}, gaming \cite{ke2010real}, multi-person pose estimation \cite{cao2017realtime}, and video tracking \cite{raaj2019efficient,xiu2018pose}, etc. \begin{table*}[h] \centering \caption{Comparison of AutoPose against other NAS works. AutoPose is the first NAS framework that integrally searches for cell, scale, aggregation (``Agg.'') and branches. We also compares the size of search space (``SS''), optimization method, and search time (GPU days).} \vspace{0.5em}. {\small \begin{tabular}{l|ccccccccc} \toprule Model & SS & Optimization & Cell & Scale & Agg. & Branch & Dataset & Task & Days \\ \midrule NASNet \cite{zoph2018learning} & $10^{16}$ & RL & \checkmark & & & & CIFAR-10& Cls & 2000 \\ DARTS \cite{liu2018darts} & $10^{28}$ & GRAD & \checkmark & & & & CIFAR-10 & Cls & 4 \\ DPC \cite{chen2018searching} & $10^{11}$ & RS & & & \checkmark & & Cityscapes & Seg & 2600 \\ Auto-DeepLab \cite{liu2019auto} & $10^{19}$ & GRAD & \checkmark & \checkmark & & & Cityscapes & Seg & 3 \\ \hline Ours & $10^{61}$ & GRAD+RL & \checkmark & \checkmark & \checkmark & \checkmark & MSCOCO & Pose & 2.5 \\ \bottomrule \end{tabular} }\label{table:comparison} \end{table*} Recently, great endeavors have been made to exploit convolutional neural networks (CNN) to improve pose estimation. Especially, multi-scale branches and context aggregation modules are increasingly leveraged to capture multi-grained features. For example, Newell \etal proposes the stacked Hourglass network \cite{newell2016stacked}, which repeatedly downsamples and restores resolutions through the network. Cascaded pyramid network \cite{chen2018cascaded} constructs a multi-scale network, keeping multi-scale information through the network and aggregating them at the end. HRNet \cite{sun2019deep} achieves state-of-the-art performance by constructing a multi-branch network, where high-resolution representations are maintained through the whole pipeline, in addition to multi-scale aggregation at each stage. While multi-scale features, as well as high resolution, are shown to be vital for accurate pose estimation, how to advance the design of pose estimation networks further is not immediately clear, since the arising complex branches and connectivity patterns can cost heavy human efforts to explore thoroughly. Designing modern CNN architectures manually can result in tedious trail-and-errors. To this end, the neural architecture search (NAS) has recently drawn a booming interest. Aiming to discover an optimal network architecture from data, NAS has been successfully applied primarily on image classification \cite{dong2019searching,liu2018darts,negrinho2017deeparchitect,pham2018efficient,real2019regularized,xie2018snas,zoph2016neural}, and lately also on object detection \cite{chen2019detnas,ghiasi2019fpn}, semantic segmentation \cite{liu2019auto,nekrasov2019fast,chen2019fasterseg}, person re-identification \cite{quan2019auto}, speech recognition \cite{ding2020autospeech}, super-resolution \cite{song2020efficient}, medical image analysis \cite{zhu2019v}, and even generative models \cite{gong2019autogan,fu2020autogan} or Bayesian deep networks \cite{ardywibowo2020nads}. These works surge heavy interests in designing sophisticated architectures automatically, reducing human efforts as well as revealing/verifying design insights. Despite the promise of NAS, there remains to be a major gap between its current capability, and the real sophistication needed by advanced computer vision applications. For example, for the sake of simplicity, most NAS methods usually define their search spaces in a way that can only cover chain-like single backbones (with skip connections), which will exclude the discovery of multiple (and inter-connected) backbones that have proven effectiveness \cite{chen2018cascaded,sun2019deep}. Recently, Auto-DeepLab \cite{liu2019auto} proposes a two-level hierarchy search space for semantic segmentation, which is able to search for the network scales at different stages. However, considering only connections within a single cell, Auto-DeepLab cannot derive an architecture that contains connections over multiple sub-paths over different scales at the same time. NAS-FPN \cite{ghiasi2019fpn} designs cross-scale connections only for the feature fusion head, while the backbone is not optimized. This paper proposes AutoPose, a novel NAS framework that automatically designs architectures towards accurate 2D human pose estimation. The core of AutoPose is a hierarchical multi-scale \textbf{search space}, consisting of a novel network-level search space in addition to the cell-level search space. Our search space can simultaneously maintain multiple parallel branches of diverse scales in an end-to-end fashion throughout the network, which leads to much flexible and finer-grained exploration. To effectively fuse features from branches, AutoPose further searches for novel aggregation cells, which support dense and sophisticated cross-scale aggregations, instead of naively summing up all features \cite{sun2019deep}. As a result, the AutoPose search space is unusually gigantic ($10^{61}$ candidates) with multi-level selections (from cell to network), making either gradient method or reinforcement learning alone \textit{not directly applicable}. For example, traditional gradient-based search is unable to select more than one branches simultaneously \cite{liu2019auto}. On the other hand, reinforcement learning would be too time-consuming for such a huge space. Motivated by that, we present a novel bi-level \textbf{optimization algorithm} combining the two, for different aspects of search space. Gradient-based method is leveraged to search for the micro cell architectures (cell-level). An RNN controller trained via reinforcement learning then guides the dynamic searching over multiple scales and network depth (network level), which boosts the flexibility in discovering networks of capacity variations We summarize our contributions as follows: \vspace{-2pt} \begin{itemize} \item \textbf{High-resolution Multi-branch Search Space.} We show that: i) the searchable parallel branches of multiple scales; and ii) the cross-scale context aggregations, are two key components towards searching for accurate human pose estimation. \vspace{-1pt} Extensive ablation studies support our design philosophy. \item \textbf{Bi-level Optimization.} To fulfill the effective discovery over the gigantic fined-grained search space, we integrate the reinforcement learning and the gradient-based search method for the first time, to jointly optimize the network-level and the cell-level architectures.\vspace{-1pt} \item Experiments demonstrate that AutoPose for the first time automatically designs architectures of sophisticated connections, achieving competitive performance as hand-crafted networks for human pose estimation.\vspace{-2pt} \end{itemize} We noticed another recently proposed NAS framework of pose estimation called PoseNFS \cite{yang2019pose}. Unlike \cite{liu2019auto}, PoseNFS follows a one-together search strategy directly over macro and micro levels. To simplify their search, the authors referred to the body structure prior knowledge to decompose the whole search space into multiple part-specific ones, with global pose constraint relationship enforced. However, its performance falls behind current state-of-the-art hand-crafted pose estimation models with a notable margin. In comparison, we decouple our search at two different granularity levels in one unified space, and show the feasibility and effectiveness of purely end-to-end data-driven search without drawing any explicit body part knowledge. We compare our results with PoseNFS in Section 4. \vspace{-3pt} \section{Related Work} \vspace{-2pt} \subsection{Human Pose Estimation} \vspace{-2pt} Existing pose estimation work can be categorized to either bottom-up or top-down. Bottom-up methods \cite{cao2017realtime,insafutdinov2016deepercut} first detect all parts in the image (i.e. parts of every person), then associate or group parts belonging to each individual. Bottom-up methods are more suitable for efficient pose estimation. Top-down methods~\cite{chen2018cascaded,fang2017rmpe,he2017mask,huang2017coarse,papandreou2017towards,sun2019deep} first generate human proposals in the form of bounding boxes and then exploit non-maximum suppression (NMS) to remove the redundant proposals, after which a single-person pose estimation is conducted for every proposal The recent trend in pose estimation leverages high-resolution features and aggregating contexts from multiple scales. Chen \etal~\cite{chen2018cascaded} proposes the Cascaded Pyramid Network which consists of a GlobalNet based on feature pyramid and a cascaded multi-scale RefineNet to focus more on fine-granularity hard keypoints. HRNet \cite{sun2019deep} achieves state-of-the-art performance by utilizing a network of multiple branches across multiple scales, where information is aggregated at each stage of the network. In AutoPose, we follow this line of leveraging high-resolution features across multi-scale branches from end to end. \begin{figure*}[ht!] \begin{center} \vspace{-4pt} \includegraphics[width=0.8\linewidth]{imgs/macro.pdf} \end{center} \vspace{-1em} \caption{Our AutoPose framework. We support the multi-scale parallel branches and context aggregation via our stacked multi-scale modules. The activation of each scale ($\{4\times, 8\times, 16\times, 32\times\}$ when $B=4$ shown here) in each stage is controlled by an RNN controller. } \vspace{-4pt} \label{fig:macro} \end{figure*} \vspace{-2pt} \subsection{Neural Architecture Search Spaces} \vspace{-2pt} Most existing works in neural architecture search (NAS) focus on searching either stacked operators \cite{pham2018efficient,zoph2016neural} or repeated cell-structured directed acyclic graph \cite{liu2018darts} for the classification task. Search spaces in these works are mainly designed for chain-like single-path networks with fixed scale patterns. Recent NAS works explore more challenging high-level vision tasks like object detection \cite{chen2019detnas,ghiasi2019fpn} and semantic segmentation \cite{liu2019auto,nekrasov2019fast}. Although these dense prediction tasks are more sensitive to resolutions and require aggregation of multi-scale context for improving performance, these early NAS works for dense prediction tasks are still limited in their searchable scale-level connections. In contrast, our search space supports more complex cross-scale connections throughout the network. Different from the network-level search in Auto-Deeplab \cite{liu2019auto} which still only explore and derive only one branch, our AutoPose supports maintaining multiple parallel branches across scales. Our search space naturally provides the architecture exploration with more flexibility yet it is more challenging. \vspace{-2pt} \subsection{Neural Architecture Search Methods} \vspace{-2pt} Neural architecture optimization is first proposed with the reinforcement learning method \cite{pham2018efficient,zoph2016neural}, which leverages a learned policy to control the selection of operators along with the network. Reinforcement learning is a popular methods for NAS works which involve non-differentiable optimization target \cite{gong2019autogan,tan2019mnasnet}, as the policy-gradient method \cite{williams1992simple} can leverage discrete extrinsic rewards. The gradient-based method is proposed in \cite{liu2018darts} which provides an efficient way of searching the architecture using gradient descent \cite{liu2019auto}. Real \etal \cite{real2019regularized} successfully introduce an evolution algorithm into NAS, achieving competitive performance, also followed by many \cite{yang2020cars}. Egrinho \etal \cite{negrinho2017deeparchitect} takes the first step to incorporate the Monte Carlo tree search (MCTS) into NAS. \cite{wang2020dc} also adopted the search space divide-and-conquer strategy. NAO \cite{luo2018neural} embeds the complex network structures into a latent space to simplify the searching. All existing NAS works focus on using one search method coupled with their search spaces. However, a single search method may lack the capability of supporting complex search spaces. In our AutoPose, we for the first time integrate different methods for different parts of our search space. \vspace{-4pt} \begin{figure}[t] \begin{center} \includegraphics[width=0.85\linewidth]{imgs/module.pdf} \end{center} \vspace{-1em} \caption{Our multi-scale module takes inputs of different scales. The inputs will first go through two individual cells and then will be aggregated together by the aggregation cells.} \label{fig:module} \vspace{-8pt} \end{figure} \section{Method} \vspace{-4pt} We illustrate the overview of our AutoPose framework in Fig. \ref{fig:macro}. The input image is first passed through a pre-defined stem module (Sec. \ref{sec:stem_head}) to output feature maps of different scales\footnote{A feature map of scale $s$ is of $\frac{1}{s^2}$ size of the input image by scaling both the height and width to $\frac{1}{s}$.}, which are served as inputs into our multi-branch search space. We split our search space into three stages, where the activated parallel branches (of different scales) in each stage are individually controlled by our RNN controller. The purpose of these separate stages is to support the different needs of scales from early to late stage along with the network. At the end, the outputs of different branches are upsampled via nearest-neighbor interpolation to the highest resolution, and are aggregated by summation. \begin{figure}[h] \begin{center} \includegraphics[width=1.0\linewidth]{imgs/eg1.pdf} \end{center} \vspace{-1em} \caption{An example of a multi-scale module with a scale vector $[1, 0, 1, 0]$. Only the branches of scales $4 \times$ and $16 \times$ are activated.} \label{fig:example} \vspace{-10pt} \end{figure} \vspace{-2pt} \subsection{High-resolution Multi-branch Search Space} \vspace{-2pt} Parallel branches of diverse scales and context aggregation modules are two key points for sufficiently capturing feature maps under different receptive fields, which motivates the design of our core functional unit ``Multi-scale Module'' (Fig. \ref{fig:module}). In the following sections, we describe our network-level search space for maintaining multiple parallel branches throughout the network and cell-level structures for merging multi-scale features. We by default stack two identical multi-scale modules in each stage. \vspace{-8pt} \subsubsection{Network-level Search Space} \vspace{-4pt} Our core component ``Multi-scale Module'' (Fig. \ref{fig:module}) is composted of $B$ branches of different scales, where each branch includes two individual cells ($\mathcal{C}_{I1}, \mathcal{C}_{I2}$) and one aggregation cell ($\mathcal{C}_M$) (see Sec. \ref{sec:cell}). The activation status of each scale in each stage is individually controlled by our RNN controller. Specifically, each stage may activate one or more different scales. If a scale is activated, the input tensor of that scale will be processed by the two individual cells on that branch. Otherwise, the input tensor will go through a skip connection, which means the two individual cells and the aggregation cell on this deactivated branch will not participate in the network forward and backward process, and correspondingly the cell weights and architecture will not be updated by the gradient descent. The feature maps remain the same scale within each branch. More formally, for the $m$-th multi-scale module, the RNN controller outputs a binary scale vector $[\beta^m_{2^2}, \beta^m_{2^3}.., \beta^m_{2^{B+1}}]$. For the $b$-th branch (top to bottom in Fig. \ref{fig:macro}, $b \in N^+, 1 \leq b \leq B$) whose scale $s_b = 2^{b+1}$, its output, denoted as $H^m_{s_b}$, can be formulated as: \vspace{-6pt} \begin{equation} H^m_{s_b} = \begin{cases} \mathcal{C}^m_{M,s_b} \circ \mathcal{C}^m_{I2,s_b} \circ \mathcal{C}^m_{I1,s_b} (H^{m-1}_{s_b}) & \text{if $\beta^m_{s_b} = 1$,} \\ H^{m-1}_{s_b} & \text{if $\beta^m_{s_b} = 0$.} \end{cases} \end{equation} Note that we allow the situation that all branches in a stage are deactivated, which means that our framework is able to search for the \textbf{network depth}. Fig. \ref{fig:example} shows an example when $B = 4$ and the controller generates a scale vector $[1, 0, 1, 0]$. In this scenario, only the branches of $4\times$ and $16\times$ scales are activated and will process their input tensors, while the branches of $8\times$ and $32\times$ scales become skip connections. Note that the aggregation cells of $4\times$ and $16\times$ scales will take $\mathcal{C}^m_{I2,s_b} \circ \mathcal{C}^m_{I1,s_b} (H^{m-1}_{s_b})$ as inputs for $s_b = 4, 16$, and will take $H^{m-1}_s$ as inputs for $s_b = 8, 32$. \vspace{-8pt} \subsubsection{Cell-level Search Space} \label{sec:cell} \vspace{-4pt} We include two types of cells ((network basic units): the individual cell and the aggregation cell. As in Fig. \ref{fig:module}, on each branch in the multi-scale module, two individual cells ($\mathcal{C}_{I1}, \mathcal{C}_{I2}$) are sequentially stacked, followed by a aggregation cell ($\mathcal{C}_M$). Both the individual cell $\mathcal{C}_I$ and the aggregation cell $\mathcal{C}_M$ are directed acyclic graphs (DAG), consisting of an ordered sequence of $K_I, K_M$ nodes, respectively. Each node $x^{(i)}$ is a feature map and each directed edge $(i, j)$ is associated with a specific operation $O^{(i,j)}$ that transforms node. The output of a cell, denoted as $H$, is the concatenation of all nodes, followed by a $1 \times 1$ convolution, aiming at compressing the channel dimension. \vspace{-8pt} \paragraph{Individual Cell} An individual cell $\mathcal{C}_I$ takes its predecessor (the previous cell's output) as its single input, and outputs one tensor. The $i$-th node $x^{(i)}_I$ is calculated as the sum of the transformed (processed by an operation) $i$ previous nodes and the input of the cell. The computation of $i$-th intermediate node in the individual cell is formulated as: \begin{equation} x^{(i)}_I = \sum_{j<i}O^{(i,j)}(x^{(j)}_I) \label{eq:node} \end{equation} $O^{(i,j)}$ denotes the operation of $i$-th node, which takes the $j$-th node $x^{(j)}_I$ as input. \vspace{-8pt} \paragraph{Aggregation Cell} A aggregation cell $\mathcal{C}_M$ takes $B$ outputs of different scales from $B$ individual cells as its inputs. In particular, the $B$ inputs from the individual cells will be first downsampled or upsampled accordingly to match the current aggregation cell's scale. The computation at $i$-th intermediate node in the aggregation cell is formulated as: \begin{equation} x^{(i)}_M = \sum_{j<i}O^{(i,j)}(x^{(j)}_M) + \sum_{b=1}^B O^i_b(H_{I2, s_b}), \label{eq:node} \end{equation} where $H_{I2, s_b}$ denotes the output of the second individual cell of scale $s_b = 2^{b+1}$ ($b \in N^+, 1 \leq b \leq B$), with associated operation $O^i_b$ for the $i$-th node. \vspace{-8pt} \paragraph{Continuous Relaxation of Cell-level Search Space} We adopts the continuous relaxation \cite{dong2019searching,liu2019auto,liu2018darts} to represent the cell-level architecture. Specifically, the categorical choice of a particular operation $O^{(i,j)}$ is relaxed to be continuous: \begin{equation} \overline{O}^{(i,j)}(x^{(j)}) = \sum_{k=1}^{|\mathcal{O}|} \alpha_k^{(i, j)} O_k^{(i,j)}(x^{(j)}) \end{equation} where $\alpha^{(i, j)}$ is a differntiable $|\mathcal{O}|$-dim vector with its $k$-th elements associated with operation $O^k \in \mathcal{O}$ for the edge from $j$-th node to $i$-th node. $\alpha_k^{(i, j)}$ is normalized by the ``Gumbel-Softmax'' with reparameterization trick, for the purpose of efficient search process (see supplementary materials). $\mathcal{O}$ is the set of candidate operations, which contains six prevalent operations as below: \vspace{-8pt} \begin{multicols}{2} \begin{itemize} \item $1 \times 1$ convolution \item $3 \times 3$ convolution \item $5 \times 5$ convolution \item $3 \times 3$ average pooling \item $3 \times 3$ max pooling \item skip connection \end{itemize} \vspace{-8pt} \end{multicols} \vspace{-8pt} \subsection{Bi-level Optimization} \vspace{-2pt} To enable the optimization over network-level search space, one ad-hoc idea may be also adopting a continuously relaxed network-level search space and applying gradient-based updates, similar to the approach proposed by Liu \etal \cite{liu2019auto}. However, this continuous relaxation cannot support the need for multiple scales. As demonstrated by the single-branch network in Auto-Deeplab, the gradient-based search method can only pick the top1 single branch, which is not naturally applicable to discovering parallel branches. We instead unify the optimization of the network-level and cell-level architectures, and train a policy to control the selection of cross-scale connections. Specifically, we update the cell-level micro architecture via gradient descent, and our policy controller will sample the macro architecture of scales, where the network will activate the corresponding branches. The network-level macro search and cell-level micro search are integrated and alternatively proceed (see Sec. \ref{sec:search_detail} for searching details). The search procedure is shown in the $search$ function in Algorithm \ref{algo:darts}. \vspace{-4pt} \begin{algorithm}[tbh] {\small \SetAlgoLined \DontPrintSemicolon \SetKwFunction{CU}{cell\_update} \SetKwFunction{CTRLU}{controller\_update} \SetKwFunction{S}{search} \SetKwProg{Fn}{Function}{:}{} \Fn{\S{$N_{epoch}$,$N_{iter}$,$N_{ctr}$}}{ initialize network weights $\omega$, cell architecture $\alpha$, branch architecture $\beta$, policy controller $\pi (\theta)$\; $epoch = 0$ \; \While{$epoch < N_{epoch}$}{ $iter = 0$ \; \While{$iter < N_{iter}$}{ $\beta\gets\pi(\theta)$\; \CU{$\beta$}\; $iter = iter + 1$ } \CTRLU{$N_{ctr}$}\; $epoch = epoch + 1$ } }\; \Fn{\CU{$\beta$}}{ Continuously relax operation $\Bar{o}^{(i,j)}$ weighted by the architecture parameter $\alpha^{(i,j)}$\\ 1. Update weights $\omega$ by descending $\nabla_{\omega}\mathcal{L}_{train}(\omega, \alpha, \beta)$\; 2. Update cell architecture $\alpha$ by descending $\nabla_{\alpha}\mathcal{L}_{val}(\omega, \alpha, \beta)$\; 3. Replace $\Bar{o}^{(i,j)}$ with $o_{k^*}^{(i,j)}, k^* = \mathrm{argmax}_{1\leq k \leq |\mathcal{O}|} \alpha_k^{(i,j)}$ \; }\; \Fn{\CTRLU{$N_{ctr}$}}{ Fix network weights $\omega$ and cell architecture $\alpha$\; $step = 0$ \; \While{$step < N_{ctr}$}{ Update controller by maximize the expected reward $\mathbb{E}_{\beta \sim \pi(\theta)}[\mathcal{R}(\omega, \alpha, \beta)]$\; $step = step + 1$ } } } \caption{Bi-level Optimization}\label{algo:darts} \end{algorithm} \vspace{-4pt} \subsubsection{Network-level Macro Search} \vspace{-4pt} For the network-level macro search, we construct an RNN controller optimized via the REINFORCE gradient \cite{williams1992simple}, to decide which branches should be activated. The optimization of controller is illustrated in $controller\_update$ function in Algo. \ref{algo:darts}. At each time step, the controller will sample a $B$-dimension vector from the policy $\pi(\theta)$, where the $b$-th element indicates the activation status of the branch of scale $2^{b+1}$. We use average precision (AP) score on validation dataset as the reward $\mathcal{R}$. \vspace{-4pt} \subsubsection{Cell-level Micro Search} \vspace{-4pt} With continuous relaxation mentioned in Sec. \ref{sec:cell}, we are able to optimize the discrete architecture with gradient descent. We adopt the first-order approximation in \cite{liu2018darts}. The loss function $\mathcal{L}$ is the mean squared error calculated between the regressed heatmap and the ground truth. The search algorithm proceeds the update of supernet weights $\omega$ and the cell-level architecture $\alpha$ in an alternative way, shown in function $cell\_update$ in Algo. \ref{algo:darts}. \vspace{-2pt} \subsection{Architecture Derivation} \vspace{-2pt} \paragraph{Network-level Architecture} We adopt the optimized policy controller to sample the scale vector of each stage for $N$ times, then evaluate each status of parallel branches on the validation set by using the same shared weights in supernet. The one with the best performance will be selected as the discovered network-level architecture. We choose $N = 10$ by default, and a larger $N$ can be adopted to sample more status of parallel branches. \vspace{-4pt} \paragraph{Cell-level Architecture} The optimal operators in cell-level architecture are derived by taking the $\mathrm{argmax}$ over $\alpha^{(i, j)}$. Different from previous works \cite{liu2019auto,liu2018darts}, we preserve the connection from all predecessors for every node. \vspace{-4pt} \section{Experiments} \vspace{-4pt} In all experiments, we use Nvidia Titan RTX for benchmarking the computing power. All experiments are performed under CUDA 9.0 and CUDNN V7, using Pytorch.\vspace{-4pt} \subsection{Datasets} \vspace{-2pt} \paragraph{COCO Dataset} We adopt the COCO dataset \cite{lin2014microsoft} as our main testbed, which contains more than 200k images and 250k person instances with 17 keypoints per instance. Our models are trained on the training dataset only, including 56k images and 150k person instances. During training, each image is resized to $256 \times 192$. We apply random flipping and rotation ([$-45 ^{\circ}$, $45 ^{\circ}$]) as data augmentation. The validation set contains about 5k images. Results are reported using the official evaluation metric of the COCO Keypoint Challenge: average precision (AP) and average recall (AR), based on object keypoints similarity (OKS):\vspace{-4pt} \begin{equation} \begin{aligned} \text{OKS} = \frac{\sum_i[\exp(-d_i^2/2s^2k_i^2)\delta(v_i>0)]}{\sum_i[\delta(v_i>0)]} \end{aligned} \end{equation} Here, $d_i$ is the Euclidean distance between ground-truth and detected keypoint, $v_i$ is the visibility flag of the ground-truth keypoint. Each kind of keypoint also has a scale $s$ which is defined as the square root of the object segment area. $k_i$ is a predefined constant provided by the COCO Keypoint Challenge 2017 which is used to control falloff. \vspace{-8pt} \paragraph{MPII Dataset} The MPII dataset \cite{andriluka14cvpr} contains around 25k images with over 40k people with annotated body joints. Note that we use MPII to study the transferability of COCO-search architectures in this paper, rather than conducting any search on MPII directly. We trained our discovered model on training split only, and evaluate the single person pose estimation result on the validation dataset. We adopt the same data augmentation as on the COCO dataset. The input image size is set to $256 \times 256$. The evaluation metric is the Percentage of Correct Keypoints (PCK) \cite{yang2012articulated}. \subsection{Architecture Search and Implementations} \paragraph{Stem and Head Structure}\label{sec:stem_head} In both our supernet and derived architecture, from the input image we leverage a pre-defined stem module to extract feature maps of different scales serving as inputs into the multi-scale modules. We design the ``stem'' structure with two $3\times 3$ convolutions (with stride 2) followed by a residual bottleneck \cite{he2016deep}, which produces a feature map of $4\times$ scale. We sequentially stack more $3\times 3$ convolutions with stride 2 to provide feature maps of higher scales. At the end of the network, the outputs of different branches are upsampled via nearest-neighbor interpolation to the highest resolution (``$4\times$'' branch in our case), and are aggregated with a concatenation. The concatenated feature map is then processed by a $3\times 3$ convolution of stride 1 towards the final output. \vspace{-8pt} \paragraph{Searching Details}\label{sec:search_detail} The number of branches $B$ is set to 4, where the scales of branches are $\{4 \times, 8\times, 16\times, 32 \times\}$ and the number of channels are 16, 32, 64, 128, respectively. The number of nodes in each individual cell is set as $K_I = 4$, while for the aggregation cell $K_M = 2$. Each stage has 2 multi-scale modules, where all stages will share the same cell-level architecture parameters $\alpha^{(i,j)}$, following previous works \cite{liu2019auto,liu2018darts,zoph2018learning}. We adopt Adam optimizer to train the cell-level architecture parameters $\alpha^{(i,j)}$ with a learning rate of $3\mathrm{e}{-3}$. During our search we set the total number of epochs $N_{epoch} = 50$, and $N_{iter} = 1100$ iterations per epoch. At the end of each epoch for the cell-level search, the scale controller will be updated for $N_{ctr} = 10$ times, with a batch size of 2. The controller is also optimized by an Adam optimizer, with a learning rate of $3.5\mathrm{e}{-3}$. For the reward to our controller, we use the OKS-based AP score on the validation dataset. Note that we start training the controller at the 5-th epochs, to avoid the bias caused by the under-trained supernet. \vspace{-8pt} \paragraph{Training Details} The number of channels in the derived architecture is doubled from the supernet used in the search. The network is trained for 210 epochs. The initial learning rate is set to 0.001, which will be multiplied by a decay factor of 0.1 at epoch 170 and epoch 200. Adam optimizer is adopted for the network, with $\beta_1 = 0.9$, $\beta_2 = 0.99$. The batch size is set to 128. \vspace{-8pt} \paragraph{Testing Details} We borrow the person detector from HTC \cite{chen2019hybrid} to get the person bounding box for COCO dataset testing. We follow the test procedure in \cite{newell2016stacked}, where the output heatmap is computed by averaging the output heatmap of the original and its flipped one. \vspace{-2pt} \subsection{Results} \begin{figure*}[h] \begin{center} \includegraphics[width=0.85\linewidth]{imgs/derived_arch.pdf} \end{center} \vspace{-4pt} \caption The discovered network-level macro architecture of our proposed AutoPose framework.} \label{fig:best_arch} \vspace{-8pt} \end{figure*} \vspace{-2pt} Fig. \ref{fig:best_arch} visualizes the best network-level architecture discovered by our AutoPose framework. Diversified scales are preferred at the beginning. Branches with different scales receive balanced activations, with feature maps of lower resolutions ($8\times,16\times, 32 \times$) are processed earlier and features of the highest resolution ($4\times$) are later processed. Please see our supplementary materials for the details of the searched cell structures. \vspace{-8pt} \paragraph{Results on COCO} Tab. \ref{tab:coco} shows the performance of the discovered architecture on COCO validation dataset, compared with other state-of-the-art methods. Without any pretraining, our AP score significantly outperforms 8-stage Hourglass \cite{newell2016stacked} by 5.6 and CPN \cite{chen2018cascaded} by 5, with the same input size. We surpass the SimpleBaseline \cite{xiao2018simple} by 1.6 with 32.1\% less GFLOPs. Compared with the state-of-the-art HRNets, our model achieves competitive AP scores. AutoPose also shows clearly superior performance over the previous NAS for pose estimation work, PoseNFS \cite{yang2019pose}, with lower input image resolution and FLOPs. \begin{table*}[h] \caption{Comparison on the COCO validation set. The symbol $\dagger$ indicates the result obtained by reproducing with the author's official released code, as the original paper did not report the same setting. Models in the first block at table are hand-crafted models, while models in the second block are obtained by neural architecture search.} \vspace{2pt} \centering {\small \resizebox{0.8\linewidth}{!}{ \begin{tabular}{ l || c | c | c | c c c c c c} \hline Method & Pretrain & Image size & GFLOPs & AP & $\text{AP}^{50}$ & $\text{AP}^{75}$ & $\text{AP}^{M}$ & $\text{AP}^{L}$ & $\text{AR}$ \\\hline 8-stage Hourglass\cite{newell2016stacked} & N & $256 \times 192$ & 14.30 & 66.9 & - & - & - & - & -\\ 8-stage Hourglass\cite{newell2016stacked} & N & $256 \times 256$ & - & 67.1 & - & - & - & - & -\\ CPN\cite{chen2018cascaded} & Y & $256 \times 192$ & 6.20 & 68.6 & - & - & - & - & -\\ Posefix\cite{moon2019posefix} & Y & $256 \times 192$ & - & 71.5 & 88.0 & 77.6 & 68.0 & 78.1 & -\\ SimpleBaseline-50\cite{xiao2018simple} & Y & $256 \times 192$ & 8.90 & 70.4 & 88.6 & 78.3 & 67.1 & 77.2 & 76.3\\ SimpleBaseline-101\cite{xiao2018simple} & Y & $256 \times 192$ & 12.40 & 71.4 & 89.3 & 79.3 & 68.1 & 78.1 & 77.1\\ SimpleBaseline-152\cite{xiao2018simple} & Y & $256 \times 192$ & 15.70 & 72.0 & 89.3 & 79.8 & 68.7 & 78.9 & 77.8\\ HRNet-W32\cite{sun2019deep} & N & $256 \times 192$ & 7.10 & 73.4 & 89.5 & 80.7 & 70.2 & 80.1 & 78.9\\ HRNet-W48\cite{sun2019deep} $\dagger$ & N & $256 \times 192$ & 14.60 & 73.5 & 89.5 & 80.6 & 70.4 & 79.8 & 79.2\\ \hline PoseNFS-3 \cite{yang2019pose} & Y & $384 \times 288$ & 14.8 & 73.0 & - & - & - & - & - \\ AutoPose (Ours) & N & $256 \times 192$ & 10.65 & \textbf{73.6} & 90.6 & 80.1 & 69.8 & 79.7 & 78.1\\ \hline \end{tabular} } } \label{tab:coco} \vspace{-6pt} \end{table*} \vspace{-8pt} \paragraph{Results on MPII} We directly transfer the discovered architecture on the COCO dataset to train on the MPII dataset. We note that images from the MPII dataset are larger ($256\times 256$) than those in COCO ($256\times 192$), which is to our discovered architecture's disadvantage. Without any pretraining, the architecture designed by AutoPose surpasses ``ASR+AHO'' \cite{peng2018jointly}. We found that recent works (SimpleBaseline \cite{xiao2018simple} and HRNet \cite{sun2019deep}) adopt ImageNet pretraining and enjoy improved performance. Further discussion with the authors of HRNet \cite{sun2019deep} helped us confirm that adopting a pretraining backbone is vital to the performance boost and convergence for complicated pose estimation network, especially on relatively small datasets like MPII. This reveals a challenging issue when extending NAS to advanced computer vision tasks: as automatically designed architectures will require extra efforts to be pretrained on ImageNet, training from scratch is an unfair setting to NAS when compared with human-designed networks which adopt mature backbones pre-trained on extra data (e.g. ResNet101 \cite{he2016deep}). One remedy might be still leveraging a pretrained hand-crafted backbone followed by searched aggregation \cite{chen2018searching,ghiasi2019fpn}; but that will limit the flexibility of NAS and somehow contradict to the philosophy of AutoML. We leave this open challenge for future work. \subsection{Ablation Study} \label{sec:eval} \vspace{-4pt} \paragraph{Multi-Scale Search Space} Recently, Liu \etal proposed Auto-Deeplab \cite{liu2019auto} to search for both the cell-level and network-level architecture. However, their search architecture only allowed one scale to be activated per layer. \begin{table}[h] \caption{Transferability results on MPII validation dataset. No multi-scale testing technique is applied on our result.} \centering \resizebox{\linewidth}{!}{ \begin{tabular}{ l || c | c c c c c c c | c} \hline Method & Pretrain & Head & Shoulder & Elbow & Wrist & Hip & Knee & Ankle & Total \\\hline ``ASR+AHO'' \cite{peng2018jointly} & Y &97.3 &95.1 &88.7 &84.7 &88.4 &82.5 &78.1 &87.8 \\ Hourglass\cite{newell2016stacked} & N &96.5 & 96.0 & 90.3 & 85.4 & 88.8 & 85.0 & 81.9 & 89.2 \\ SimpleBaseline\cite{xiao2018simple} & Y & 97.0 & 95.9 & 90.3 & 85.0 & 89.2 & 85.3 & 81.3 & 89.6 \\ HRNet-W32\cite{sun2019deep} & Y & 97.1 & 95.9 & 90.3 & 86.4 & 89.1 & 87.1 & 83.3 & 90.3 \\ \hline AutoPose (Ours) & N & 96.6 & 95.0 & 88.3 & 83.2 & 87.2 & 82.8 & 78.9 & 88.0 \\ \hline \end{tabular} } \label{tab:mpii} \vspace{-5pt} \end{table} \begin{table} \vspace{-1pt} \caption{Evaluating our multi-scale parallel branches and aggregation cells on the COCO validation set.} \centering \resizebox{1.0\linewidth}{!}{ \begin{tabular}{ c | c || c c c c c c} \hline Aggregation Cell & Multi-branch & AP & $\text{AP}^{50}$ & $\text{AP}^{75}$ & $\text{AP}^{M}$ & $\text{AP}^{L}$ & $\text{AR}$ \\ \hline searched & searched (single) & 63.9 & 86.5 & 70.2 & 61.2 & 68.9 & 69.0 \\ N/A & searched & 70.8 & 90.4 & 77.6 & 67.2 & 77.0 & 75.3 \\ searched & fixed to four & 71.8 & 89.5 & 79.4 & 69.6 & 75.5 & 74.8 \\ searched & searched & 73.6 & 90.6 & 80.1 & 69.8 & 79.7 & 78.1\\ \hline \end{tabular} } \label{tab:ablation} \vspace{-7pt} \end{table} \begin{figure*}[t!] \vspace{-2pt} \begin{center} \includegraphics[width=0.88\linewidth]{imgs/visualization.pdf} \caption{The visualizations of predicted keypoints. The first and last two rows are the results on COCO and MPII, respectively.} \label{fig:qual} \end{center} \vspace{-8pt} \end{figure*} To demonstrate the effectiveness of the proposed multi-scale search space, we construct two variants of our network. First, we limit the maximum number of activated branch in each stage to one during search, i.e., degrading our parallel branches back to a single chain-like backbone. Second, we allow our multi-scale branches, but remove the context aggregations in our aggregation cells and instead adopt plain concatenation operations. Third, we manually keep all branches in all stages to be activated, and only search for the cell-level architecture. The ablation results are shown in Tab. \ref{tab:ablation}. When we only search one single scale per stage, the AP score dramatically drops to 63.9\%, demonstrating the key contribution of maintaining multiple scales throughout the network. When we activate multiple scales but bypass our aggregation cells, although the average precision under OKS = 0.5 achieves the similar bar (90.4\% v.s. 90.6\%), large OKS (0.75) will drop, implying the cross-scale context aggregation to be vital here. When we manually activate all four branches across all stages during search and evaluation, and only search for the micro cell-level structure, the performance remains to be lower than our proposed method. \vspace{-8pt} \paragraph{Bi-level Optimization} As existing NAS works only adopt a single search algorithm throughout their framework, we are the first to leverage a bi-level optimization for different aspects of our search space. Fig. \ref{fig:entropy} visualizes the convergences and performance during our search process. We can see that the validation accuracy steadily improves throughout the search process, while both the cell-level and network-level optimizations are converged to a small subset of the search space, indicated by the decreasing entropies. \vspace{-4pt} \begin{figure}[h] \begin{center} \includegraphics[width=0.85\linewidth]{imgs/entropy_pck.pdf} \end{center} \vspace{-1em} \caption{During the search process, the entropies of both cell-level and network-level architecture are decreasing (i.e. the supernet is becoming confident in its derived architecture), while the validation AP and controller's reward keep increasing (i.e. the performance of our supernet is being improved). Note that we begin to train the controller at 5-th epoch.} \label{fig:entropy} \vspace{-4pt} \end{figure} \vspace{-8pt} \paragraph{Image Size during searching} Previous work \cite{liu2019auto} reduced the input image size during the search phase to accelerate NAS. However, we argue that for dense image prediction tasks like pose estimation which requires fine details in context, adopting reduced input size during search amplifies the gap between the search and the train from scratch processes. We conduct an experiment where we use the size of $128\times96$ during searching, while still keep the size of $256\times192$ during training from scratch. In Tab. \ref{tab:size}, we can see an obvious performance drop when the image size is reduced during searching. \begin{table}[h] \caption{Impact of image sizes during search (evaluated on the COCO validation set).} \centering \resizebox{1.0\linewidth}{!}{ \begin{tabular}{ c | c || c c c c c c} \hline \multicolumn{2}{c||}{Image size} & \multirow{2}{*}{AP} & \multirow{2}{*}{$\text{AP}^{50}$} & \multirow{2}{*}{$\text{AP}^{75}$} & \multirow{2}{*}{$\text{AP}^{M}$} & \multirow{2}{*}{$\text{AP}^{L}$} & \multirow{2}{*}{$\text{AR}$} \\ \multicolumn{1}{c}{Search} & \multicolumn{1}{c||}{Train} & & & & & & \\ \hline \multicolumn{1}{c|}{$128 \times 96$} & $256 \times 192$ & 70.1 & 89.6 & 75.9 & 66.1 & 75.8 & 74.5 \\ \multicolumn{1}{c|}{$256 \times 192$} & $256 \times 192$ & 73.6 & 90.6 & 80.1 & 69.8 & 79.7 & 78.1 \\ \hline \end{tabular} } \label{tab:size} \vspace{-2pt} \end{table} \vspace{-6pt} \section{Conclusion} \vspace{-4pt} We propose AutoPose for the 2D human pose estimation task. Our high-capacity multi-scale search space supports the discovery of multiple parallel branches of diverse scales. By leveraging both gradient-based cell-level search and reinforcement learning based network-level search, our AutoPose successfully discovers the architecture that achieves very competitive performance on COCO and MPII dataset. We believe that pursuing an optimal combination of both cell-level and network-level structure is vital to accurate pose estimation, and wish our work to further advocate more NAS practice in advanced computer vision applications, with more reflections in the pros and cons. \clearpage {\small \bibliographystyle{ieee_fullname}
{'timestamp': '2020-08-18T02:21:03', 'yymm': '2008', 'arxiv_id': '2008.07018', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07018'}
arxiv
\section{Introduction} Humans use natural language (NL\xspace) to communicate with each other. Accordingly, a desired method for conveying goals or assigning tasks to an autonomous machine (e.g., a robot) is also by NL\xspace. For example, in household tasks, when asking an agent to pick up a toolbox from the garage, we do not assign the coordinates of the toolbox to the robot. Instead, we state to the agent \textit{retrieve my toolbox from the garage}. This requires the agent to understand the semantics of the natural language goals, associate states and actions with the natural language goals, and infer whether the natural language goals are achieved or not -- all of which are very challenging tasks. Furthermore, we want to be able to learn policies that are robust to lexical variation in goals and generalize well to new goals and environments. Inverse reinforcement learning (IRL)~\citep{abbeel2004apprenticeship,fu2018learning}, a form of imitation learning~\citep{osa2018algorithmic}, is the task of learning a reward function and hence a policy based on expert demonstrations. Imitation learning has been successfully applied to a wide range of tasks including robot manipulation~\citep{finn2016guided}, autonomous driving~\citep{kuefler2017imitating}, human behavior forecasting~\citep{rhinehart2017first}, video game AI~\citep{tucker2018inverse}. Generally, task goals are specified intrinsically by the environment and an agent is trained for each task. To generalize the learned policy to new goals, goal-conditioned imitation learning~\citep{ding2019goal} and reinforcement learning (RL\xspace) algorithms~\citep{kaelbling1993learning,schaul2015universal,nair2018visual} have been proposed where the policy is explicitly conditioned on a goal. Normally, the goals either share the same space with the states or can be easily mapped to the state space. For example, in~\citet{ding2019goal}, the goals and states are both coordinates in the environment and the goals are provided to the agent by specifying goal positions. \citet{fu2019language} and \citet{bahdanau2018learning} represent two recent related works from the perspective of understanding NL\xspace goal specifications, where they propose learning a language-conditioned reward function under the maximum entropy inverse reinforcement learning~\citep{ziebart2008maximum} and generative adversarial imitation learning frameworks~\citep{ho2016generative}. However, the NL\xspace goals are produced by a preset template-based grammar. \citet{fu2019language}'s policy is optimized exactly in a grid environment with known dynamics and when the policy is optimized by sample-based reinforcement learning algorithms such as deep Q-learning~\citep{mnih2015human}, the model performance drops significantly. This reveals a sample efficiency challenge in this setting and implies that when the NL\xspace goals and the environments are complicated, generalization to new goals and environments becomes a very difficult problem. One potential method for addressing these shortcomings are goal relabeling techniques such as hindsight experience replay (HER)~\citep{andrychowicz2017hindsight} and latent goal relabeling~\citep{nair2018visual}, which have been shown to improve sample efficiency in RL\xspace settings. However, when the goals are NL\xspace and are in a different space than the state space, goal relabeling cannot be applied directly as we cannot easily relabel a state to a NL\xspace goal. \citet{cideron2019self} proposes to build such a relabeling function with a \textsc{Seq2Seq} model that takes a trajectory as input and outputs a relabeled NL\xspace goal. However, this uses the ground-truth reward function and their experiments are again based on simple template-based NL\xspace goals. Moreover, as we will show in this paper, applying HER to IRL with NL\xspace goals doesn't significantly improve performance, as the reward function does not generalize well to relabeled goals. In this work, we propose a sample efficient IRL algorithm with natural language (NL\xspace) goals. To the best of our knowledge, our work is the first IRL algorithm that works with real human generated NL\xspace goals (as opposed to template-based language goals~\citep{fu2018learning,bahdanau2018learning}) in a real world vision-based environment. Our contributions include: (1) proposing a NL\xspace goal-conditioned adversarial inverse reinforcement learning algorithm, (2) specifying a variational goal generator that efficiently sample diverse NL\xspace goals given a trajectory, (3) utilizing goal relabeling and sampling strategies to improve the generalization of both the policy and the reward function to new NL\xspace goals and new environments, (4) proposing a self-supervised learning mechanism to further improve the generalization in new environments. Through these innovations, we show that our algorithm significantly outperform strong baselines on the Room-2-Room dataset~\citep{anderson2018vision}. \section{Problem Formulation} A task is defined as a pair $(E, G)$, where $E$ is an environment that the agent can interact with and $G$ is a NL\xspace goal that the agent has to fulfill. $G=\{w_1, w_2, ..., w_N\}$ consists of $N$ words. For example, in our experiments, $E$ is a realistic 3D indoor environment and $G$ is a human-generated navigation instruction. The true reward function of each task is unknown, but there exists a set of expert demonstrations consisting of a task ($E$, $G$) and a trajectory $\tau$. The trajectory $\tau = \{s_1, a_1, s_2, a_2, ..., s_T, a_T\}$ consists of a sequence of $T$ states perceived by the experts and the actions taken by the experts given the states. For example, in our experiments the states are first-person views in a 3D indoor environment and the actions are movements towards a direction in the environment. While our proposed methods can be applied to both continuous and discrete action spaces, we focus on discrete action spaces in this paper. The objective of the algorithm is to learn a policy that imitates expert demonstrations such that given a new NL\xspace goal in an existing or new environment, the agent can perform a sequence of actions to achieve that goal. In this paper, we use $G$ to represent an arbitrary goal, $\bm{G}$ to represent the set of goals in expert demonstrations, and $G_i$ to represent the $i$-th goal in $\bm{G}$. The same notation style applies to $E$ and $\tau$ too. \section{Method} \subsection{Preliminary: Adversarial Inverse Reinforcement Learning (AIRL)} AIRL~\cite{fu2018learning} is based on maximum entropy inverse reinforcement learning (MaxEntIRL)~\cite{ziebart2008maximum}. In MaxEntIRL, the probability of a trajectory is defined as $p_\theta(\tau) = \frac{1}{Z} \exp(f_\theta(\tau))$, where $f_\theta$ is the reward function to learn and $Z = \sum_{\tau} \exp(f_{\theta}(\tau))$ is the partition function. MaxEntIRL learns the reward function from expert demonstrations by maximizing the likelihood of trajectories in the expert demonstrations: $\max_\theta \mathbb{E}_{\tau \sim \mathcal{D}}(\log p_\theta(\tau))$. Maximizing this likelihood is challenging because the partition function $Z$ is hard to estimate. AIRL maximizes this likelihood by using a generative adversarial network (GAN)~\cite{goodfellow2014generative}. The GAN generator is the policy $\pi$ to learn and the GAN discriminator is defined as \begin{linenomath} \postdisplaypenalty=0 \begin{align} D_{\theta, \phi}(s, a, s') = \frac{\exp \{ f_{\theta, \phi}(s, a, s') \}}{\exp \{ f_{\theta, \phi}(s, a, s') \} +\pi(a|s)} \label{eq:discri} \end{align} \end{linenomath} where $f_{\theta, \phi}(s, a, s') = g_\theta(s, a) + \gamma h_\phi(s') - h_{\phi}(s)$, $g_\theta(s, a)$ is the reward function to learn, and $h_{\phi}(s') - h_\phi(s)$ is the reward shaping term. The policy $\pi$ and the discriminator are updated alternately. \subsection{Inverse Reinforcement Learning with Natural Language Goals} \label{sec:ilnlg} Our AIRL-based solution builds on language-conditioned reward learning (LC-RL)~\citep{fu2019language} by adding template-free NL\xspace capabilities and continuous state space support. In this problem setting, the policy and the reward function are conditioned on a NL\xspace goal $G$, so we first extend the discriminator in Equation (\ref{eq:discri}) to have $f_{\theta, \phi}(s, a, s', G) = g_\theta(s, a, G) + \gamma h_\phi(s', G) - h_\phi(s, G)$ such that \begin{linenomath} \postdisplaypenalty=0 \begin{align*} g_\theta(s, a, G) &= \text{MLP}([e^s; \text{Att}(s, G); e^a]) \\ h_\phi(s, G) &= \text{MLP}([e^s; \text{Att}(s, G)]) \end{align*} \end{linenomath} where $\text{MLP}(\cdot)$ is a multilayer Perceptron, $e^s$ and $e^a$ are the embeddings of state $s$ and action $a$, respectively, and $\text{Att}(s, G)$ is an attention function. $\text{Att}(s, G) = \sum \alpha_i e^w_i$ where $e^w_i$ is the word embedding of $w_i$ in $G$, $\alpha_i = \left(\text{Linear}(e^s) \cdot e^w_i \right) / \left(\sum_i \text{Linear}(e^s) \cdot e^w_i \right)$ and $\text{Linear}(\cdot)$ is a single-layer Perceptron. We use soft actor-critic (SAC)~\cite{haarnoja2018soft}, one of the state-of-the-art off-policy RL\xspace algorithms, to optimize policy $\pi$ given the reward function $g_\theta(s, a, G)$. SAC includes a policy network to predict an action given a state and a goal, and a Q-network that estimate the Q-value of an action given a state and a goal. We define the policy network as \begin{linenomath} \postdisplaypenalty=0 \begin{align*} \pi_{w}(s, a, G) = \text{Softmax}(e^a \cdot \text{MLP}([e^s; \text{Att}(s, G)])) \end{align*} \end{linenomath} and we define the Q-network $q_{\psi}(s, a, G)$ as the same network architecture as $g_\theta$. Compared with on-policy algorithms such as TRPO~\cite{schulman2015trust}, SAC utilizes a replay buffer to re-use sampled trajectories. The replay buffer is beneficial to training both the discriminator and the policy. \textit{To update the discriminator}, we sample negative $(s, a, s', G)$ examples from the replay buffer and sample positive $(s, a, s', G)$ examples from the expert demonstrations. \textit{To update the policy}, we sample a batch of $(s, a, s', G)$ from the replay buffer and use $g_\theta$ to estimate their rewards; then we update the Q- and policy network using these reward-augmented samples. We modify SAC slightly to support discrete action spaces. Appendix \ref{appendix:impdetail} contains details about model architecture and optimization. \subsection{A Variational Goal Generator for Improved Generalization and Sample Efficiency} \label{sec:vgg} While SAC has better sample efficiency than many on-policy RL algorithms, as we will show in our experiments, in environments with complicated NL\xspace goals and high dimensional state spaces (e.g., vision-based instruction following), AIRL with SAC performs only slightly better than supervised learning based behavior cloning and the learned policy and discriminator doesn't generalize well to new goals or new environments. In this section, we show that by learning a variational goal generator, we can enrich the training data for both the discriminator and the policy, which leads to large improvements in sample efficiency and generalization for both the discriminator and policy in NL\xspace settings. A goal generator takes a trajectory $\tau$ (sequence of states and actions) as input and outputs a NL\xspace goal $G$. Given expert demonstrations, a straightforward way of learning a goal generator is to train an encoder-decoder model that encodes a trajectory and decodes a NL\xspace goal. However, in reality, there are many possible ways to describe a specific trajectory using NL\xspace, and the description will likely be biased due to variance in people's expression preferences. For example, consider a trajectory in which the agent goes to the kitchen and washes the dishes. Two possible goal descriptions for this trajectory can be \textit{go to the kitchen and wash the dishes} or \textit{clean the dishes on the dining table}. To better model variations and generate more diverse NL\xspace goals, we learn a variational encoder-decoder model as goal generator. The generative process of the variational goal generator is \begin{linenomath} \postdisplaypenalty=0 \begin{gather*} \mu_{prior}, \sigma^2_{prior} = f_{prior}\left(\tau \right) \\ z \sim \mathcal{N}\left(\mu_{prior}, \sigma_{prior}^2\mathbf{I}\right) \\ G = f_{dec}\left(z, \tau \right) \end{gather*} \end{linenomath} where $f_{prior}$ is a LSTM-based trajectory encoder and $f_{dec}$ is an attention-based goal decoder. The posterior distribution of latent variable $z$ is approximated by \begin{linenomath} \postdisplaypenalty=0 \begin{gather*} \mu_{posterior}, \sigma_{posterior}^2 = f_{posterior}\left(\tau, G \right)\\ q\left(z|\tau, G\right) = \mathcal{N}\left(z | \mu_{posterior}, \sigma^2_{posterior}\mathbf{I}\right) \end{gather*} \end{linenomath} where $f_{posterior}$ is a LSTM-based trajectory and goal encoder. We then maximize the variational lower bound $-D_{KL}(q(z|\tau, G)||p(z)) + \mathbb{E}_{q(z|\tau, G)} [\log p(G|z, \tau)]$. Network architecture and optimization details are in Appendix \ref{appendix:impdetail}. Given the learned variational goal generator, we propose using three goal relabeling and sampling strategies to improve generalization as itemized below. \subsubsection{Expert Goal Relabeling (EGR).} As discussed previously, multiple goals can be mapped to the same trajectory. We propose to augment expert demonstrations by generating $N$ other goals for each expert trajectory $\tau_i$: $G_{i, n} \sim \text{GoalGenerator}(\tau_i),\ n=\{1, 2, ..., N\}$, where $G_{i, n}$ is the $n$-th generated goal for $\tau_i$, and $\text{GoalGenerator}(\cdot)$ is the learned variational goal generator. For expository and experimental simplicity, we set $N=2$, which works well for this dataset. Model performance under different values of $N$ are shown in Appendix \ref{appendix:addexp}. These newly generated tuples $\{(E_i, G_{i, n}, \tau_i)\}_{n=1}^N$ are also treated as expert demonstrations for training. We represent the set of goals in the augmented expert demonstrations by $\bm{G}^1$ where the superscript of $\bm{G}$ represents the round of generation as described shortly. \subsubsection{Hindsight Goal Relabeling (HGR) for the Discriminator.} \label{sec:hgrd} In the AIRL framework, the quality of the discriminator is crucial to the generalization of the learned policy. A good discriminator learns a good reward function that generalizes well to new goals and new environments such that the learned policy can also well generalize to new goals and new environments~\cite{fu2019language}. To improve the discriminator, we propose to augment the positive examples of the discriminator by relabeling the goals of the sampled trajectories. More specifically, during the training, given a goal $(E_j, G^1_j)$, the agent interacts with the environment and samples a trajectory $\tau^1_j$. We then use the variational goal generator to sample a goal for $\tau^1_j$: \begin{linenomath} \postdisplaypenalty=0 \begin{align} \tau^1_j &\sim \pi(E_j, G^1_j) \label{eq:g1} \\ G^2_j &\sim \text{GoalGenerator}(\tau^1_j) \end{align} \end{linenomath} The tuples $(\bm{E}, \bm{G}^2, \bm{\tau}^1)$ are treated as positive examples for the discriminator, as a supplement to the positive examples from expert demonstrations $(\bm{E}, \bm{G}^1, \bm{\tau})$. \subsubsection{Hindsight Goal Sampling (HGS) for Policy Optimization.} When optimizing the policy with SAC, we have to sample NL\xspace goals to train the policy. One natural way is to sample goals from expert demonstrations. However, expert demonstrations are relatively scarce, expensive to acquire, and it is difficult to cover goal variance encountered in the testing. Meanwhile, as we will show in our experiments, training with a diverse set of goals is beneficial to the generalization of the policy. Therefore, we propose to also sample goals from $\bm{G}^2$ so that the policy can train with goals beyond these in the expert demonstrations. \begin{linenomath} \postdisplaypenalty=0 \begin{align} \tau_j^2 &\sim \pi(E_j, G^2_j) \\ G^3_j &\sim \text{GoalGenerator}(\tau^2_j) \label{eq:g3} \end{align} \end{linenomath} Of course, training the policy with $\bm{G}^2$ relies on the discriminator's generalization ability to provide reasonable reward estimates for states and actions sampled under $\bm{G}^2$. This is ensured by HGR in Section \ref{sec:hgrd}, as $(\bm{E}, \bm{G}^2, \bm{\tau}^1)$ are provided as positive examples for the discriminator. The process from Equation (\ref{eq:g1}) to Equation (\ref{eq:g3}) can be seen as using $\bm{G}^1$ and $\bm{\tau}$ as seed, and iteratively sample $\bm{\tau}^{v}$ from $\bm{G}^v$ using the policy, and then sample $\bm{G}^{v+1}$ from $\bm{\tau}^{v}$ using the goal generator. We can go deeper in this loop to sample more diverse NL\xspace goals and trajectories for policy and discriminator training. More specifically, \textit{to train the discriminator}, positive examples are sampled from $(\bm{E}, \bm{G}^1, \bm{\tau})$ with probability $0.5$, and are sampled from $\{(\bm{E}, \bm{G}^{v+1}, \bm{\tau}^v)|v \ge 1\}$ with probability $0.5$; negative examples are sampled from $\{(\bm{E}, \bm{G}^v, \bm{\tau}^v)|v \ge 1\}$. \textit{To train the policy}, goals are sampled from $(\bm{E}, \bm{G}^1)$ with probability $0.5$ and are sampled from $\{(\bm{E}, \bm{G}^{v+1})| v\ge 1\}$ with probability $0.5$. Algorithm \ref{algo:algo} shows the overall description for LangGoalIRL. \subsubsection{Hindsight Experience Replay (HER) for Policy Optimization.} A closely related approach, hindsight experience replay~\citep{andrychowicz2017hindsight}, has been shown to work very well in RL\xspace settings with sparse rewards. In principle, we could easily incorporate HER into our training procedure. That is, when sampling from replay buffer to optimize policy $\pi$, we sample batches not only from $\{(\bm{E}, \bm{G}^v, \bm{\tau}^{v})\ | v \ge 1\}$, but also from $\{(\bm{E}, \bm{G}^{v+1}, \bm{\tau}^v)\ | v \ge 1\}$. The difference between HER and HGR is that the former is goal relabeling for the policy while the latter is goal relabeling for the discriminator. HER is most efficient when rewards are sparse; however, in our setting, the rewards provided by the discriminator are not sparse and we do not observe a boost of performance after applying HER. This is discussed in greater detail in Section~\ref{sec:experiments}. \algnewcommand{\LineComment}[1]{\State \(\triangleright\) #1} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \begin{algorithm}[!t] \footnotesize \caption{Inverse Reinforcement Learning with Natural Language Goals (LangGoalIRL)} \begin{algorithmic}[1] \Require GoalGenerator: the variational goal generator from section \ref{sec:vgg}; $\mathcal{D}$: expert demonstrations; $\mathcal{R}=\varnothing$: replay buffer; $b$: batch size; N: number of expert relabeling goals. \State $\tilde{\mathcal{D}} = \varnothing$, $\mathcal{G} = \varnothing$ \For{each $(E_i, G_i, \tau_i) \in \mathcal{D}$} \For{n = 1, 2, ..., N} \LineComment{\textbf{Expert Goal Relabeling (EGR)}} \State $G_{i, n} \sim \text{GoalGenerator}(\tau_i)$ \EndFor \State add $(E_i, G_i, \tau_i)$ and $\{(E_i, G_{i,n}, \tau_i)\}_{n=1}^N$ to $\tilde{\mathcal{D}}$ \EndFor \While{not converged} \State $r_1, r_2 \sim \text{Uniform}(0, 1)$ \If{$r_1 < 0.5$} \State Sample a goal $(E_j, G_j) \sim \tilde{\mathcal{D}}$ \Else \LineComment{\textbf{Hindsight Goal Sampling (HGS)}} \State Sample a goal $(E_j, G_j) \sim \mathcal{G}$ \EndIf \State Sample a trajectory $\tau'_j \sim \pi(E_j, G_j)$ \State Sample a relabeled goal $G'_j \sim \text{GoalGenerator}(\tau'_j)$ \State Add $(E_j, G_j, G'_j, \tau'_j)$ to replay buffer $\mathcal{R}$ \State Add $(E_j, G'_j)$ to $\mathcal{G}$ \If{$r_2 < 0.5$} \State Sample a batch $\mathcal{P}_{+} = \{(s_k^t, a_k^t, s_k^{t+1},G_k)\}_{k=1}^{b} \sim \tilde{\mathcal{D}}$ \Else \LineComment{\textbf{Hindsight Goal Relabeling (HGR)}} \State Sample a batch $\mathcal{P}_{+} = \{(s_k^t, a_k^t, s_k^{t+1},G'_k)\}_{k=1}^{b} \sim \mathcal{R}$ \EndIf \State Sample a batch $\mathcal{P}_{-} = \{(s_k^t, a_k^t, s_k^{t+1}, G_k)\}_{k=1}^{b} \sim \mathcal{R}$ \State Update discriminator parameters with $\mathcal{P}_{+}$ and $\mathcal{P}_{-}$ as positive and negative examples, respectively \State Sample a batch $\mathcal{Q} = \{(s_k^t, a_k^t, s_k^{t+1}, G_k)\}_{k=1}^{b} \sim \mathcal{R}$ \State Expand each entry of $\mathcal{Q}$ with reward $r_k^t = g_\theta(s_k^t, a_k^t, G_k)$ \State Optimize $\pi$ using Soft Actor-Critic with $\mathcal{Q}$ \EndWhile \end{algorithmic} \label{algo:algo} \end{algorithm} \subsection{Self-Supervised Learning in New Environments} \label{sec:ss} In this section, we specifically examine the scenario where the learned policy is deployed to a new environment. For example, after training an embodied agent to perform tasks in a set of buildings, we may deploy this agent to a new building with different floor plans. We assume that we have access to these new environments, but we do not have any expert demonstrations nor any NL\xspace goals in new environments. Note that we can not directly apply NL\xspace goals from existing environments to new environments, because goals are tied to the environments. For example, in instruction-following tasks, an example goal is \textit{go downstairs and walk pass the living room}. However, there may be no stairs in a new environment. As a result, we can not just sample goals from expert demonstrations to train in the new environments. The high-level idea of our method is to first learn a policy $\pi_p$ that is goal-agnostic. That is, the policy selects an action purely based on the state without conditioning on a goal. This model gives us a prior of how the agent will act given a state. We use behavior cloning to train this policy on expert demonstrations. More details are available in Appendix \ref{appendix:impdetail}. We then sample trajectories in the new environments using this policy and sample goals of these trajectories using the goal generator: \begin{linenomath} \postdisplaypenalty=0 \begin{align*} \tau^{new} &\sim \pi_{p}(E^{new}) \\ G^{new} &\sim \text{GoalGenerator}(\tau^{new}) \end{align*} \end{linenomath} $(\bm{E}^{new}, \bm{G}^{new}, \bm{\tau}^{new})$ are treated as expert demonstrations in the new environments. We then fine-tune the discriminator and the policy in new environments using Algorithm~\ref{algo:algo} (w/o expert goal relabeling). The self-supervised learning signals come from both the generated expert demonstrations for the new environments, and the hindsight goal relabeling and sampling proposed in Section \ref{sec:vgg}. The generated expert demonstrations can be seen as seeds to bootstrap hindsight goal relabeling and sampling. \section{Experiments} \label{sec:experiments} While LangGoalIRL\xspace works on any natural language (NL\xspace) goal based IRL problems, our experiments focus on a challenging vision-based instruction following problem. We evaluate our model on the Room-2-Room (R2R) dataset~\citep{anderson2018vision}, a visually-grounded NL\xspace navigation task in realistic 3D indoor environments. The dataset contains $7{,}189$ routes sampled from $90$ real world indoor environments. A route is a sequence of viewpoints in the indoor environments with the agent's first-person camera views. Each route is annotated by humans with $3$ navigation instructions. The average length of navigation instructions is $29$ words. The dataset is split into train ($61$ environments and $14{,}025$ instructions), seen validation ($61$ environments same as train set, and $1{,}020$ instructions), unseen validation ($11$ new environments and $2{,}349$ instructions), and test ($18$ new environments and $4{,}173$ instructions). We don't use the test set for evaluation because the ground-truth routes of the test set are not released. Along with the dataset, a simulator is provided to allow the embodied agent to interact with the environments. The observation of the agent is the first-person camera view, which is a panoramic image. The action of the agent is the nearby viewpoints that the agent can move to. For details about the dataset, please see Appendix \ref{appendix:data}. The R2R dataset has become a very popular testbed for language grounding in visual context~\citep{tan2019learning,wang2019reinforced,fried2018speaker,zhu2020vision}. We evaluate the model performance based on the trajectory success rate. Each navigation instruction in the R2R dataset is labeled with a goal position. Following~\citet{anderson2018vision}, the agent is considered successfully reaching the goal if the navigation error (the distance between the stop position and the goal position) is less than 3 meters. Note that the goal position is not available to our model, as we use navigation instructions as goals. We compare our model with the following baselines: (1) \textbf{LangGoalIRL\_BASE}, which corresponds to our proposed model in Section \ref{sec:ilnlg} {\em without} the goal relabeling/sampling strategies proposed in Section \ref{sec:vgg}. (2) \textbf{Behavior Cloning}, which is imitation learning as supervised learning. The model shares the same architecture as the policy network of LangGoalIRL and is trained to minimize cross entropy loss with actions in the expert demonstrations as labels. (3) \textbf{LC-RL (Sampling)}~\cite{fu2019language}, which also uses MaxEntIRL~\cite{ziebart2008maximum} to learn a reward function. It optimizes the policy exactly in a grid environment, which is not scalable to our experimental setting, so we use AIRL with SAC for LC-RL to optimize the policy. In this case, LC-RL is very similar to LangGoalIRL\_BASE, except that LC-RL simply concatenates state and goal embeddings as input to the policy and reward function, while LangGoalIRL\_BASE uses the attention mechanism $\text{Att}(s, G)$ in Section \ref{sec:ilnlg}. (4) \textbf{AGILE}~\cite{bahdanau2018learning}, which proposes to learn a discriminator (reward function) that predicts whether a state is the goal state for a NL\xspace goal or not. The positive examples for the discriminator are the (NL\xspace goal, goal state) pairs in expert demonstrations, and the negative examples are sampled from the replay buffer of SAC. (5) \textbf{HER}~\cite{andrychowicz2017hindsight,cideron2019self}, which uses our learned variational goal generator to relabel trajectories. This corresponds to the \texttt{final} strategy in~\citet{andrychowicz2017hindsight} applied to LangGoalIRL\_BASE. (6) \textbf{Upper Bound}~\citep{tan2019learning}. Recently, there are a few vision-language navigation models~\cite{tan2019learning,wang2019reinforced,fried2018speaker,zhu2020vision} developed and evaluated on R2R dataset. However, they assume the goal positions or the optimal actions at any states are known, and assume the environments can be exhaustively searched without sample efficiency considerations in order to do training data augmentation. As a result, their problem settings are not really comparable, but we include~\citet{tan2019learning}'s result a potential upper bound. Note that without the additional information described above, their model performance reverts to our \textbf{Behavior Cloning} baseline. We will discuss this more in Section~\ref{sec:related}. For implementation details of our algorithms and the baselines, please refer to Appendix \ref{appendix:impdetail}. \begin{figure*}[t] \captionsetup{font=footnotesize} \captionsetup[subfigure]{font=scriptsize} \centering \makebox[\linewidth][c]{ \begin{subfigure}[b]{0.35\textwidth} \centering \includegraphics[width=\textwidth]{fig1.png} \caption{Baseline performance in seen validation.} \end{subfigure} \begin{subfigure}[b]{0.35\textwidth} \centering \includegraphics[width=\textwidth]{fig2.png} \caption{HER variants performance in seen validation.} \end{subfigure} \begin{subfigure}[b]{0.35\textwidth} \centering \includegraphics[width=\textwidth]{fig6.png} \caption{Self-supervised learning in unseen validation.} \end{subfigure} } \makebox[\linewidth][c]{ \begin{subfigure}[b]{0.35\textwidth} \centering \includegraphics[width=\textwidth]{fig5.png} \caption{More self-supervised learning in unseen validation.} \end{subfigure} \begin{subfigure}[b]{0.35\textwidth} \centering \includegraphics[width=\textwidth]{fig4.png} \caption{Ablation study in seen validation.} \end{subfigure} \begin{subfigure}[b]{0.35\textwidth} \centering \includegraphics[width=\textwidth]{fig3.png} \caption{More ablation study in seen validation.} \end{subfigure} } \captionsetup{width=1.0\textwidth} \caption{Model performance on both seen and unseen validation. LangGoalIRL\_SS in Figure (c) and (d) represents self-supervised learning in unseen environments. LangGoalIRL\_SS (15K) means that $15,000$ demonstrations are sampled by the goal-agnostic policy $\pi_p$. Random Explore means that a random policy instead of $\pi_p$ is used to sample demonstrations. LangGoalIRL\_SS\_G2 means that the policy does not iteratively sample goals from $\{(\bm{E}, \bm{G}^v) | v > 2\}$ as described in Section 3.3.3.} \label{fig:res} \end{figure*} The performance of our algorithm and baselines are shown in Figure \ref{fig:res}, Table \ref{tb:res}, and Table \ref{tb:ablation}. From the results, we would like to highlight the following observations. 1.\ \textbf{LangGoalIRL outperforms baselines by a large margin.} From Table \ref{tb:res} and Figure \ref{fig:res}(a) we can see that LangGoalIRL achieves a $0.530$ success rate on seen validation set, a $47.63\%$ improvement over LC-RL (sampling) and a $129\%$ improvement over AGILE. Rewards learned by AGILE are binary and sparse, which may be one of the main reasons why AGILE performs even worse than Behavior Cloning. The difference between LC-RL (sampling) and LangGoalIRL\_BASE is just the lack of attention mechanism over NL\xspace goals, which simply indicates that attention mechanism is important when NL\xspace goals are complicated. Other powerful attention mechanisms such as the Transformer architecture~\cite{vaswani2017attention} could also be easily considered. The success rate of LangGoalIRL is $18.04\%$ and $15.91\%$ higher than LangGoalIRL\_BASE on seen validation and unseen validation, respectively, which shows that the three proposed strategies efficiently improve the generalization of the policy to new NL\xspace goals and new environments. From Figure \ref{fig:res}(b) we see that, when combined with HER, LangGoalIRL converges slower and performs worse than LangGoalIRL alone. HER has been shown to efficiently deal with reward sparsity; however, the rewards learned by AIRL are not sparse. From Table \ref{tb:res} we see that HER alone barely outperforms LangGoalIRL\_BASE. As we will discuss shortly, HER only improves the sample efficiency of the \emph{generator (policy)}, however, the generalization of the \emph{discriminator (reward function)} is what is crucial to the overall performance of the policy. Finally, from Figure \ref{fig:res}(b) we can also see that LangGoalIRL\_BASE consistently outperforms Behavior Cloning after about 200k interactions, which effectively indicates the benefit of using inverse reinforcement learning over behavior cloning. \begin{table}[t] \centering \resizebox{\linewidth}{!}{ \begin{tabular}{l|cc} \hline & seen validation & unseen validation \\ \hline Behavior Cloning & $0.445 \pm 0.0122$ &$0.300 \pm 0.0114$ \\ LC-RL (sampling) & $0.359 \pm 0.0117$ & $0.216 \pm 0.0081$ \\ AGILE & $0.231 \pm 0.0173$ &$0.253 \pm 0.0269$ \\ HER & $0.464 \pm 0.0126$ &$0.306 \pm 0.0173$ \\ \hline LangGoalIRL\_BASE & $0.449 \pm 0.0130$ & $0.308 \pm 0.0087$ \\ LangGoalIRL & $\mathbf{0.530 \pm 0.0138}$ & $0.357 \pm 0.0089$ \\ \ \ +self-supervised & \textendash & $\mathbf{0.491 \pm 0.0065}$ \\ \hline Upper Bound & 0.621 & 0.645 \\ \hline \end{tabular} } \caption{Success rate after 1 million environment interactions. LangGoalIRL+self-supervised is further fine-tuned in unseen environment for 1 million environment interactions (explained in Figure 1(c)).} \label{tb:res} \end{table} \begin{table}[t] \centering \resizebox{\linewidth}{!}{ \begin{tabular}{ccc|c} \hline \begin{tabular}[c]{@{}c@{}}Expert\\ Goal Relabeling\end{tabular} & \begin{tabular}[c]{@{}c@{}}Hindsight\\ Goal Relabeling\end{tabular} & \begin{tabular}[c]{@{}c@{}}Hindsight\\ Goal Sampling\end{tabular} & \begin{tabular}[c]{@{}c@{}}seen validation\\ success rate\end{tabular} \\ \hline \textendash & \textendash & \textendash & $0.449 \pm 0.0130$ \\ \hline \ding{51} & \textendash & \textendash & $0.450 \pm 0.0122$ \\ \textendash & \ding{51} & \textendash & $0.427 \pm 0.0048$ \\ \textendash & \textendash & \ding{51} & $0.399 \pm 0.0124$ \\ \hline \ding{51} & \ding{51} & \textendash & $0.504 \pm 0.0185$ \\ \ding{51} & \textendash & \ding{51} & $0.444 \pm 0.0134$ \\ \textendash & \ding{51} & \ding{51} & $0.503 \pm 0.0117$ \\ \hline \ding{51} & \ding{51} & \ding{51} & $\mathbf{0.530 \pm 0.0138}$ \\ \hline \end{tabular} } \caption{Ablation study of the three proposed strategies on seen validation set. A complete ablation study which includes HER is in Table \ref{tb:fullablation} of Appendix \ref{appendix:addexp}.} \label{tb:ablation} \end{table} \begin{table*}[] \resizebox{1.0\linewidth}{!}{ \begin{tabular}{|l|c|c|c|c|c|c|} \hline & LangGoalIRL & \begin{tabular}[c]{@{}c@{}}Language Goal-Conditioned IRL\\ \citep{fu2019language}\\ \citep{bahdanau2018learning}\end{tabular} & \begin{tabular}[c]{@{}c@{}}Language Goal-Conditioned RL\\ \citep{cideron2019self}\\ \citep{jiang2019language}\end{tabular} & \begin{tabular}[c]{@{}c@{}}State Goal-Conditioned IRL\\ \citep{ding2019goal}\end{tabular} & \begin{tabular}[c]{@{}c@{}}State Goal-Conditioned RL\\ \citep{andrychowicz2017hindsight}\\ \citep{plappert2018multi}\end{tabular} & \begin{tabular}[c]{@{}c@{}}SoTA models on R2R dataset\\ \citep{tan2019learning}\\ \citep{fried2018speaker}\\ \citep{zhu2020vision}\end{tabular} \\ \hline \begin{tabular}[c]{@{}l@{}}Require Ground-Truth\\ Reward function\end{tabular} & No & No & Yes & No & Yes & No (Yes if use RL fine-tuning) \\ \hline Goal Type & Natural Language & Natural Language & Natural Language & States & States & Natural Language \\ \hline Use Student-forcing & No & No & No & No & No & Yes \\ \hline \begin{tabular}[c]{@{}l@{}}Goals/Paths\\ Augmentation\end{tabular} & EGR, HGS, HGR & No & HER & HER & HER & \begin{tabular}[c]{@{}c@{}}All shortest-paths between any \\ two locations in environments\end{tabular} \\ \hline \end{tabular} } \caption{We compare our algorithm with closely related works that fall into $5$ different problem settings. In the setting we are interested in, the goals of the tasks are NL goals, and neither the ground-truth reward function (required by RL) nor the optimal action at any state (required by student-forcing) is available.} \label{tb:assumption_comparison} \end{table*} 2.\ \textbf{Hindsight goal relabeling and expert goal relabeling improve the generalization of the \emph{discriminator (reward function)}; such generalization is \emph{crucial} to the performance of the policy.} From Table \ref{tb:ablation} and Figure \ref{fig:res}(f), we see that if we take out HGR, the success rate drops significantly from $0.530$ to $0.444$. This shows that HGR plays a key role in learning a better reward function by enriching positive examples of the discriminator. Meanwhile, when applying HGS without HGR, the success rate drops from $0.503$ to $0.399$. This is because the discriminator cannot generalize well to sampled goals when HGR is not applied, which shows the importance of discriminator generalization. However, from Table \ref{tb:ablation} and Figure \ref{fig:res}(e) we can also see that if we only keep HGR, the success rate drops to $0.427$ which is even lower than LangGoalIRL\_BASE. We observe that in this case the goals generated by the variational goal generator only appear in the positive examples of the discriminator, so the discriminator easily identify these goals, and simply assigns high rewards to these goals regardless of what action is taken. When EGR and HGR are applied together, relabeled goals appear in both positive and negative examples, and the success rate improves from $0.427$ to $0.504$. 3.\ \textbf{Self-supervised learning largely improves performance in unseen environments.} Table \ref{tb:res} shows that with self-supervised learning, LangGoalIRL achieves a success rate of $0.491$, a $59.42\%$ improvement over LangGoalIRL\_BASE and a $37.54\%$ improvement over LangGoalIRL w/o self-supervised learning. This shows that the proposed self-supervised learning algorithm can significantly improve policy performance even though neither expert demonstrations nor NL\xspace goals in new environments are given. The number of trajectories sampled by the goal-agnostic policy $\pi_p$ in new environments by default is $15{,}000$. In Figure \ref{fig:res}(c), we show the performance of a baseline model where the embodied agent randomly explores the new environments (randomly selects an action at any states, but does not visit any visited viewpoints) rather than using $\pi_p$ to sample trajectories. We set the number of sampled trajectory to $15{,}000$ and $5{,}000$. We see that the agent performance drops during early stages, as randomly explored trajectories are not good seeds to bootstrap Algorithm \ref{algo:algo} in new environments. After early stages, the model performance gradually increases as HGR and HGS provide some self-supervised signals but the overall the performance remains lower than LangGoalIRL\xspace. More results are in Table \ref{tb:ss3} of Appendix \ref{appendix:addexp}. Finally, self-supervised learning can also be applied to existing environments by augmenting the expert demonstrations in seen validation set. While this is not our target setting, we include these results in Table \ref{tb:sstrain} of Appendix \ref{appendix:addexp}. 4.\ \textbf{Hindsight goal sampling improves the generalization of the policy by enabling the policy to explore a more diverse set of goals.} From Table \ref{tb:ablation} and Figure \ref{fig:res}(f) we can see that HGS further improves the policy performance from $0.504$ to $0.530$ on seen validation set. Figure \ref{fig:res}(d) shows the impact of HGS on self-supervised learning in new environments. The baseline, LangGoalIRL\_SS\_G2 samples goals only from $\bm{G}^1$ and $\bm{G}^2$ defined in Section \ref{sec:vgg} and does not iteratively sample goals from $\{(\bm{E}, \bm{G}^v)| v > 2\}$. As goals sampled are less diverse, we see that LangGoalIRL\_SS\_G2 performs worse than LangGoalIRL\_SS given $5{,}000$, $10{,}000$ and $15{,}000$ generated expert demonstrations in new environments. More experiments are in Table \ref{tb:ss3} of Appendix \ref{appendix:addexp}. \section{Related Works} \label{sec:related} Our paper focuses on proposing a sample efficient algorithm for IRL with natural language (NL\xspace) goals. Table \ref{tb:assumption_comparison} summarizes the differences between our LangGoalIRL algorithm and recent closely related works on goal-conditioned RL\xspace and imitation learning (IL). Goal-conditioned RL\xspace and IL have been explored by many prior works~\cite{schaul2015universal,florensa2017automatic,nair2018visual,plappert2018multi,ding2019goal}. Usually, the task is to learn a policy that is parameterized by a goal and can generalize to new goals. In most prior works, the goals and states are in a same space, such as positions in a Cartesian coordinate system~\cite{plappert2018multi,ding2019goal}. This corresponds to column $5$ and $6$ in Table \ref{tb:assumption_comparison}. However, in this paper we investigate a different setting where the goals are NL\xspace goals, which corresponds to column $3$ and $4$ in Table \ref{tb:assumption_comparison}. The closest prior works to our algorithm are language-conditioned IRL and reward learning~\cite{fu2019language,bahdanau2018learning,MacGlashan-RSS-15,williams2018learning,goyal2019natural}. \citet{goyal2019natural} propose to train a model to predict whether a language instruction describes an action in a trajectory, and use the predictions to perform reward shaping. \citet{bahdanau2018learning} propose to use GAN~\citep{goodfellow2014generative,ho2016generative} to learn a discriminator that predicts whether a state is the goal state of a NL\xspace instruction. \citet{fu2019language} propose to use the MaxEntIRL~\citep{ziebart2008maximum} framework to learn a language-conditioned reward function for instruction following tasks. The language instructions in \citet{bahdanau2018learning} and \citet{fu2019language}'s experiments are generated by templates and much easier to understand compared with our dataset. Meanwhile, LangGoalIRL\xspace demonstrates significantly better generalization than these two prior works. There are also many prior works on goal relabeling to improve sample efficiency, but none of them can be directly applied to the IRL with NL\xspace goals setting. \citet{andrychowicz2017hindsight} propose hindsight experience replay that samples additional goals for each transition in the replay buffer and can efficiently deal with the reward sparsity problem. \citet{nair2018visual} propose to sample additional diverse goals from a learned latent space. \citet{ding2019goal} propose to relabel trajectories using the states within the trajectories. These algorithms do not work with NL\xspace goals. \citet{cideron2019self} and \citet{jiang2019language} generalize HER to language setting and relabel trajectories by hindsight language instructions. However, in this paper we show that, when doing IRL, simply applying HER to policy optimization does not improve policy performance, and it is critical to improve the generalization of the reward function. Finally, there are multiple recent works~\citep{tan2019learning,wang2019reinforced,fried2018speaker,zhu2020vision} on R2R dataset that focus on solving vision-language navigation~\citep{anderson2018vision}. This corresponds to the last column in Table \ref{tb:assumption_comparison}. These works do not focus on sample efficient IRL algorithms and use student-forcing~\citep{anderson2018vision} to train their supervised learning models or pre-train their RL models. With student-forcing, the policy is assumed to always have access to the optimal action at any state it encounters during training, which is even a stronger assumption than knowing the ground-truth reward function. \citet{fried2018speaker} and \citet{tan2019learning} propose to learn a speaker model that back-translate a given trajectory to a NL\xspace goal, which is similar to our goal generator without latent variables. However, the purpose of the speaker model is to augment training data before the training, rather than relabeling goals during training. To augment training data, they generate the shortest path between any two viewpoints. This requires knowing the topological graph of viewpoints before the training. Moreover, they augment training set with every shortest path that is not included in the original training set. This assumes the environments can be exhaustively searched without sampling efficiency considerations. Other proposed techniques in these papers such as environment dropout~\citep{tan2019learning} and progress monitoring~\citep{zhu2020vision} are orthogonal to our work. For a survey of reinforcement learning with NL\xspace, please see \citet{luketina2019survey}. \section{Conclusion} In this work, we propose a sample efficient algorithm for IRL with NL\xspace goals. Observing limitations of existing works regarding language-conditioned IRL, LangGoalIRL\xspace emphasizes template-free NL\xspace goal specification and sample efficiency when generalizing to new goals and environments. Specifically, we propose learning a variational goal generator that can relabel trajectories and sample diverse goals. Based on this variational goal generator, we describe three strategies to improve the generalization and sample efficiency of the language-conditioned policy and reward function. Empirical results demonstrate that LangGoalIRL\xspace outperforms existing baselines by a large margin and generalizes well to new natural language goals and new environments, thus increasing flexibility of expression and domain transfer in providing instructions to autonomous agents.
{'timestamp': '2020-12-17T02:09:19', 'yymm': '2008', 'arxiv_id': '2008.06924', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06924'}
arxiv
\section{Introduction} \label{sec:intro} \label{sec:intro} The use of multiple-input multiple-output (MIMO) systems has been recognized as an efficient technology to meet the ever-increasing demand in spectral efficiency. It is indeed known since the early works of Telatar \cite{Tela99} and Foshini \cite{Fosc98} that the mutual information scales with the minimum of the number of transmit and receive antennas. In practice, however, the spectral efficiency of a wireless link depends not only on how many antennas are deployed at the transmit and receive sides but also on the channel estimation accuracy, the detection procedure as well as the distribution of the power resources, all of which have a direct bearing on the end-to-end signal-to-noise-ratio. At the receiver side, accurate channel estimation and symbol detection are crucial to reap the gains promised by the additional degrees of freedom offered by MIMO systems. Channel estimation is performed by allocating a training period during which the transmitter sends known \emph{pilot} symbols to the receiver for it to acquire an estimate of the channel state information (CSI). During the data transmission phase, this estimate is leveraged by the receiver to equalize the channel and recover the data symbols. It is worth mentioning that it is important for the success of the data recovery step to acquire accurate channel estimates because otherwise the error in the channel estimation would propagate to the symbol recovery, crippling the overall performance even under state-of-the-art detection strategies. Resource allocation in terms of power and time is also an essential part of the design of wireless systems. Increasing the duration of the transmitted pilot sequence would lead to enhanced channel estimation quality but at the cost of spectral efficiency losses since less time is spent to transmit useful data. Moreover, as the total power allocated to data and training transmission is fixed, we cannot increase the power allocated to data without affecting the channel accuracy estimation and vice versa. The problem of finding optimal power allocation between pilot and data has received a lot of attention over the last decades. It has been applied to different contexts with the aim of realizing various communication objectives. In \cite{hassibi2003much}, \cite{kannu2005capacity} and \cite{gottumukkala2009}, the authors proposed power designs that optimizes bounds on the average channel capacity. A different line of research works in \cite{simko2011, vsimko2012optimal, wang2011power, zhang2016energy} considered the post-equalization signal to interference and noise ratio as a target metric to determine the optimal power allocation. Depending on the application at hand, different other metrics such as the bit error rate (BER) \cite{wang2014ber,wang2009super}, the symbol error rate (SER) \cite{cai2004error}, mean squared error (MSE)-related indexes \cite{liu2016pilot,zhao2017game}, max-min fairness utilities \cite{van2018joint} or bounds on the received signal-to-noise ratio \cite{zhou2010two} have been used in several existing papers. Of interest in these works are a wide range of contexts including classical MIMO systems \cite{hassibi2003much}, mutli-carrier systems \cite{rottenberg2016generalized, xu2012energy, ma2003optimal, khosravi2014joint, chen2003pilot, montalban2013power}, amplify-and-forward relaying \cite{wang2014ber}, cognitive radio systems \cite{yu2016optimal} and very recently massive MIMO systems in both single-cell \cite{cheng2016optimal} and multi-user multi-cell settings \cite{van2018joint, dao2018pilot, ngo2014massive, liu2016pilot, guo2015energy}. Most of the aforementioned works, despite looking at the power allocation problem from different angles, present the common denominator of relying on linear receivers and optimizing some related performance metrics. To achieve optimal performance, it is well known that non-linear detectors are required, but they are often not implemented as they require a prohibitively high computation complexity. In this work, we consider optimization of the power allocation of a non-linear decoder coined Box-RLS decoder, the idea behind which has been proposed in \cite{atitallah2017ber,thrampoulidis2016ber} and earlier in \cite{tan2001constrained}. As explained in \cite{tan2001constrained}, this decoder is rooted in the formulation of the maximum-likelihood (ML) problem. At the one hand, the ML decoder is known to be NP-hard since its solution is constrained to belong to a finite discrete set, at the other hand, the Least Square (LS) decoder or its regularized version referred to as Regularized Least Squares (RLS) decoder \cite{tikhonov1963solution} are linear detectors, obtained by solving the unconstrained ML problem. The Box-RLS decoder falls between the ML and the RLS decoders in that the solution is constrained to lie within a closed convex-set. As a consequence, unlike the RLS decoder, the solution of the Box-RLS cannot be expressed in closed-form but is numerically computed using standard convex-optimization tools. Both the RLS and Box-RLS decoders are more computationally efficient than the ML decoder. Besides they are also shown to outperform many heuristic algorithms such as zero-forcing (ZF), successive interference cancellation and decision-feedback, \cite{atitallah2017ber, thrampoulidis2016ber, tan2001constrained}. Performance analysis of the Box-RLS has been carried out in \cite{atitallah2017ber}, \cite{thrampoulidis2016ber} but these studies assume unrealistic scenarios in which the channel is perfectly known and do not address the problem of power allocation. To fill this gap, this work addresses the problem of finding optimal power allocation between pilots and data for RLS and Box-RLS under a fixed total power constraint and when the channel is estimated using the linear minimum mean square error estimator (LMMSE). Particularly, we derive sharp characterization of the MSE and symbol error probability (SEP) for the RLS and Box-RLS decoders under $M$-ary pulse amplitude modulation ($M$-PAM) when assuming that the symbol is recovered by hard-thresholding the output of RLS and Box-RLS decoders. Our analysis, based on the assumption that the MIMO channel and the noise are independent and follow standard Gaussian distributions, builds upon the CGMT framework put forth in \cite{thrampoulidis2018precise, alrashdi2017precise,alrashdi2019precise}. As compared to previous works dealing with the use of CGMT in high-dimensional regression problems, our consideration of imperfect CSI poses technical challenges towards assessing the performance of the Box-RLS. Particularly, contrary to previous studies, the application of the CGMT in the asymptotic regime leads to a non-convex optimization problem; the uniqueness of its solution which is an important step in the analysis becomes thus extremely challenging. This required us to develop new techniques to break these difficulties, which while being accommodated to this specific scenario, may be of independent interest. We refer the interested reader to Appendix B devoted to the detailed proofs of our main results. To summarize, the main contributions of this work can be listed as follows: \begin{enumerate} \item We derive sharp characterizations of the MSE, SEP and goodput expressions for the RLS, LS and Box-RLS under imperfect CSI. Our expressions shed light on interesting relationships between MSE and SEP for $M$-PAM modulation and under imperfect CSI. \item We determine the optimal power allocation between training and data symbols when SEP or MSE are used as target criteria. \item We optimize the power and the number of pilot symbols to maximize the goodput for all studied decoders. \end{enumerate} To the best of our knowledge, none of the above was previously derived for the $M$-PAM case in the presence of imperfect CSI. \subsection{Paper Organization} This paper is organized as follows. The system model is presented in Section II. In Section III, we discuss channel estimation, the properties of the estimator and the channel estimation error, as well as symbol estimation. The MSE/SEP of symbol estimation is derived in Section IV by applying the CGMT. These expressions are then validated through an assortment of numerical results and leveraged to find optimal power strategies in Section V. The key ingredient of the analysis which is the CGMT is reviewed in Appendix A. The proofs for the derived MSE and SEP are presented in Appendix B and Appendix C for the Boxed RLS and un-boxed RLS, respectively. \subsection{Notations} Scalars are denoted by lower-case letters (e.g., $\alpha$), column vectors are represented by boldface lowercase letters (e.g., ${\bf x}$), whereas matrices are denoted by boldface upper-case letters (e.g., ${\bf X}$). The notations $(\cdot)^T$ and $(\cdot)^{-1}$ denote the transpose and inversion operators, respectively. The $j$-th element of vector ${\bf x}$ will be denoted by ${x}_j$. The symbol ${\bf I}_N$ is used to represent the identity matrix of dimension $N \times N$. We use the standard notation $\mathbb{P}[\cdot]$ and $\mathbb{E}[\cdot]$ to denote probability and expectation. We write $X \thicksim p_X$ to denote that a random variable $X$ has a probability density function (pdf) $p_X$. In particular, $G \thicksim \mathcal{N}(\mu, \sigma^2)$ implies that $G$ has a Gaussian (normal) distribution of mean $\mu$ and variance $\sigma^2$. $p(x)= \frac{1}{\sqrt{2 \pi}} e^{\frac{-x^2}{2}}$ and $Q(x) = \frac{1}{\sqrt{2\pi}}\int_{x}^{\infty} e^{-t^2/2} {\rm{d}} t$ denote the pdf of a standard normal distribution and its associated $Q$-function respectively. Finally, $\| \cdot \|$ indicates the Euclidean norm (i.e., the $\ell_2$-norm) of a vector and $\| \cdot \|_\infty$ represents its $\ell_\infty$-norm.\footnote{For a vector ${\bf x}$, $\| {\bf x} \|_\infty = \max_{j} | x_j|$.} \begin{table}[ht] \centering \caption{Summary of Main Variables} \begin{tabular}{|l|l|} \hline \textbf{Symbol} & \quad \quad \quad \quad \textbf{Meaning} \\ \hline $T_\mathsmaller{p}$ & number of pilot symbols \\ \hline $T_\mathsmaller{d}$ & number of data symbols \\ \hline $T$ & total number of symbols \\ \hline $M$ & size of the PAM signal \\ \hline $ \mathcal{E}$ & average power of non-normalized $M$-PAM signal \\ \hline $\rho_\mathsmaller{p}$ & average training power \\ \hline $\rho_\mathsmaller{d}$ & average data power \\ \hline $\rho$ & average received power per receive antenna \\ \hline $\rho_\text{eff}$ & effective SNR \\ \hline $\alpha$ & data power ratio \\ \hline $K$ & Number of transmit (Tx) antennas \\ \hline $N$ & Number of receive (Rx) antennas\\ \hline $\delta$ & ratio of Rx to Tx antennas $N/K$ \\ \hline $ \lambda$ & regularization coefficient \\ \hline $t$ & box-constraint threshold \\ \hline $ {\bf H}$ & channel matrix \\ \hline {{$ \widehat{{\bf H}}$}} & estimated channel matrix \\ \hline $ \hbox{\boldmath$\Delta$}$ & channel estimation error matrix \\ \hline $\sigma_{\mathsmaller{\Delta}}^2$ & variance of error matrix \\ \hline $\sigma_{\mathsmaller{\hat{H}}}^2$ & variance of estimated channel matrix \\ \hline ${\bf X}_\mathsmaller{p}$ & pilot symbols matrix\\ \hline ${\bf x}_{0}$ & transmitted data symbol vector \\ \hline $\widehat{{\bf x}}$ & estimated data symbol vector \\ \hline ${\bf y}$ & received data symbol vector \\ \hline ${\bf z}$ & noise vector \\ \hline \end{tabular} \label{tab:1} \end{table} \section{System Model} \label{sec:model} We consider a flat block-fading massive MIMO system with $K$ transmitter antennas and $N$ receiver antennas. The transmission consists of $T$ symbols that occur in a time interval within which the channel is assumed to be static. A number $T_\mathsmaller{p}$ pilot symbols (for channel estimation) occupy the first part of the transmission interval with power, $\rho_\mathsmaller{p}$. The remaining part is devoted for transmitting $T_\mathsmaller{d}= T - T_\mathsmaller{p}$ data symbols with power, $\rho_{\mathsmaller{d}}$. Figure \ref{fig:channels} illustrates the system model. It implies from conservation of time and energy that: \begin{equation} \label{eq:energy conseve} \rho_\mathsmaller{p} T_\mathsmaller{p} + \rho_{\mathsmaller{d}} T_\mathsmaller{d}= \rho T, \end{equation} where $\rho$ is the expected average power. Alternatively, we have $ \rho_\mathsmaller{d} T_\mathsmaller{d} = \alpha \rho T$, where $\alpha \in (0,1)$ is the ratio of the power allocated to the data so that \begin{equation} \label{eq:data power} \rho_\mathsmaller{p} T_\mathsmaller{p} = (1- \alpha) \rho T. \end{equation} The received signal model for the \emph{data} transmission phase is given by \begin{equation} \label{eq:data model} {\bf y} = \sqrt{\frac{\rho_\mathsmaller{d}}{K}} {\bf H} {\bf x}_{0}+ {\bf z}, \end{equation} where ${\bf y} \in \mathbb{R}^{N}$ is the received data symbol vector, ${\bf x}_0 \in \mathbb{R}^{K}$ is the transmitted data symbol vector, ${\bf H}\in \mathbb{R}^{N\times K}$ is a channel matrix with i.i.d. Gaussian elements $h_{ij}\thicksim \mathcal{N}\left(0, 1\right)$, and ${\bf z} \in \mathbb{R}^{N}$ stands for the additive Gaussian noise at the receiver with i.i.d. elements of mean $0$ and variance 1. It is assumed that ${\bf x}_0$ has i.i.d. $M$-PAM symbols normalized to have unit variance ($\mathbb{E}[{\bf x}_0 {\bf x}_0^T] = {\bf I}_K$), such that each transmit antenna sends a data symbol $x_{0,j}$ that takes values (with equal probability $1/M$) in the set: \begin{equation} x_{0,j} \in \mathcal{C}:= \bigg\{\pm\frac{1}{\sqrt{\mathcal{E}}}, \pm\frac{3}{\sqrt{\mathcal{E}}}, \cdots, \pm\frac{(M-1)}{\sqrt{\mathcal{E}}} \bigg\}, j=1,2,\cdots,K, \end{equation} {{where $\mathcal{E} = \frac{M^2-1}{3}$ is the average power of the non-normalized $M$-PAM signal}}, $M=2^{b}$ being the modulation order and $b$ the number of bits carried by each symbol As the channel matrix ${\bf H}$ is unknown to the receiver, a training phase during which the transmitter sends $T_{\mathsmaller{p}} \geq K$ \emph{pilot} symbols is dedicated. The received signals corresponding to this phase can be modeled as \begin{equation} \label{eq:pilot model} {\bf Y}_\mathsmaller{p} = \sqrt{\frac{\rho_\mathsmaller{p}}{K}} {\bf H} {\bf X}_\mathsmaller{p} + {\bf Z}_\mathsmaller{p}, \end{equation} where ${\bf Y}_\mathsmaller{p}\in \mathbb{R}^{N \times T_\mathsmaller{p}}$ is the received signal matrix, ${\bf X}_\mathsmaller{p}\in \mathbb{R}^{K \times T_\mathsmaller{p}}$ is the matrix of transmitted pilot symbols, and ${\bf Z}_\mathsmaller{p}\in \mathbb{R}^{N \times T_\mathsmaller{p}}$ stands for the additive Gaussian noise with $\mathbb{E}[{\bf Z}_{\mathsmaller{p}} {\bf Z}_{\mathsmaller{p}}^T] =T_{\mathsmaller{p}} {\bf I}_N$. For the reader convenience, we summarize in Table \ref{tab:1} the notation symbols of the parameters used in this paper. \begin{figure} \begin{center} \includegraphics[width=9.0cm]{aa4.png} \caption{\scriptsize{Massive MIMO system with training-based transmission.}} \label{fig:channels} \end{center} \end{figure} \section{MIMO Symbols Detection under LMMSE Channel Estimation} \label{sec:ch estimate} \subsection{LMMSE Channel Estimation} Based on the knowledge of ${\bf Y}_\mathsmaller{p}$ from \eqref{eq:pilot model}, the LMMSE channel estimate is given by \cite{kay1993fundamentals} \begin{align} \label{eq:LMMSE} \widehat{{\bf H}} &= \sqrt{\frac{K}{\rho_\mathsmaller{p}}}{\bf Y}_\mathsmaller{p} {\bf X}_{\mathsmaller{p}}^T \left( \frac{K}{\rho_\mathsmaller{p}} {\bf I}_\mathsmaller{K}+ {\bf X}_{\mathsmaller{p}} {\bf X}_{\mathsmaller{p}}^T \right)^{-1},\nonumber \\ & = {\bf H} - \hbox{\boldmath$\Delta$}, \end{align} where $\hbox{\boldmath$\Delta$}$ is the zero-mean channel estimation error matrix, which is independent of $\widehat{{\bf H}}$, as per the orthogonality principle of the LMMSE estimation \cite{hassibi2003much}, \cite{kay1993fundamentals}. For MIMO channels with i.i.d. entries, it has been proved that the optimal ${\bf X}_\mathsmaller{p}$ that minimizes the estimation mean squared error under a total power constraint satifies \cite{hassibi2003much} \begin{equation} \label{eq:pilot orthogonality} {\bf X}_\mathsmaller{p} {\bf X}_{\mathsmaller{p}}^{T}= T_\mathsmaller{p}{\bf I}_\mathsmaller{K}. \end{equation} For the above condition to hold, the number of training symbols should be greater than or equal to $K$. Moreover, under \eqref{eq:pilot orthogonality}, the channel estimate $\widehat{{\bf H}}$ has i.i.d. zero-mean Gaussian entries with mean $0$ and variance $\sigma_{\mathsmaller{\hat{H}}}^2 = 1-\sigma_{\mathsmaller{\Delta}}^2$ \cite{hassibi2003much}, with \begin{equation} \label{eq:error matrix variance} \sigma_{\mathsmaller{\Delta}}^2 = \frac{1}{ 1+ \frac{\rho_\mathsmaller{p}}{K} T_\mathsmaller{p} }, \end{equation} being the variance of each element in $\hbox{\boldmath$\Delta$}$. It appears from \eqref{eq:error matrix variance} that channel estimation error decreases with the pilot energy given by $ \rho_\mathsmaller{p} T_\mathsmaller{p}$. \subsection{Symbol Detection under Imperfect Channel Estimation} With the channel estimate $\widehat{{\bf H}}$ at hand, the receiver can proceed to the recovery of the transmitted symbols. The optimal decoder which minimizes the probability of error is the maximum likelihood (ML) decoder under perfect channel knowledge which is given by: \begin{equation} \widehat{{\bf x}}_{\text{\tiny{ML}}} = \underset{{{\bf x} \in \mathcal{C}^{\mathsmaller{K}}}}{\argmin} \big\| {\bf y} -\sqrt{\frac{\rho_\mathsmaller{d}}{K}} {\bf H} {\bf x} \big\|^2. \label{eq:ML} \end{equation} As can be seen, the ML decoder involves a combinatorial optimization problem. It presents thus a prohibitively high computational complexity, especially when the system dimensions become large as envisioned by current communication systems. To overcome this issue, suboptimal strategies that require less computational complexity are in general used. They often proceed in two steps. First, a real-valued approximation of the transmitted symbol is obtained. This estimate is then hard-thresholded in a second step to produce the final estimate. In this work, the focus is on the regularized least squares (RLS) and the Box-regularized least squares (Box-RLS) decoders. The RLS decoder is based on regularizing the cost in \eqref{eq:ML} and relaxing the finite-alphabet constraint, thus leading to: \begin{subequations} \begin{align}\label{eq:LS matrix} \widehat{{\bf x}} &= \argmin_{{\bf x} \in \mathbb{R}^{\mathsmaller{K}}}\| {\bf y} - \sqrt{\frac{\rho_\mathsmaller{d}}{K}} \widehat{{\bf H}} {\bf x} \|^2 + \lambda \rho_\mathsmaller{d}\| {\bf x} \|^2, \\ &= ({\bf A}^T {\bf A} + {\lambda} \rho_\mathsmaller{d} {\bf I}_\mathsmaller{K})^{-1} {\bf A}^T {\bf y},\label{eq:LS matrixb}\\ {x}_j^* &= \argmin_{s \in \mathcal{C}} \bigg| \frac{\widehat{x}_j}{B} -s \bigg|, j=1,2,\cdots,K,\label{eq:LS matrixc} \end{align} \end{subequations} where $\lambda \geq 0$ is the regularization coefficient, ${\bf A}= \sqrt{\frac{\rho_\mathsmaller{d}}{K}} \widehat{{\bf H}}$ and $B$ is a normalization constant, the value of which will be suggested from our analysis so as to remove the bias of the decoder \cite{practical_guide} \footnote{It follows from our analysis that $\widehat{x}_j$ behaves as $B {x}_{0,j}$ plus some independent Gaussian noise where $B$ is some constant depending on the regularization factor, the data and channel estimation powers. It is thus sensible to divide $\widehat{x}_{j}$ by $B$ to remove the induced bias.}. Note that the optimization in \eqref{eq:LS matrixc} simply selects the symbol value $s$ that is closest to the solution $\frac{\widehat{ x}_j}{B}$ among a total of $M$ possible choices. As can be seen from \eqref{eq:LS matrixb}, the elements of the solution $\widehat{{\bf x}}$ may take large values in high-noise conditions or poor channel estimation scenarios. This motivates the Box-RLS decoder \cite{yener2002cdma, tan2001constrained, ma2002quasi} given b \begin{subequations} \begin{align}\label{eq:Box-RLS matrix} \widehat{{\bf x}} &= \argmin_{\|{\bf x}\|_{\infty}\leq t} \|{\bf y} - \sqrt{\frac{\rho_\mathsmaller{d}}{K}} \widehat{{\bf H}} {\bf x} \|^2 + \lambda \rho_\mathsmaller{d}\| {\bf x}\|^2, \\ & { x}_j^* = \argmin_{s \in \mathcal{C}} \bigg|\frac{\widehat{x}_j}{B} -s \bigg|, j=1,2,\cdots,K,\label{eq:BLS matrixb} \end{align} \end{subequations} which is based on relaxing the finite-alphabet constraint to the convex constraint ${\bf x} \in [-t,t]^K$, where $t$ is a fixed threshold that can be optimally tailored according to the propagation scenario. \subsection{Performance Metrics} This work considers the performance evaluation of the RLS and the Box-RLS decoders in terms of three different performance metrics, which are: \noindent\textbf{Mean Squared Error}: A natural and heavily used measure of performance is the reconstruction \textit{mean squared error} (MSE), which measures the deviation of $\widehat{{\bf x}}$ from the true signal ${\bf x}_0$. This assesses the performance of the \textit{first} step of the decoding algorithms. Formally, the MSE is defined as \begin{equation} {\rm{MSE}} := \frac{1}{K}\| \widehat{{\bf x}} - {\bf x}_0\|^2. \end{equation} \textbf{Symbol Error Probability}: The symbol error rate (SER) characterizes the performance of the detection process and is defined as: \begin{equation} {\rm{SER}} := \frac{1}{K} \sum_{j=1}^{K} {\bf 1}_{\{{x}^*_j \neq x_{0,j} \}}, \end{equation} where ${\bf 1}_{\{\cdot\}}$ indicates the indicator function.\\ In relation to the SER is the symbol error probability (SEP) which is defined as the expectation of the SER averaged over the noise, the channel and the constellation. Formally, the symbol error probability denoted by ${\rm SEP}$ is given by: \begin{equation} {\rm SEP}:=\mathbb{E}[{\rm SER}] =\frac{1}{K}\sum_{j=1}^K \mathbb{P}\left[{x}^*_j \neq x_{0,j} \right]. \label{eq:SEP} \end{equation} \textbf{Goodput}: The goodput is a performance measure that accounts for the amount of useful data transmitted, divided by the time it takes to \textit{successfully} transmit it. The amount of data considered excludes protocol overhead bits as well as retransmitted data packets \cite{grote2008ieee}. In our context, it can be defined as \begin{equation}\label{good_def} G := \left( \frac{T -T_\mathsmaller{p}}{T}\right) \left(1- {\rm SEP} \right). \end{equation} Goodput and throughput are connected performance parameters in that the throughput can be obtained by simply dividing the goodput by the data transmission rate. \section{Analysis of the Mean Squared Error (MSE) and Symbol-Error Probability (SEP)} \label{sec:BER} In this section, we derive asymptotic expressions of the MSE and SEP for the RLS and Box-RLS decoders. Particularly, we show that these metrics can be approximated by deterministic quantities that involve the power and time devoted for data and training transmissions. Our analysis builds upon the CGMT framework. For the RLS decoder, the same results could have been obtained using tools from random matrix theory as the decoder possesses a closed-form expression. However, since the use of the CGMT framework is more adapted to the Box-RLS decoder that cannot be expressed in closed-form, we rely in this work on the CGMT framework for both decoders for the sake of a unified presentation. Prior to stating our main results, we shall introduce the following assumptions which describe the considered growth rate regime: \subsection{Technical Assumptions} \begin{assumption} We consider the asymptotic regime in which the system dimensions $K$ and $N$ grow simultaneously to infinity at a fixed ratio $$\delta :=\frac{N}{K} \in (0,\infty).$$ \end{assumption} \begin{assumption} We assume a fixed normalized coherence interval $$\tau:= \frac{T}{K}\in (1,\infty).$$ and that the pilot and data symbols grow proportionally with $K$, where: $$\tau_{\mathsmaller{p}} :=\frac{T_{\mathsmaller{p}}}{K} \in [1,\infty),$$ and $$\tau_{\mathsmaller{d}} :=\frac{T_{\mathsmaller{d}}}{K},$$ are fixed and denote the normalized number of pilot and data symbols, respectively. \end{assumption} In the sequel, we leverage the statistical distribution of the channel and the channel estimate as well as the asymptotic regime specified in Assumption 1 and 2 to provide asymptotic approximations of the MSE and SEP for RLS and Box-RLS. We use the standard notation ${\rm{plim}}_{n\to\infty}\ X_n = X$ to denote that a sequence of random variables $X_n$ converges in probability towards a constant $X$. \subsection{MSE and SEP Analysis for RLS} We provide herein asymptotic approximations of the MSE and SEP for RLS under imperfect channel state information. The derived closed form expressions are given in Theorem \ref{MSE-RLS}, and Theorem \ref{SER-RLS} while the proof is given in Appendix~\ref{sec:unbox}. \begin{theorem}(MSE for RLS): \label{MSE-RLS} \normalfont Fix $\lambda>0$, $\delta>0$, and let $\widehat{{\bf x}}$ be a minimizer of the RLS problem in (\ref{eq:LS matrix}). Define \begin{equation*} \Upsilon(\lambda,\delta)=\frac{-(\delta-\frac{\lambda}{ \sigma_{\mathsmaller{\hat{H}}}^2}-1)+\sqrt{(\delta-\frac{\lambda}{ \sigma_{\mathsmaller{\hat{H}}}^2}-1)^2+4\frac{\lambda}{\sigma_{\mathsmaller{\hat{H}}}^2}\delta}}{2\delta}, \end{equation*} \label{th:MSE_RLS} and \begin{equation*} \theta_\star = \sqrt{\frac{\rho_\mathsmaller{d} \sigma_{\mathsmaller{\hat{H}}}^2 \left(\frac{\Upsilon(\lambda,\delta)}{1+\Upsilon(\lambda,\delta)}\right)^2+ \rho_\mathsmaller{d} \sigma_{\mathsmaller{\Delta}}^2 +1 }{\delta-\frac{1}{(1+\Upsilon(\lambda,\delta))^2}}}. \end{equation*} Then, under Assumption 1 and Assumption 2, it holds: \begin{equation}\label{RLS-MSE} \underset{K\to\infty}{{\rm{plim}}} {\rm{ MSE}} = \frac{1}{\rho_\mathsmaller{d} \sigma_{\mathsmaller{\hat{H}}}^2} \biggl(\delta \theta_{\star}^2 - \rho_\mathsmaller{d} \sigma_{\mathsmaller{\Delta}}^2 -1 \biggr), \end{equation} \label{th:MSE_RLS} \end{theorem} \begin{proof} The proof of Theorem \ref{MSE-RLS} is given in Appendix~\ref{sec:unbox}. \end{proof} It is worth mentioning that the above formula is not restricted to ${\bf x}_0$ belonging to $M$-PAM constellation and is valid for ${\bf x}_0$ from any distribution provided that ${\bf x}_0$ is normalized to have unit-variance. However, assuming that ${\bf x}_0$ is drawn from $M$-PAM constellations, the SEP can be approximated as: \begin{theorem}(SEP of RLS):\label{SER-RLS} \normalfont Under the same setting of Theorem~\ref{MSE-RLS}, the SEP under $M$-PAM modulation of the RLS decoder employing the normalization constant $$ B=\frac{\sigma_{\mathsmaller{\hat{H}}}^2\frac{\beta_\star}{\theta_\star}}{\sigma_{\mathsmaller{\hat{H}}}^2\frac{\beta_\star}{\theta_\star}+2\lambda}, $$ with $\beta_\star=\frac{2\lambda\theta_\star}{\sigma_{\mathsmaller{\hat{H}}}^2\Upsilon(\lambda,\delta)}$, converges to: \begin{align}\label{SER-RLS1} &\underset{K\to\infty}{{\rm{plim}}} {\rm{SEP}} = \widetilde{\rm {SEP}}_{\rm RLS}, \end{align} where \begin{align} \widetilde{\rm {SEP}}_{\rm RLS}=2\bigg(1- \frac{1}{M}\bigg) Q \biggl( \frac{\sqrt{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2}}{\sqrt{\mathcal{E}}\theta_\star} \biggr). \end{align} where $\theta_\star$ is defined in Theorem \ref{MSE-RLS}. \label{th:SER_RLS} \end{theorem} \begin{proof} A sketch of the proof is provided in Appendix \ref{sec:unbox}. \end{proof} Before proceeding further, we validate the approximations provided in Theorem \ref{th:MSE_RLS} and Theorem \ref{th:SER_RLS}. To this end, we report in Figure \ref{xz2} and \ref{fig221} the MSE and SEP for the RLS decoder when $K=400, \delta=1.2, T_\mathsmaller{p} = 456, T=1000$, $\alpha = 0.5$ and $M=2$ (corresponding to Binary Phase Shift Keying (BPSK) modulation), as a function of the average power $\rho$. As seen, the simulation results, averaged over 500 realizations of the channel, show a perfect agreement with the theoretical results. \begin{figure} \begin{center} \input{MSE_all2.tex} \caption{\scriptsize {MSE performance of both RLS and Box-RLS decoders.}}% \label{xz2} \end{center} \end{figure} \begin{figure} \begin{center} \definecolor{OliveGreen}{rgb}{0.,0.5,0}% \begin{tikzpicture} \renewcommand{\axisdefaulttryminticks}{4} \tikzstyle{every major grid}+=[style=densely dashed] \tikzstyle{every axis y label}+=[yshift=-10pt] \tikzstyle{every axis x label}+=[yshift=5pt] \tikzstyle{every axis legend}+=[cells={anchor=west},fill=white, at={(0.01,0.01)}, anchor=south west, font=\tiny ] \begin{semilogyaxis}[ xmin=0, xmax=35, xlabel={$\rho$ (dB)}, ymin=1e-08, ymax=1, grid=major, scaled ticks=true, ylabel={$\rm SEP$}, ] \addplot [color=blue, dashed, line width=1.0pt] table[row sep=crcr]{% 0 0.350459340292567\\ 1 0.327764311848152\\ 2 0.303926176211485\\ 3 0.279320706337796\\ 4 0.254314158316087\\ 5 0.229242888725249\\ 6 0.204406786760934\\ 7 0.180073309514013\\ 8 0.15648712837236\\ 9 0.133880765103076\\ 10 0.112482833893392\\ 11 0.0925217103150944\\ 12 0.0742233021576124\\ 13 0.0578021802676642\\ 14 0.0434459087685994\\ 15 0.0312933201890589\\ 16 0.0214089981539884\\ 17 0.0137584510384389\\ 18 0.00819101549419987\\ 19 0.00443925225095467\\ 20 0.00214242164474999\\ 21 0.000895369378812596\\ 22 0.000312783009952526\\ 23 8.73276360949533e-05\\ 24 1.84089840021163e-05\\ 25 2.72630922944329e-06\\ 26 2.58913272686158e-07\\ 27 1.4049048537798e-08\\ 28 3.76485824561519e-10\\ 29 4.14564850454516e-12\\ 30 1.48766661366215e-14\\ 31 1.29918691063005e-17\\ 32 1.91165053296695e-21\\ 33 2.98331362174482e-26\\ 34 2.75751521374633e-32\\ 35 7.2508171277502e-40\\ }; \addlegendentry{Theory: RLS} \addplot [color=red, line width=1.0pt] table[row sep=crcr]{% 0 0.350457294241988\\ 1 0.327753869309766\\ 2 0.303887706964755\\ 3 0.279208559407752\\ 4 0.254039230640741\\ 5 0.228652819430034\\ 6 0.203267789562573\\ 7 0.178060056621547\\ 8 0.153189736493996\\ 9 0.128840221301295\\ 10 0.105266338996575\\ 11 0.08284346209772\\ 12 0.0620987274007333\\ 13 0.0436925267371205\\ 14 0.0283163162140137\\ 15 0.0164998657742636\\ 16 0.00838245060260327\\ 17 0.00357064911454958\\ 18 0.00121384188672377\\ 19 0.000309424762544297\\ 20 5.46775883898135e-05\\ 21 6.06616166277274e-06\\ 22 3.72931776763772e-07\\ 23 1.08526141113352e-08\\ 24 1.22546152720128e-10\\ 25 4.17823828367716e-13\\ 26 3.13450117928608e-16\\ 27 3.47074559128233e-20\\ 28 3.427905354052e-25\\ 29 1.6000686196605e-31\\ 30 1.58464101983168e-39\\ 31 1.21313235359248e-49\\ 32 2.01068942655409e-62\\ 33 1.45087587121845e-78\\ 34 6.03839370290781e-99\\ 35 1.13531914618792e-124\\ }; \addlegendentry{Theory: Box-RLS} \addplot [only marks, line width =1pt, mark size=1.5pt, mark=o, mark options={solid, OliveGreen}] table[row sep=crcr]{% 0 0.35029\\ 1 0.329365\\ 2 0.304495\\ 3 0.279165\\ 4 0.254035\\ 5 0.228675\\ 6 0.204945\\ 7 0.1804\\ 8 0.156435\\ 9 0.133495\\ 10 0.11249\\ 11 0.092495\\ 12 0.07419\\ 13 0.0587350000000001\\ 14 0.044275\\ 15 0.03324\\ 16 0.022035\\ 17 0.01348\\ 18 0.00859999999999996\\ 19 0.00450999999999997\\ 20 0.00217999999999999\\ 21 0.001145\\ 22 0.000415\\ 23 0.000115\\ 24 1e-05\\ 25 5e-06\\ 26 0\\ 27 0\\ 28 0\\ 29 0\\ 30 0\\ 31 0\\ 32 0\\ 33 0\\ 34 0\\ 35 0\\ }; \addlegendentry{Simulation: RLS} \addplot [only marks, line width =1pt,mark size=1.2pt,mark=square, mark options={solid, black}] table[row sep=crcr]{% 0 0.34829\\ 1 0.32627\\ 2 0.303635\\ 3 0.27983\\ 4 0.25391\\ 5 0.228285\\ 6 0.20187\\ 7 0.176435\\ 8 0.153285\\ 9 0.130705\\ 10 0.10746\\ 11 0.08269\\ 12 0.062785\\ 13 0.043285\\ 14 0.028045\\ 15 0.016865\\ 16 0.00917499999999997\\ 17 0.00385499999999997\\ 18 0.0014\\ 19 0.000315\\ 20 0.0001\\ 21 5e-06\\ 22 0\\ 23 0\\ 24 0\\ 25 0\\ 26 0\\ 27 0\\ 28 0\\ 29 0\\ 30 0\\ 31 0\\ 32 0\\ 33 0\\ 34 0\\ 35 0\\ }; \addlegendentry{Simulation: Box-RLS} \addplot [color=red, line width=1.0pt, forget plot] table[row sep=crcr]{% 0 0.711253484048703\\ 1 0.699586152608233\\ 2 0.684194241923735\\ 3 0.665403607486198\\ 4 0.64380420939113\\ 5 0.619989082397616\\ 6 0.594431502722788\\ 7 0.567456173242119\\ 8 0.539253203928065\\ 9 0.509905654983553\\ 10 0.479418518895088\\ 11 0.447745860428822\\ 12 0.414816677914106\\ 13 0.380561547333089\\ 14 0.344942741954312\\ 15 0.307991150743048\\ 16 0.269854274186925\\ 17 0.230859692545542\\ 18 0.191593448717738\\ 19 0.152975987179971\\ 20 0.116288181974942\\ 21 0.0830759900420946\\ 22 0.0548855129461526\\ 23 0.0328681141245825\\ 24 0.0173970488830062\\ 25 0.00788370017741921\\ 26 0.00293811162958705\\ 27 0.000855912780302872\\ 28 0.000182791493980562\\ 29 2.63918324912536e-05\\ 30 2.32571139485218e-06\\ 31 1.09939941030772e-07\\ 32 2.36883399824932e-09\\ 33 1.89440157570858e-11\\ 34 4.33970489021406e-14\\ 35 2.05429471551232e-17\\ }; \addplot [only marks, line width =1pt,mark size=1.2pt,mark=square, mark options={solid, black}, forget plot] table[row sep=crcr]{% 0 0.713095\\ 1 0.700564999999999\\ 2 0.685090000000001\\ 3 0.663655\\ 4 0.64351\\ 5 0.61872\\ 6 0.59371\\ 7 0.566244999999999\\ 8 0.539895\\ 9 0.50927\\ 10 0.478585\\ 11 0.44592\\ 12 0.414390000000001\\ 13 0.38022\\ 14 0.34742\\ 15 0.306595\\ 16 0.27048\\ 17 0.233195\\ 18 0.193285\\ 19 0.15074\\ 20 0.11712\\ 21 0.08325\\ 22 0.05689\\ 23 0.033485\\ 24 0.018745\\ 25 0.00813499999999997\\ 26 0.00341499999999998\\ 27 0.00107\\ 28 0.00026\\ 29 6.5e-05\\ 30 5e-06\\ 31 0\\ 32 0\\ 33 0\\ 34 0\\ 35 0\\ }; \addplot [color=blue, dashed, line width=1.0pt, forget plot] table[row sep=crcr]{% 0 0.711253924048519\\ 1 0.699591479103027\\ 2 0.684226136323834\\ 3 0.665522151352639\\ 4 0.644122242583016\\ 5 0.620670282741894\\ 6 0.59567845637359\\ 7 0.569500002679421\\ 8 0.542351369380446\\ 9 0.51434830732354\\ 10 0.485540284863718\\ 11 0.455938763226462\\ 12 0.425539662428557\\ 13 0.394341881735279\\ 14 0.362363919102911\\ 15 0.329660332960631\\ 16 0.296339302277958\\ 17 0.262581873203749\\ 18 0.228662489830488\\ 19 0.194968876508967\\ 20 0.162017069633976\\ 21 0.130454388200832\\ 22 0.101039936472539\\ 23 0.0745904697728985\\ 24 0.0518822443133251\\ 25 0.0335109857886377\\ 26 0.0197348904292777\\ 27 0.0103547023768895\\ 28 0.00470180553535449\\ 29 0.0017811494572203\\ 30 0.000537518182497747\\ 31 0.000121922198230349\\ 32 1.93174416766044e-05\\ 33 1.94945927541291e-06\\ 34 1.11556932947844e-07\\ 35 3.12695901256859e-09\\ }; \addplot [only marks, line width =1pt, mark size=1.5pt, mark=o, mark options={solid, OliveGreen}, forget plot] table[row sep=crcr]{% 0 0.710835\\ 1 0.699545\\ 2 0.682605\\ 3 0.6664\\ 4 0.64303\\ 5 0.62046\\ 6 0.59462\\ 7 0.570305\\ 8 0.53977\\ 9 0.51497\\ 10 0.48589\\ 11 0.45662\\ 12 0.42586\\ 13 0.39182\\ 14 0.363355\\ 15 0.32811\\ 16 0.296835\\ 17 0.26537\\ 18 0.229275\\ 19 0.195645\\ 20 0.16357\\ 21 0.13141\\ 22 0.10251\\ 23 0.075945\\ 24 0.05345\\ 25 0.034135\\ 26 0.021585\\ 27 0.011185\\ 28 0.00540499999999997\\ 29 0.00211499999999999\\ 30 0.000715\\ 31 0.000175\\ 32 4e-05\\ 33 1e-05\\ 34 0\\ 35 0\\ }; \addplot [color=red, line width=1.0pt, forget plot] table[row sep=crcr]{% 0 0.856560776522316\\ 1 0.850133914691904\\ 2 0.842154681233208\\ 3 0.832552638443874\\ 4 0.821367596201006\\ 5 0.808719061693533\\ 6 0.794752906007021\\ 7 0.77959728627331\\ 8 0.763338251523865\\ 9 0.746011163400331\\ 10 0.727601046573941\\ 11 0.708046785737042\\ 12 0.687246486827392\\ 13 0.665063042317415\\ 14 0.641329954218627\\ 15 0.615858022031592\\ 16 0.588443805120912\\ 17 0.55888093272155\\ 18 0.526975388185607\\ 19 0.492565801741042\\ 20 0.455549495149654\\ 21 0.415914645772482\\ 22 0.373779166115683\\ 23 0.329438883102927\\ 24 0.283430315129813\\ 25 0.236609119050697\\ 26 0.190222537502513\\ 27 0.145915433224433\\ 28 0.105590134886961\\ 29 0.0710877716827082\\ 30 0.0437630656502699\\ 31 0.0241037388312149\\ 32 0.0115533331425682\\ 33 0.00465331448729876\\ 34 0.00150670595908694\\ 35 0.000370887903393403\\ }; \addplot [only marks, line width =1pt,mark size=1.2pt,mark=square, mark options={solid, black}, forget plot] table[row sep=crcr]{% 0 0.856510000000002\\ 1 0.849320000000001\\ 2 0.844285\\ 3 0.832799999999999\\ 4 0.820784999999999\\ 5 0.808029999999999\\ 6 0.794555000000001\\ 7 0.77926\\ 8 0.763515\\ 9 0.746525\\ 10 0.727165000000001\\ 11 0.7068\\ 12 0.68862\\ 13 0.66251\\ 14 0.641995\\ 15 0.617685\\ 16 0.58951\\ 17 0.557095\\ 18 0.52677\\ 19 0.491905\\ 20 0.454865\\ 21 0.41631\\ 22 0.3762\\ 23 0.329715\\ 24 0.284344999999999\\ 25 0.2367\\ 26 0.190945\\ 27 0.146995\\ 28 0.10251\\ 29 0.072645\\ 30 0.045095\\ 31 0.02587\\ 32 0.012415\\ 33 0.00526499999999997\\ 34 0.00207999999999999\\ 35 0.00046\\ }; \addplot [color=blue, dashed, line width=1.0pt, forget plot] table[row sep=crcr]{% 0 0.856560809832214\\ 1 0.850134419878044\\ 2 0.842158542692523\\ 3 0.832570741289359\\ 4 0.821427119263506\\ 5 0.808870186196997\\ 6 0.795070694238331\\ 7 0.780179755462676\\ 8 0.764304000692831\\ 9 0.747499246190571\\ 10 0.729774049819035\\ 11 0.711096728316407\\ 12 0.691402468491484\\ 13 0.670599295889109\\ 14 0.648572814872365\\ 15 0.625190176892908\\ 16 0.600303990859824\\ 17 0.573757053962806\\ 18 0.545388946448561\\ 19 0.515045726852003\\ 20 0.48259416031167\\ 21 0.447942031240205\\ 22 0.411065980251948\\ 23 0.372047720791533\\ 24 0.331118094210097\\ 25 0.288705812888075\\ 26 0.245483580282788\\ 27 0.202398568783768\\ 28 0.160667859443718\\ 29 0.1217149524468\\ 30 0.0870258298879691\\ 31 0.0579193827920901\\ 32 0.0352629710293805\\ 33 0.019215009279918\\ 34 0.0091168365245574\\ 35 0.00363820395796678\\ }; \addplot [only marks, line width =1pt, mark size=1.5pt, mark=o, mark options={solid, OliveGreen}, forget plot] table[row sep=crcr]{% 0 0.857660000000002\\ 1 0.850910000000001\\ 2 0.841335\\ 3 0.832469999999999\\ 4 0.823169999999998\\ 5 0.80854\\ 6 0.79551\\ 7 0.779579999999999\\ 8 0.76415\\ 9 0.75004\\ 10 0.72983\\ 11 0.71202\\ 12 0.689675\\ 13 0.66997\\ 14 0.649554999999999\\ 15 0.62468\\ 16 0.600745\\ 17 0.57293\\ 18 0.546655\\ 19 0.51363\\ 20 0.480245\\ 21 0.44767\\ 22 0.41179\\ 23 0.370195\\ 24 0.33083\\ 25 0.28816\\ 26 0.2458\\ 27 0.20456\\ 28 0.162835\\ 29 0.12168\\ 30 0.0883350000000001\\ 31 0.060655\\ 32 0.0356\\ 33 0.019625\\ 34 0.010535\\ 35 0.00469499999999997\\ }; \draw [black, line width=0.60pt] (axis cs: 19.20,0.001) ellipse [x radius=10, y radius=2]; \node at (axis cs: 15,0.0001) (nodeA) {\scriptsize {BPSK}}; \draw[black,thin,->] (axis cs: 18,0.001) - - (nodeA) ; \draw [black, line width=0.60pt] (axis cs: 28.20,0.001) ellipse [x radius=10, y radius=2]; \node at (axis cs: 26,0.0001) (nodeA) {\scriptsize {4-PAM}}; \draw[black,thin,->] (axis cs: 27.20,0.001) - - (nodeA) ; \draw [black, line width=0.60pt] (axis cs: 31.20,0.05) ellipse [x radius=8, y radius=1.2]; \node at (axis cs: 30,0.01) (nodeA) {\scriptsize {8-PAM}}; \draw[black,thin,->] (axis cs: 30.6,0.08) - - (nodeA) ; \end{semilogyaxis} \end{tikzpicture}% \caption{\scriptsize {Symbol error probability of both RLS and Box-RLS decoders.}}% \label{fig221} \end{center} \end{figure} \begin{corollary}{(Optimal regularization coefficient for RLS in MSE and SEP senses):}\label{C:opt_Lmda} \normalfont Let $\lambda_\star$ denote the optimal regularization coefficient that minimizes the limit in (\ref{RLS-MSE}) or in \eqref{SER-RLS1}. Then, \begin{equation}\label{opt_Lmda} \lambda_\star = \frac{1}{\rho_\mathsmaller{d}}+ \sigma_{\mathsmaller{\Delta}}^2. \end{equation} \end{corollary} \begin{proof} Note that in both \eqref{RLS-MSE} and \eqref{SER-RLS1}, the regularization coefficient $\lambda$ appears through $\theta_\star$ only. Then, $\lambda_\star = {\argmin}_{\lambda\geq 0} \theta_\star$. Taking the derivative of $\theta_\star$ with respect to $\lambda$, setting it to zero and solving completes the proof of the corollary. \end{proof} \begin{remark} It is worth mentioning that the optimal regularization coefficient in \eqref{opt_Lmda} minimizes both the MSE and SEP. Moreover, it can be written in terms of the so called effective SNR of the system \cite{hassibi2003much} as $\lambda_\star = \frac{\sigma_{\mathsmaller{\hat{H}}}^2}{\rho_{\text{eff}}}$, where \begin{equation}\rho_{\text{eff}} := \frac{\rho_\mathsmaller{d} \sigma_{\mathsmaller{\hat{H}}}^2}{1 + \rho_\mathsmaller{d} \sigma_{\mathsmaller{\Delta}}^2}. \label{rho_eff} \end{equation} \end{remark} \begin{remark} {In Appendix \ref{LMMSE_Append}, we show that the RLS detector with optimal regularization coefficient is equivalent to the LMMSE detector. The later is known by definition to minimize the MSE, but it turns out according to Corollary \ref{C:opt_Lmda} that it also minimizes the asymptotic SEP among all other choices of $\lambda$. In the perfect CSI case, $\sigma_{\mathsmaller{\Delta}}^2 = 0$, hence the optimal regularization coefficient becomes ${\lambda}_\star = \frac{1}{\rho_\mathsmaller{d}}$ which is clearly equivalent to the LMMSE decoder. This shows that in both perfect and imperfect settings, the RLS with optimal regularization coefficient turns out to be the LMMSE detector. Such a finding is appealing due to the fundamental importance of the LMMSE decoder in many applications.} \end{remark} \subsection{MSE and SEP Analysis for Box-RLS} In this subsection, we study the asymptotic performance of the Box-RLS decoder in terms of the MSE and SEP. We first present the MSE results in the following theorem. \begin{theorem}(MSE of Box-RLS):\label{Box-RLS MSE} \normalfont Fix $\lambda>0$, $\delta>0$, and let $\widehat{{\bf x}}$ be a minimizer of the Box-RLS problem in (\ref{eq:Box-RLS matrix}). Let $\beta_\star$ and $\theta_\star$ be the unique solutions in $\beta$ and $\theta$ to the following max-min problem: \begin{align} \label{box-minimax} \sup_{\beta >0}\min_{ \theta \geq 0} & \ D(\theta,\beta):= \frac{\beta\delta \theta}{2} +\frac{\beta}{2\theta}(1+\rho_{\mathsmaller{d}})- \frac{\beta^2}{4} + \frac{1}{M} \sum_{i =\pm1,\pm3,\cdots,\pm(M-1)} \Psi (\theta,\beta;i), \end{align} with \begin{align} \Psi (\theta,\beta; i) :=& t \big(c_i Q(-\ell_i) + d_i Q(\mu_i) \big) - \beta \sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} t \big( p(\ell_i) + p(\mu_i) \big) \nonumber \\ -&\frac{\beta^2}{{2 \rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\frac{\beta}{\theta}} + 4 \lambda\rho_{\mathsmaller{d}}} \int_{\ell_{i}}^{\mu_{i}} \bigg( \frac{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2 i}{\sqrt{\mathcal{E}\theta} } + \sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} h \bigg)^2 p(h) {\rm{d}}h, \end{align} where $\ell_i =-t(\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}}{\theta}+\frac{2\lambda \rho_d}{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} \beta})-\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}i}{\theta \sqrt{\mathcal{E}}}$, $\mu_i =t(\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}}{\theta}+\frac{2\lambda\rho_d}{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} \beta})-\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} i}{\theta \sqrt{\mathcal{E}}}$, $c_i = \frac{-\beta \sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}}{2} \ell_i + \frac{\beta {\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} i}{2 \theta\sqrt{\mathcal{E}}}$, and $d_i = \frac{\beta \sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} }{2} \mu_i - \frac{\beta {\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2} i}{2 \theta\sqrt{\mathcal{E}} }$. Then, under Assumption 1 and Assumption 2, it holds: \begin{equation} \underset{K\to\infty}{{\rm{plim}}} {\rm{MSE}} = \frac{1}{\rho_\mathsmaller{d} \sigma_{\mathsmaller{\hat{H}}}^2} \biggl(\delta \theta_{\star}^2 - \rho_\mathsmaller{d} \sigma_{\mathsmaller{\Delta}}^2 -1 \biggr), \end{equation} \end{theorem} \begin{proof} The proof of this theorem is deferred to Appendix \ref{sec:box}. \end{proof} \begin{remark} It is worth mentioning that contrary to previous works based on the framework of the CGMT, the optimization problem in \eqref{box-minimax} which resulted from the asymptotic analysis is not convex-concave in the variables $\theta$ and $\beta$. Indeed, it is concave in $\beta$ but not convex in $\theta$. This poses a major challenge to prove the uniqueness of the solutions in $\theta$ of \eqref{box-minimax}, which is a crucial step that is required to ensure convergence results. The reader can refer to Appendix \ref{sec:box} for more details of the technical arguments developed to show the uniqueness of the solutions of \eqref{box-minimax}. \end{remark} \begin{remark} If the optimal values $\theta_\star$ and $\beta_\star$ are strictly positive, then they satisfy the following first-order stationarity conditions: \begin{align*} & \frac{\partial D(\theta,\beta)}{\partial \theta} =0,\nonumber \\ &\frac{\partial D(\theta,\beta)}{\partial \beta} =0. \end{align*} which can be exploited in practice to facilitate their numerical evaluation. \end{remark} The following theorem provides the asymptotic expression of the SEP for the Box-RLS decoder. \begin{theorem}(SEP for Box-RLS):\label{Box_RLS SER} \normalfont Under the same settings of Theorem \ref{Box-RLS MSE}, assuming that the Box-RLS decoder uses a normalization constant given by $B=\frac{\sigma_{\hat{\mathsmaller{H}}}^2\frac{\beta_\star}{\theta_\star}}{\sigma_{\hat{\mathsmaller{H}}}^2\frac{\beta_\star}{\theta_\star}+2\lambda} $ where $\beta_\star$ is the solution to \eqref{box-minimax} in $\beta$, and that $t\notin\left\{\frac{Bi}{\sqrt{\mathcal{E}}},i= 1,3\cdots, M-1\right\}$, it holds that: $$ \underset{K\to\infty}{{\rm{plim}}} {\rm SEP}=\widetilde{{\rm SEP}}_{\text{\tiny Box-RLS}}, $$ where $\widetilde{\rm {SEP}}_{\text{\tiny Box-RLS}}$ is given in \eqref{eq:SEP_BoXc}. \begin{figure*} \begin{equation} \label{eq:SEP_BoXc} \begin{aligned} \widetilde{\rm SEP}_{\text{\tiny Box-RLS}}&=\frac{4}{M}\sum_{i=1,3,\dots,M-3}{\bf 1}_{\{\frac{t}{B}\geq\frac{i+1}{\sqrt{\mathcal{E}}}\}}Q\left(\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}}{\sqrt{\mathcal{E}}\theta_\star}\right)+\frac{2}{M}\sum_{i=1,3,\cdots,M-3}\left\{{\bf 1}_{\{\frac{i-1}{\sqrt{\mathcal{E}}}\leq \frac{t}{B}\leq \frac{i+1}{\sqrt{\mathcal{E}}}\}}Q\left(\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}}{\sqrt{\mathcal{E}}\theta_\star}\right)+{\bf 1}_{\{\frac{t}{B}\leq \frac{i-1}{\sqrt{\mathcal{E}}}\}}\right\}\\ &+\frac{2}{M}{\bf 1}_{\{\frac{t}{B}\geq \frac{M-2}{\sqrt{\mathcal{E}}}\}}Q\left(\frac{\sqrt{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}}{\sqrt{\mathcal{E}} \theta_\star}\right)+\frac{2}{M}{\bf 1}_{\{\frac{t}{B}\leq \frac{M-2}{\sqrt{\mathcal{E}}}\}}. \end{aligned} \end{equation} \hrule \end{figure*} If $t\geq \frac{M-1}{\sqrt{\mathcal{E}}}$, then $\widetilde{\rm SEP}_{\text{\tiny Box-RLS}}$ is simplified to: \begin{equation} \widetilde{{\rm SEP}}_{\text{\tiny Box-RLS}}=2\left(1-\frac{1}{M}\right)Q \biggl( \frac{\sqrt{\rho_\mathsmaller{d} \sigma_{\mathsmaller{\hat{H}}}^2 }}{\sqrt{\mathcal{E}}\theta_\star} \biggr). \end{equation} \end{theorem} \begin{proof} The proof of Theorem~\ref{Box_RLS SER} is also based on the CGMT framework and is given in Appendix \ref{sec:box}. \end{proof} \begin{remark} Figure \ref{xz2} and Figure \ref{fig221} reveal a perfect match between the analytical expressions of MSE and SEP given by Theorem~\ref{Box-RLS MSE} and Theorem~\ref{Box_RLS SER} and the numerical simulations. It also shows that the Box-RLS outperforms the ordinary RLS. Figure \ref{xz2} also suggests that as $M$ increases, the performance of the Box-RLS approaches that of the un-boxed RLS. This is because in this figure $t=\frac{M-1}{\sqrt{\mathcal{E}}}$ and as such as $M \to \infty$, the box-constraint $[-t,t]$ tends to $(-\infty,\infty)$ which is the whole real line $\mathbb{R}$, thereby reducing the Box-RLS to the RLS \end{remark} \begin{remark} It should be noted that when $t\geq\frac{M-1}{\sqrt{\mathcal{E}}}$, the MSE and SEP expressions take the same form as in the RLS case, with the single difference that $\theta_\star$ and $ \beta_\star$ do not admit a closed-form expression. Moreover, as for the RLS, the optimal regularization coefficient for Box-RLS is given by $\lambda_\star = {\argmin}_{\lambda\geq 0} \theta_\star$, since $\lambda$ appears in the expressions for the MSE and SEP only through $\theta_\star$. However, in contrast to the RLS, the optimal regularization coefficient cannot be obtained in closed-form, but could be retrieved by invoking any bisection algorithm. Moreover, as opposed to the RLS, its value depends on $M$. \end{remark} \begin{remark} Figure \ref{fig4} plots the optimal regularization coefficient computed using a bisection algorithm as a function of $\rho_d$ for RLS and Box-RLS for different values of $M$. As a first observation, we note that the optimal regularization coefficient for Box-RLS becomes zero starting from moderate values of $\rho_d$. Moreover, the Box-RLS needs less regularization, due to its achieved improvement over the RLS. On the other hand, in low SNR regions corresponding to low $\rho_d$ values, the optimal regularization coefficient for both RLS and Box-RLS are higher than $\frac{1}{\rho_{\mathsmaller{d}}}$ which coincides with the optimal regularization coefficient in the perfect CSI case. This can be explained by the fact, under imperfect CSI cases, more regularization is needed in low SNR regions, because of the degradation caused by channel estimation errors. \begin{figure} \centering \input{SER_lmda3} \centering \caption{\scriptsize {Optimal regularization coefficient $\lambda_\star$ as a function of the data power. We used $\delta=1.2, K=400, \alpha =0.5, T_p =400$, and $T =1000$.}} \label{fig4} \end{figure} \end{remark} \begin{remark} Similar to the regularization coefficient, we can set the threshold $t$ to the optimal value that minimizes the MSE and SEP expressions, that is $t_\star = \argmin_{t>0} \theta_\star$. Figure \ref{fig:threshold} shows the optimal box-threshold as a function of $\rho_d$ when the regularization coefficient is already optimized as well. As can be seen, for practical SNR regions, the optimal threshold coincides with $\frac{M-1}{\sqrt{\mathcal{E}}}$, which is the maximum value of ${\bf x}_0$. For this reason, we will use in the subsequent simulations this value for the threshold $t$. \begin{figure}[htbp] \centering \begin{subfigure} \centering \input{BPSK_thr.tex} \end{subfigure} \begin{subfigure} \centering \input{4PAM_thr.tex} \end{subfigure} \begin{subfigure} \centering \input{8PAM_the.tex} \end{subfigure} \caption{\scriptsize{The optimal normalized box-threshold $\sqrt{\mathcal{E}} t_\star$ as a function the data power. We used $\delta=1.2, K=400, T_p =400, \alpha =0.5$, and $T =1000$.}} \label{fig:threshold} \end{figure} \end{remark} \section{Optimal Data Power Allocation and Optimal Training Duration Allocation} In this section, we leverage the asymptotic expressions of the MSE and SEP derived thus far for the RLS and Box-RLS to determine the optimal power distribution between the training and data symbols. Particularly, we show that for all considered decoders, the optimal allocation schemes boils down to maximizing the effective SNR of the system $\rho_{\rm eff}$ defined in \eqref{rho_eff}. Additionally, we derive for each decoder the asymptotic expression of the goodput and derive the optimal fraction of power allocated to the pilot transmission as well as the training duration. (i.e. $(\tau_{\mathsmaller{p}}, \alpha)$ that maximizes the goodput). In this respect, we illustrate that, while the optimal power allocation remains to be the one that maximizes the effective SNR, the optimal number of training symbols coincides with the number of transmitting antennas $K$, which is also the minimum number of training symbols that needs to be employed to satisfy orthogonality between pilot sequences. \subsection{Simplifying the Decoders' Expressions} \subsubsection{LS decoder} To begin with, we consider first the LS decoder for which $\lambda=0$ and $\delta>1$. Hence, from \eqref{RLS-MSE}, $\Upsilon(0,\delta) =0$, and as such: \begin{equation*} \theta_\star =\sqrt{\frac{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1}{\delta -1}}, \end{equation*} The MSE limit in \eqref{RLS-MSE} reduces thus to \begin{align} \widetilde{\rm{ MSE}}_{\text{\tiny{LS}}} :=\underset{K\to\infty}{{\rm{plim}}} {\rm{ MSE}}_{\text{\tiny{LS}}} =& \frac{\delta (\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1)}{(\delta -1)\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2} -\frac{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1}{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2} \nonumber \\ =& \frac{\delta}{(\delta-1)\rho_\text{eff}} - \frac{1}{\rho_\text{eff}} \label{LS_MSE} \nonumber \\ =& \frac{1}{(\delta -1) \rho_\text{eff}}, \end{align} where $\rho_\text{eff}$ is the effective SNR defined in \eqref{rho_eff}. The result in \eqref{LS_MSE} recovers the well-known formula of the MSE of LS with the difference being that $\rho_d$ which stands for the SNR in the perfect CSI case is replaced by $\rho_\text{eff}$. Similarly, for $\delta>1$, and from \eqref{SER-RLS1}, the SEP of the LS decoder can also be expressed in terms of $\rho_\text{eff}$ as follows \begin{align}\label{LS_pp} \underset{K\to\infty}{{\rm{plim}}} {\rm{SEP}}_{\text{\tiny{LS}}} &= 2 \bigg( 1 - \frac{1}{M} \bigg) Q \bigg(\sqrt{\frac{(\delta -1)}{\mathcal{E} } \rho_{\text{eff}}}\bigg) \nonumber \\ &= 2 \bigg( 1 - \frac{1}{M} \bigg) Q \bigg(\sqrt{\frac{1}{\mathcal{E} \cdot \widetilde{\text{ MSE}}_{\text{\tiny{LS}}} }}\bigg). \end{align} Again, the first equation in \eqref{LS_pp} parallels the well-known result for the LS and BPSK signaling but under perfect CSI \cite{hassibi2005sphere}, (in which case the BER converges in probability to ${\text{BER}}_{LS} =Q(\sqrt{(\delta - 1)\rho_{\mathsmaller{d}}})$) in that it takes the same form with $\rho_{\text{eff}}$ replacing $\rho_{\mathsmaller{d}}$. Hence, our result generalizes \cite{hassibi2005sphere} to encompass $M$-PAM modulation and imperfect CSI scenarios \subsubsection{RLS decoder} We proceed now with the RLS decoder. The MSE expression in \eqref{RLS-MSE} can also be written in terms of $\rho_{\text{eff}}$ as \begin{equation} \widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}} :=\underset{K\to\infty}{{\rm{plim}}} {\rm{ MSE}}_{\text{\tiny{RLS}}} = \frac{\delta \theta_\star^2}{\rho_{\mathsmaller{d}}\sigma_{\mathsmaller{\hat{H}}}^2}- \frac{1}{\rho_{\text{eff}}}, \end{equation} from which it follows that $\frac{\rho_{\mathsmaller{d}}\sigma_{\mathsmaller{\hat{H}}}^2}{\theta_\star^2} = \frac{\delta}{\widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}} +\frac{1}{\rho_{\text{eff}}}}$. This yields the following interesting relationship between the MSE and SEP for the RLS decoder. \begin{align}\label{SER_MSE_RLS} \widetilde{\rm SEP}_{\text{\tiny RLS}}:=\underset{K\to\infty}{{\rm{plim}}} { \rm{SEP}}_{\text{\tiny{RLS}}} &= 2 \bigg( 1 - \frac{1}{M} \bigg) Q \bigg(\sqrt{\frac{\delta }{\mathcal{E} \cdot (\widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}} +\frac{1}{\rho_{\text{eff}}}) }}\bigg). \end{align} Such an expression holds for any $\lambda>0$, and not necessarily $\lambda_\star$. But when $\lambda=\lambda_\star$, with $\lambda_\star =\frac{\sigma_{\mathsmaller{\hat{H}}}^2}{\rho_{\text{eff}}}$, we obtain after some algebraic manipulations the following expression for the MSE: \begin{align}\label{RLS_pp} \underset{K\to\infty}{{\rm{plim}}} {\rm{MSE}}_{\text{\tiny{RLS}}} & =\frac{1}{2} \bigg( -\frac{1}{\rho_{\text{eff}}} + (1-\delta) + \sqrt{\frac{1}{\rho_{\text{eff}}^2} + \frac{2(1+\delta ) }{\rho_{\text{eff}}} +(1-\delta )^2} \bigg)\nonumber \\ &= \frac{1}{2} \bigg( -(\delta -1 +\frac{1}{\rho_{\text{eff}}}) + \sqrt{(\delta -1 +\frac{1}{\rho_{\text{eff}}})^2 + \frac{4}{\rho_{\text{eff}}}} \bigg). \end{align} Note that in the perfect CSI case for which the optimal regularization coefficient is $\frac{1}{\rho_{\mathsmaller{d}}}$, the right-hand side of \eqref{RLS_pp} is exactly the minimum mean squared error estimator (MMSE) (see\cite[Theorem 8]{wu2012optimal}), where $\rho_{\text{eff}}$ is replaced by ${\rho_{\mathsmaller{d}}}$. \subsubsection{Box-RLS decoder} In a similar way, for the Box-RLS decoder, we have the same asymptotic relationships between MSE and SEP: \begin{equation} \widetilde{\rm{ MSE}}_{\text{\tiny{Box-RLS}}}:=\underset{K\to\infty}{{\rm{plim}}} {\rm{MSE}}_{\text{\tiny{Box-RLS}}} = \frac{\delta \theta_\star^2}{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2} - \frac{1}{\rho_{\text{eff}}}, \end{equation} and, for $t \geq \frac{M-1}{\sqrt{\mathcal{E}}}$: \begin{align} \widetilde{\rm SEP}_{\text{\tiny{Box-RLS}}}&:=\underset{K\to\infty}{{\rm{plim}}} {\rm{SEP}}_{\text{\tiny{Box-RLS}}}\nonumber\\ &= 2 \bigg( 1 - \frac{1}{M} \bigg) Q \bigg(\sqrt{\frac{\delta }{\mathcal{E} \cdot (\widetilde{\rm{MSE}}_{\text{\tiny{Box-RLS}}}+\frac{1}{\rho_{\text{eff}}}) }}\bigg), \end{align} which again reveals that minimizing the MSE is equivalent to minimizing the SEP. \subsection{Optimal Power Allocation in MSE and SEP Sense} For the RLS decoder, we prove in Appendix \ref{Azx} that both $\widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}}$, and $\widetilde{\rm{ SEP}}_{\text{\tiny{RLS}}}$ are monotonically increasing functions in $\frac{1}{\rho_{\text{eff}}}$. Hence, minimizing the MSE or SEP is equivalent to maximizing $\rho_{\text{eff}}$. This can be easily seen to be the case of the LS decoder. However, for the Box-RLS decoder, such a statement could not be checked analytically as $\theta_\star$ does not possess a closed-form expressions. However, based on extensive simulations, we conjecture that both $\widetilde{\rm{MSE}}_{\text{\tiny{Box-RLS}}}$ and $\widetilde{\rm{SEP}}_{\text{\tiny{Box-RLS}}}$ increase with $\frac{1}{\rho_{\text{eff}}}$. All these considerations suggest that the optimal power allocation is the one that maximizes $\rho_{\text{eff}}$ over $\alpha$, i.e., \begin{equation} \alpha_\star = \argmax_{0< \alpha<1} \rho_{\text{eff}}. \end{equation} Recall that $\rho_{\text{eff}} = \frac{\rho_\mathsmaller{d} \sigma_{\mathsmaller{\hat{H}}}^2}{1+ \rho_\mathsmaller{d} \sigma_{\mathsmaller{\Delta}}^2}$. Substituting the expressions for $\sigma_{\mathsmaller{\hat{H}}}^2$ and $\sigma_{\mathsmaller{\Delta}}^2$ gives \begin{align} \rho_\text{eff}= \frac{\tau_\mathsmaller{p} \rho_\mathsmaller{p} \rho_\mathsmaller{d}}{(1+ \rho_\mathsmaller{d}) + \tau_\mathsmaller{p} \rho_\mathsmaller{p}}. \end{align} Further, upon using $\rho_\mathsmaller{p} = \frac{(1-\alpha) \rho \tau}{\tau_{\mathsmaller{p}}}$, and $\rho_\mathsmaller{d} = \frac{\alpha \rho \tau}{\tau_{\mathsmaller{d}}}$, the effective SNR becomes \begin{align*} \rho_\text{eff}&= \frac{\rho \tau}{\tau_\mathsmaller{d} -1} \cdot \frac{\alpha (1- \alpha)}{-\alpha + \frac{1 + \rho \tau}{\rho \tau(1- \frac{1}{\tau_\mathsmaller{d}})}}. \end{align*} With this expression at hand, we determine in the following Theorem the optimal power allocation that maximizes the effective SNR: \begin{theorem}(Optimal Power Allocation):\label{Power_Th} \normalfont The optimal power allocation $\alpha_\star$ that maximizes the effective SNR in a training-based system is given by \begin{equation}\label{optimal_power} \alpha_\star = \begin{cases} \vartheta - \sqrt{\vartheta(\vartheta -1)}, & \text{if $\tau_\mathsmaller{d} > 1$,} \\ \frac{1}{2}, & \text{if $\tau_\mathsmaller{d} =1$,} \\ \vartheta + \sqrt{\vartheta(\vartheta -1)} & \text{if $\tau_\mathsmaller{d} < 1$,} \end{cases} \end{equation} where $\vartheta = \frac{1 + \rho \tau}{\rho \tau (1 - \frac{1}{\tau_\mathsmaller{d}})}$. \end{theorem} \begin{proof} The proof of this theorem is given in Appendix \ref{power_proof}. \end{proof} It is worth mentioning that the use of this power allocation has already been proposed in the early work of \cite{hassibi2003much} as the one that maximizes a lower bound on the capacity. Interestingly, we retrieve the same power allocation scheme which we prove to be optimum in the MSE/SEP sense for RLS and LS decoders and conjecture that it is also optimum for the Box-RLS decoder. \begin{remark} \begin{itemize} \item At high SNR ($\rho \gg1$), $\vartheta \approx \frac{\tau_{\mathsmaller{d}}}{\tau_{\mathsmaller{d}} -1}$, then $\alpha_\star \approx \frac{\sqrt{\tau_{\mathsmaller{d}}}}{1+\sqrt{\tau_{\mathsmaller{d}}}}$. \item At low SNR ($\rho \ll 1$), $\vartheta \approx \frac{\tau_{\mathsmaller{d}}}{\rho \tau(\tau_{\mathsmaller{d}}-1)}$, and $\alpha_\star \approx \frac{1}{2}$. This means that, at low SNR, \textit{half} of the transmit energy should be devoted to training and the other half to data transmission. \end{itemize} \end{remark} \begin{remark}[Numerical Illustration] The asymptotic predictions of the MSE and the SEP are plotted as functions of the data power ratio $\alpha$ in Figure \ref{fig:MSE_alpha} and Figure \ref{fig:SER_alpha} when $\delta =2, K = 256, T=1000, T_{\mathsmaller{p}} =256, M=2$ and $\rho =15$ dB. As can be seen, the optimal power allocation, $\alpha_\star$, is the same in the MSE and SEP sense for the different decoders considered here, namely LS, RLS and Box-RLS. The same conclusion has been found for other settings confirming the conjecture that for Box-RLS, the optimal power allocation is obtained by maximizing the effective SNR. \end{remark} \begin{figure}[hh] \centering \input{MSE_alp02.tex} \caption{\scriptsize{MSE as a function of the data power ratio $\alpha$.}} \label{fig:MSE_alpha} \end{figure} \begin{figure}[hh] \centering \captionsetup{justification=centering,margin=2cm} \input{ SER_alp01.tex} \caption{\scriptsize{SEP as a function of the data power ratio $\alpha$.}} \label{fig:SER_alpha} \end{figure} \subsection{Joint Optimization of Power Allocation and Training Duration in the Goodput Sense} We now consider the goodput metric for the joint optimization of the power allocation and the training duration. From its definition in \eqref{good_def}, its asymptotic value can be written as: \begin{equation}\label{Goodput_limit} \underset{K\to\infty}{{\rm{plim}}} G = \bigg(1 -\frac{\tau_\mathsmaller{p}}{\tau}\bigg) \big(1- \underset{K\to\infty}{{\rm{plim}}} {\rm{SEP}} \big), \end{equation} where the limit in the right hand side is given by (\ref{SER-RLS1}) for RLS, and by \eqref{eq:SEP_BoXc} for Box-RLS. The above expression can be used to find the optimal pair $(\tau_{\mathsmaller{p}}^{\star},\alpha_\star)$ that \textit{maximizes} the goodput limit in (\ref{Goodput_limit}). The result is summarized below. \begin{proposition}({{Joint optimization in goodput sense}}): \normalfont The optimal pair $(\tau_{\mathsmaller{p}}^{\star},\alpha_\star)$ that maximizes the goodput limit in (\ref{Goodput_limit}) is given by: $\tau_{\mathsmaller{p}}^{\star} =1$ (or $T_{\mathsmaller{p}}^{\star} = K$), and $\alpha_\star$ is the same as in \eqref{optimal_power} for all $\rho$ and $\tau$ (or $T$). \end{proposition} \begin{proof} The proof of this proposition is given in Appendix \ref{goodput_proof}. \end{proof} \begin{remark} A major outcome of the above result is that the optimal number of training symbols that maximizes the goodput is given by the minimum number of the required training symbols that is the number of transmit antennas, $K$. This result differs from the finding of \cite{hassibi2003much} in which it has been proven that in case of equal distribution of power between training and data, the optimal number of training symbols may be larger than the number of transmit antennas. \end{remark} \section{Conclusions} \label{sec:conc} Based on the CGMT framework, this work carries out a large-system performance analysis of the regularized least squares (RLS) and box-regularized least squares (Box-RLS) decoders used to recover signals from $M$-ary constellations when the channel matrix is estimated using the LMMSE and is modeled by i.i.d. real Gaussian entries. Although our analysis relies on asymptotic growth assumptions, numerical results demonstrated the accuracy of the theoretical predictions even for limited system dimensions. Compared to previous related works, the main feature of the present work is our consideration of imperfect CSI, which allowed us to derive the optimal power allocation between training and data. However, considering imperfect CSI, posed several technical challenges and brought us to develop novel technical tools to establish convergence results. We believe that these results can be leveraged in the future to further facilitate carrying out rigorous analysis based on the use of the CGMT framework. \section*{Acknowledgment} We would like to thank Prof. Ahmed-Sultan Salem for the very helpful comments, discussions and suggestions. We also would like to thank Houssem Sifaou for fruitful discussions. \appendices \section{Gaussian Min-max Theorem} The key ingredient of the analysis is the \textbf{C}onvex \textbf{G}aussian \textbf{M}in-max \textbf{T}heorem (\textbf{CGMT}), a concrete formulation for it can be found in \cite{thrampoulidis2018precise}. The CGMT is a tool that allows analyzing the behavior of solutions of stochastic optimization problems that can be cast into the following form: \begin{equation} \label{primary} \Phi({\bf G}) := \underset{{\bf w} \in \mathcal{S}_{w}}{\operatorname{\min}} \ \underset{{\bf u} \in \mathcal{S}_{u}}{\operatorname{\max}} \ {\bf u}^{T} {\bf G} {\bf w} + \psi( {\bf w}, {\bf u}), \\ \end{equation} where ${\bf G}\in\mathbb{R}^{N\times K}$ with i.i.d. standard normal entries, $\mathcal{S}_w$ and $\mathcal{S}_{u}$ are sets of $\mathbb{R}^K$ and $\mathbb{R}^{N}$ and $\psi:\mathbb{R}^K\times \mathbb{R}^{N}\to \mathbb{R}$ is continuous convex-concave function on $\mathcal{S}_w\times \mathcal{S}_u$. Problem \eqref{primary} is referred to as Primary Problem (PO) and its analysis is in general not tractable. The CGMT associates with it an Auxiliary Optimization (AO) problem given by \begin{align} &\phi({\bf g}, {\bf s}) := \underset{{\bf w} \in \mathcal{S}_{w}}{\operatorname{\min}} \ \underset{{\bf u} \in \mathcal{S}_{u}}{\operatorname{\max}} \ \| {\bf w} \| {\bf g}^{T} {\bf u} - \| {\bf u} \| {\bf s}^{T} {\bf w} + \psi( {\bf w}, {\bf u}), \label{AA2} \end{align} where ${\bf g} \in \mathbb{R}^{N}$, and ${\bf s} \in \mathbb{R}^K$ have i.i.d. standard Gaussian entries. The initial formulation of the CGMT establishes that the (AO) has the same asymptotic behavior as the (PO) in the regime in which $N$ and $K$ grow simultaneously with the same pace under the condition that the sets $\mathcal{S}_{{w}}$ and $\mathcal{S}_{{u}}$ are convex and compacts. Particularly, if for some $\nu\in\mathbb{R}$, the optimal cost of the (AO) concentrates around $\nu$ in the sense that $$ \mathbb{P}\left[\left|\phi({\bf g},{\bf s})-\nu\right|\right]\to 0, $$ then the optimal cost of the PO concentrates also around $\nu$, satisfying similarly: $$ \mathbb{P}\left[\left|\Phi({\bf G})-\nu\right|\right]\to 0. $$ Recently in \cite{kammoun_christos}, the compactness of $\mathcal{S}_{{ u}}$ is shown to be possibly relaxed provided that the order of the min-max in \eqref{AA2} can be inverted, that is $\phi({\bf g},{\bf s})$ is also given by: \begin{equation} \phi({\bf g},{\bf s}):=\max_{{\bf u}\in\mathcal{S}_{ u}} \min_{{\bf w}\in\mathcal{S}_w} \|{\bf w}\|{\bf g}^{T}{\bf u} - \|{\bf u}\| {\bf s}^{T}{\bf w} +\psi({\bf w},{\bf u}). \label{eq:inversion} \end{equation} More formally, we have the following result: \begin{theorem}[CGMT \cite{thrampoulidis2018precise}] Let $\mathcal{S}$ be any arbitrary open subset of $\mathcal{S}_w $, and $\mathcal{S}^c = \mathcal{S}_w \setminus\mathcal{S}$. Denote $\phi_{\mathcal{S}^c}({\bf g},{\bf s})$ the optimal cost of the optimization in (\ref{AA2}), when the minimization over ${\bf w}$ is constrained over ${\bf w} \in \mathcal{S}^c$. Assume that $\mathcal{S}_u$ is convex while $\mathcal{S}_w$ is convex and compact. Assume also that \eqref{eq:inversion} holds true. Consider the regime $K, N\to\infty$ such that $\frac{N}{K}\to \delta$, which will be denoted by $K\to\infty$. Suppose that there exist constants $\bar{\phi}$ and $\eta >0$ such that in the limit as $K \rightarrow + \infty$ it holds with probability approaching one: (i) $\phi({\bf g},{\bf s}) \leq \bar{\phi} +\eta$, and, (ii) $\phi_{\mathcal{S}^c}({\bf g},{\bf s}) \geq \bar{\phi} + 2\eta$. Let ${\bf w}_\Phi$ and ${\bf w}_\phi$ denote respectively the solutions in ${\bf w}$ to the (PO) and the (AO). Then, $\lim_{K \rightarrow \infty} \mathbb{P}[{\bf w}_{\phi} \in \mathcal{S}] = 1$, and $\lim_{K \rightarrow \infty} \mathbb{P}[{\bf w}_{\Phi} \in \mathcal{S}] = 1.$ \label{eq:th_CGMT} \end{theorem} \begin{remark} It is worth mentioning that the result in Theorem \ref{eq:th_CGMT} goes beyond the asymptotic equivalence between the costs of the (AO) and the (PO) to the localization of the (PO) and (AO) solutions. More specifically, one can easily see that conditions $(i)$ and $(ii)$ in Theorem~\ref{eq:th_CGMT} imply that the solution of the (AO) lies in the set $\mathcal{S}$ with probability approaching $1$. Theorem \ref{eq:th_CGMT} allows us to carry over this property to the solution of the (PO), that is ${\bf w}_{\Phi}$ is in $\mathcal{S}$ with probability approaching $1$. \end{remark} \begin{remark} \label{remark_imp} To satisfy $(i)$ and $(ii)$ in Theorem \ref{eq:th_CGMT}, one can prove that $\phi({\bf g},{\bf s})$ converges to $\overline{\phi}$ while $\phi_{\mathcal{S}^{c}}({\bf g},{\bf s})$ is lower-bounded by a quantity that converges to $\overline{\phi}_{\mathcal{S}^c}$ with \begin{equation}\overline{\phi}_{\mathcal{S}^c}>\overline{\phi}. \label{eq:cond_eq}\end{equation} In practice, it is usually the case that $\overline{\phi}$ and $\overline{\phi}_{\mathcal{S}^{c}}$ represent optimal costs of the same optimization problem but with the solution of the latter being constrained to be away from the optimal solution of the former. Under this setting, showing that the optimization problem whose optimal cost is $\overline{\phi}$ admits a unique solution directly implies \eqref{eq:cond_eq}. \end{remark} \section{Proofs of Box-RLS} \label{sec:box} In this appendix we prove Theorem~\ref{Box-RLS MSE} and Theorem \ref{Box_RLS SER}. For simplicity, we will divide the steps of the proof into subsections. \subsection{Identifying the (PO) and the (AO)} For convenience, we consider the error vector ${\bf w} := {\bf x}- {\bf x}_0 $, and also the box set: \begin{equation} \mathcal{B}= \bigg\{ {\bf w} \in \mathbb{R}^K | -t - x_\mathsmaller{{0,j}} \leq w_j \leq t- x_\mathsmaller{{0,j}}, j \in \{1,2, \cdots, K\} \bigg\}, \end{equation} With this notation, the problem in (\ref{eq:Box-RLS matrix}) can be reformulated as \begin{equation}\label{Lasso_w} \widehat{{\bf w}} = \text{arg} \ \underset{{\bf w} \in \mathcal{B}}{\operatorname{\min}} \ \biggl\| \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}}\widehat{{\bf H}} {\bf w} -\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \hbox{\boldmath$\Delta$} {\bf x}_0 - {\bf z} \biggr\|^2+ \rho_{\mathsmaller{d}}\lambda \| {\bf x}_0 +{\bf w} \|^2. \end{equation} \noindent To bring the problem in (\ref{Lasso_w}) to the form of \eqref{primary} required by the CGMT, we express the loss function of (\ref{Lasso_w}) in its dual form through the Fenchel's conjugate $$\ \left\| \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}}\widehat{{\bf H}} {\bf w} -\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \hbox{\boldmath$\Delta$} {\bf x}_0 - {\bf z} \right\|^2 = \max_{{\bf u}} {\bf u}^T \left(\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}}\widehat{{\bf H}} {\bf w} -\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \hbox{\boldmath$\Delta$} {\bf x}_0 - {\bf z} \right) - \frac{\| {\bf u} \|^2}{4}.$$ Hence, the problem in (\ref{Lasso_w}) is equivalent to the following: \begin{align}\label{minmax_1} \underset{{\bf w} \in \mathcal{B}}{\operatorname{\min}} \ \underset{{\bf u}}{\operatorname{\max}} &\ {\bf u}^T \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}}\widehat{{\bf H}} {\bf w} -{\bf u}^T \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \hbox{\boldmath$\Delta$} {\bf x}_0 - {\bf u}^T {\bf z} - \frac{\| {\bf u} \|^2}{4} + \rho_{\mathsmaller{d}}\lambda \| {\bf x}_0 +{\bf w} \|^2, \end{align} To reach the desired PO form, we introduce the variables ${\bf v}= \begin{bmatrix} \sigma_{\mathsmaller{\hat{H}}} \sqrt{\rho_{\mathsmaller{d}}}{\bf w} \\[0.3em] -\sigma_{\mathsmaller{\Delta}} \sqrt{\rho_{\mathsmaller{d}}}{{\bf x}}_0 \\[0.3em] \end{bmatrix}$ $\in \mathbb{R}^{2K}$, ${\bf G}= \begin{bmatrix} \widetilde{{\bf H}} & \widetilde{\hbox{\boldmath$\Delta$}} \\[0.3em] \end{bmatrix}$ $\in \mathbb{R}^{N \times 2K}$ and ${\bf C}= \begin{bmatrix} \frac{1}{\sigma_{\mathsmaller{\hat{H}}}}{\bf I}_{K} & \frac{-1}{ \sigma_{\mathsmaller{\Delta}}} {\bf I}_{K} \\[0.3em] \end{bmatrix}$ $\in \mathbb{R}^{K \times 2K}$, where $\widetilde{{\bf H}}$ and $\widetilde{\hbox{\boldmath$\Delta$}}$ are $N \times K$ independent matrices with i.i.d. standard normal entries. Now, using these variables, and after normalization by $1/K$, the above problem can be written as: \begin{align} {\Phi}:=&\frac{1}{\sqrt{K}}\underset{{\bf v} \in \mathcal{D}}{\operatorname{\min}} \ \underset{{\bf u}}{\operatorname{\max}} \ \frac{1}{K} {\bf u}^T {\bf G} {\bf v} - \frac{1}{\sqrt{K}}{\bf u}^T {\bf z} - \frac{\| {\bf u} \|^2}{4\sqrt{K}} + \frac{\lambda}{\sqrt{K}} \| {\bf C} {\bf v} \|^2, \label{POprob} \end{align} where $\mathcal{D} = \{{\bf v}^T \in \mathbb{R}^{1 \times 2K}, \ \ {\bf v}= [ \sigma_{\mathsmaller{\hat{H}}} \sqrt{\rho_{\mathsmaller{d}}}{{\bf w}}^T \quad -\sigma_{\mathsmaller{\Delta}} \sqrt{\rho_{\mathsmaller{d}}}{{{\bf x}}_0}^T]^{T} | {{\bf w}} \in \mathcal{B}\}$. We note that \eqref{POprob} is in the form of the (PO) and associate with it the following (AO) \begin{align}\label{eq:AO1} \phi:=\frac{1}{\sqrt{K}}&\underset{{\bf v} \in \mathcal{D} }{\operatorname{\min}} \ \underset{{\bf u}}{\operatorname{\max}} \ \| {\bf v} \| \frac{1}{K}{\bf g}^T {\bf u} - \frac{1}{K}\| {\bf u} \| {\bf q}^T {\bf v} - \frac{1}{\sqrt{K}} {\bf u}^T {\bf z} - \frac{1}{4\sqrt{K}} \| {\bf u}\|^2 + \frac{1}{\sqrt{K}} \lambda \| {\bf C} {\bf v} \|^2, \end{align} where ${\bf q} \in \mathbb{R}^{2K}$ and ${\bf g} \in \mathbb{R}^N$ are independent standard normal vectors. Note that for the moment, we relate the (PO) to the unbounded (AO) as $\mathcal{S}_u=\mathbb{R}^{N}$ is not compact. In the sequel, we check that \eqref{eq:inversion} holds true, which gives support to considering the unbounded (AO) according to Theorem \ref{eq:th_CGMT}. \subsection{Scalarizing the (AO)} The next step is to simplify the (AO) as it appears in (\ref{eq:AO1}) into an optimization problem involving only scalar variables. Since the vectors ${\bf g}$ and ${\bf z}$ are independent and have i.i.d. Gaussian entries, then, $ \| {\bf v} \| {\bf g}- \sqrt{K} {\bf z}$ has i.i.d. entries $\mathcal{N}(0,\| {\bf v} \|^2 + K)$. Hence, for our purposes and using some abuse of notation so that ${\bf g}$ continues to denote a vector with i.i.d. standard normal entries, the corresponding terms in (\ref{eq:AO1}) can be combined as $\sqrt{\| {\bf v} \|^2 + K}{\bf g}^T {\bf u}$, instead. {{Therefore, (\ref{eq:AO1}) is equivalent to}} \begin{align}\label{simpleAO1} \phi=& \ \underset{{\bf v} \in \mathcal{D}}{\operatorname{\min}} \ \underset{{\bf u}}{\operatorname{\max}} \ \frac{{\bf g}^T {\bf u}}{K}\sqrt{\frac{1}{K}\| {\bf v} \|^2 + 1} -\frac{1}{K\sqrt{K}} \| {\bf u} \| {\bf q}^T {\bf v} - \frac{1}{4 {K}} \| {\bf u} \|^2 + \frac{1}{{K}} \lambda\| {\bf C} {\bf v} \|^2 . \end{align} Expressing the above problem in terms of the original ${\bf w}$ variable: {{ \begin{align}\label{PO20} \phi\!=\! \underset{{{\bf w}}\in \mathcal{B}}{\operatorname{\min}} \ \underset{{\bf u}}{\operatorname{\max}} & \ \frac{{\bf g}^T {\bf u}}{K}\sqrt{\sigma_{\mathsmaller{\hat{H}}}^2 \rho_{\mathsmaller{d}} \frac{1}{K}\| {{\bf w}} \|^2 + \sigma_{\mathsmaller{\Delta}}^2 \rho_{\mathsmaller{d}} \frac{1}{K}\| {{\bf x}}_0\|^2+ 1} - \frac{1}{4{K}} \| {\bf u} \|^2\ \nonumber\\ &-\!\frac{\| {\bf u} \|}{K\sqrt{K}}\sqrt{\rho_{\mathsmaller{d}}} (\sigma_{\mathsmaller{\hat{H}}} {{\bf w}}^T{{\bf q}^{\boldsymbol{1}}} -\sigma_{\mathsmaller{\Delta}} {{\bf x}}_0^T{{\bf q}^{\boldsymbol{2}}} ) + \frac{1}{{K}} \lambda \rho_{\mathsmaller{d}} \| {{\bf x}}_0 +{{\bf w}} \|^2, \end{align}}} \noindent where ${\bf q}^{\boldsymbol{1}},{\bf q}^{\boldsymbol{2}} \in \mathbb{R}^K$ are independent standard normal vectors. Fixing the norm of $\frac{{\bf u}}{\sqrt{K}}$ to ${\beta}: =\frac{\| {\bf u} \|}{\sqrt{K}}$, it is easy to see that its optimal direction should be aligned with ${\bf g}$. Working with ${\bf x}$ instead of ${\bf w}$ results into the following optimization problem: \begin{align} \phi=\min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}} \max_{\beta>0} & \ \beta \frac{\| {\bf g} \|}{\sqrt{K}} \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}( \sigma_{\mathsmaller{\hat{H}}}^2 \| {{\bf x}} \|^2 -2\sigma_{\hat{H}}^2{\bf x}_0^{T}{\bf x}+\|{\bf x}_0\|^2) +1} -\frac{\beta^2}{4} \nonumber\\ &-\beta\sqrt{\rho_d}\sigma_{\hat{H}}\frac{1}{K}{\bf x}^{T}{\bf q}^{\bf 1}+ \frac{1}{K}\beta \sqrt{\rho_d}{\bf x}_0^{T}\tilde{\bf h}+\lambda \rho_d\frac{1}{K}\|{\bf x}\|^2,\label{eq:pr} \end{align} where $\tilde{\bf h}=\sigma_{\hat{H}} {\bf q}^{\bf 1}+\sigma_{\Delta}{\bf q}^{\bf 2}$. At this point, it is worth mentioning that \eqref{eq:pr} is convex in ${\bf x}$ and concave in $\beta$. Based on this, we can prove that \eqref{eq:inversion} holds true. Indeed using \cite[Cor. 37.3.2]{rockafellar2015convex}, we can flip the order of $\min_{\bf x}\max_{\beta}$. Now, consider the following problem \begin{align} \max_{\beta} \max_{\substack{\tilde{\bf u}\\ \|\tilde{\bf u}\|=1} }\min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}}& \ \beta {{\bf g}^{T}\tilde{\bf u}} \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}( \sigma_{\mathsmaller{\hat{H}}}^2 \| {{\bf x}} \|^2 -2\sigma_{\hat{H}}^2{\bf x}_0^{T}{\bf x}+\|{\bf x}_0\|^2) +1} -\frac{\beta^2}{4}\nonumber\\ &-\beta\sqrt{\rho_d}\sigma_{\hat{H}}\frac{1}{K}{\bf x}^{T}{\bf q}^{\bf 1}+ \frac{1}{K}\beta \sqrt{\rho_d}{\bf x}_0^{T}\tilde{\bf h}+\lambda \rho_d\frac{1}{K}\|{\bf x}\|^2.\label{eq:pr1} \end{align} Then, based on \cite[Lemma 8]{svm_abla} and setting ${\bf u}=\sqrt{K}\beta\tilde{\bf u}$ we can prove that \eqref{eq:pr1} is the same as \eqref{eq:pr} in which the order of the min-max is inverted. This completes the proof of \eqref{eq:inversion}, which as aforementioned, allows us to extend the scope of the CGMT for optimization problems in which the variable ${\bf u}$ is constrained to lie in a non-compact set. Now, getting back to the optimization problem in \eqref{eq:pr} and flipping the order of $\min_{\bf x}\max_{\beta}$ results into the following optimization problem: \begin{align} \phi=\max_{\beta>0} \min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}} & \nonumber\\ \hat{\mathcal{H}}(\beta,{\bf x}):=&\beta \frac{\| {\bf g} \|}{\sqrt{K}} \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}( \sigma_{\mathsmaller{\hat{H}}}^2 \| {{\bf x}} \|^2 -2\sigma_{\hat{H}}^2{\bf x}_0^{T}{\bf x}+\|{\bf x}_0\|^2) +1} -\frac{\beta^2}{4}\nonumber\\ &-\beta\sqrt{\rho_d}\sigma_{\hat{H}}\frac{1}{K}{\bf x}^{T}{\bf q}^{\bf 1}+ \beta \frac{1}{K}\sqrt{\rho_d}{\bf x}_0^{T}\tilde{\bf h}+\lambda \rho_d\frac{1}{K}\|{\bf x}\|^2.\label{eq:pr2} \end{align} Prior to proceeding further, we shall first check that the optimization over $\beta$ of the above problem is not achieved in the limit $\beta\to 0$ and more specifically, there exists $\tilde{\delta}>0$ such that taking the supremum over $\beta>\tilde{\delta}$ instead of $\beta>0$ would almost surely not change the optimal cost of \eqref{eq:pr2}. Towards this goal, first note that $$ \left|\min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}} \hat{\mathcal{H}}(\beta,{\bf x})\right|\leq \left|\beta \frac{\|{\bf g}\|}{\sqrt{K}}-\frac{\beta^2}{4}+\beta\left|\frac{1}{K}\sqrt{\rho_{\mathsmaller{d}}}{\bf x}_0^{T}\tilde{\bf h}\right|\right|, $$ and the function $\beta\mapsto \beta \left(\frac{\|{\bf g}\|}{\sqrt{K}}+\frac{1}{K}\sqrt{\rho_{\mathsmaller{d}}}\left|{\bf x}_0^{T}\tilde{\bf h}\right|\right)-\frac{\beta^2}{4}$ is increasing and positive for all $\beta\in \left[0,2 \left(\frac{\|{\bf g}\|}{\sqrt{K}}+\frac{1}{K}\sqrt{\rho_{\mathsmaller{d}}}\left|{\bf x}_0^{T}\tilde{\bf h}\right|\right)\right]$. As $2 \left(\frac{\|{\bf g}\|}{\sqrt{K}}+\frac{1}{K}\sqrt{\rho_{\mathsmaller{d}}}\left|{\bf x}_0^{T}\tilde{\bf h}\right|\right)$ converges in probability to $2\sqrt{\delta}$, with probability approaching one, for all $\tilde{\delta}\in(0,\sqrt{\delta})$, and all $\beta\in(0,\tilde{\delta})$, \begin{equation} \left|\min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}} \hat{\mathcal{H}}(\beta,{\bf x})\right|\leq 4\tilde{\delta}\sqrt{\delta}. \label{eq:min_proof} \end{equation} To conclude it suffices to prove that there exists a $\beta_0$ such that with probability approaching one, \begin{equation} \min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}} \hat{\mathcal{H}}(\beta_0,{\bf x}) > \Theta, \label{eq:HH} \end{equation} where $\Theta$ is a some positive constant. Indeed, if \eqref{eq:HH} is satisfied then almost surely, $$ \sup_{\beta>0}\min_{\substack{-t\leq x_j\leq t\\ j=1,\dots,K}}\hat{\mathcal{H}}(\beta_0,{\bf x}) >\Theta. $$ Setting $\tilde{\delta}=\min(\frac{\Theta}{4\sqrt{\delta}},\sqrt{\delta})$ in \eqref{eq:min_proof}, we conclude thus that the supremum over $\beta$ could not be attained in the interval $[0,\tilde{\delta}]$. To keep the flow of the proof, \eqref{eq:HH} is proved in Appendix \ref{app:pp}. With this result at hand, we are now ready to proceed to the optimization of the (AO). Let $\chi=\frac{\rho_d}{K}\left(\sigma_{\hat{H}}^2\|{\bf x}\|^2-2\sigma_{\hat{H}}^2{\bf x}_0^T{\bf x}+\|{\bf x}\|_0^2\right)+1$. To make the above optimization problem separable, we express the term in the square root in a variational form using the identity: $\sqrt{\chi} = \underset{r>0}{\operatorname{\min}} \ \frac{1}{2r} + \frac{r\chi}{2}$. Note that at optimum, $r_\star=\frac{1}{\sqrt{\chi}}$. Using the fact that $\chi\geq 1$ and as such bigger than any small positive constant, we also have $$ \sqrt{\chi}=\min_{0<r\leq C'} \frac{1}{2r}+\frac{r\chi}{2}. $$ where $C'$ is any constant greater than $1$. Similarly, as $\chi$ is almost surely bounded by some constant, we can also argue that: $$ \sqrt{\chi}=\min_{\epsilon' <r\leq C'} \frac{1}{2r}+\frac{r\chi}{2}. $$ where $\epsilon'$ is a sufficiently small positive constant. Using this relation, the optimization problem \eqref{eq:pr1} becomes {{ \begin{align}\label{AA23} \phi= \underset{{\beta} \geq 0}{\operatorname{\max}} \ \underset{\epsilon' <r\leq C'}{\operatorname{\min}} & \ {\beta} \biggl( \frac{ \| {\bf g} \|}{2r\sqrt{K}} + \frac{ r\| {\bf g} \| }{2 \sqrt{K}} + \frac{ \rho_{\mathsmaller{d}} r\| {\bf g} \| \| {{\bf x}}_0 \|^2}{2 \sqrt{K} K }+ \sqrt{\rho_{\mathsmaller{d}}} \frac{1}{K}\tilde{{\bf h}}^{T} {{\bf x}}_0 \biggr) \nonumber\\ &+ \frac{1}{K}\sum_{j = 1}^{K} \biggl[ \underset{-t\leq x_j \leq t }{\operatorname{\min}} \ \biggl(\frac{{\beta} \sigma_{\mathsmaller{\hat{H}}}^2 \rho_{\mathsmaller{d}} r\| {\bf g} \|}{2 \sqrt{K} } + {\lambda} \rho_{\mathsmaller{d}}\biggr) x_j^2 - {\beta} \biggl( \frac{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2 r\| {\bf g} \| }{\sqrt{K} } {x}_{0,j} + \sqrt{\rho_{\mathsmaller{d}}}\sigma_{\mathsmaller{\hat{H}}} q^1_{j} \biggr) {x}_j \biggr]-\frac{{\beta}^2}{4}. \end{align} }} For ease of notation, define $\tilde{\theta} :=\frac{r\| {\bf g} \|}{\sqrt{K}}$. As $\frac{1}{\sqrt{K}}\|{\bf g}\|$ is almost surely bounded above and below, the variable $\tilde{\theta}$ is almost surely bounded above by a constant $C$ which we shall assume as large as needed and also bounded below by some positive constant $\epsilon$ . Introducing this notation leads to: {{ \begin{align}\label{AA23} \phi= \ \underset{\beta > 0}{\operatorname{\max}} \ \underset{\epsilon\leq \tilde{\theta} \leq C}{\operatorname{\min}} & \ \frac{ \beta \| {\bf g} \|^2}{2\tilde{\theta}K} + \frac{ \beta \tilde{\theta}}{2 } - \frac{\beta^2}{4} + \frac{\beta \tilde{\theta}\rho_{\mathsmaller{d}} \| {{\bf x}}_0 \|^2}{2 K} + \sqrt{\rho_{\mathsmaller{d}}} \beta \frac{1}{K}{{\bf x}}_0^{T} \tilde{{\bf h}} \nonumber \\ & + \frac{1}{K}\sum_{j = 1}^{K} \biggl[ \underset{ -t\leq {x}_j \leq t }{\operatorname{\min}} \ \biggl(\frac{\beta \tilde{\theta}\rho_{\mathsmaller{d}}\sigma_{\mathsmaller{\hat{H}}}^2}{2} + \lambda \rho_{\mathsmaller{d}} \biggr) x_j^2 - \beta \biggl( \rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2 {x}_{0,j}\tilde{\theta}+\sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} q^{1}_{j} \biggr) {x}_j \biggr]. \end{align} For $\beta > 0$, the optimal solution in the variables ${x}_j$, $j=1,\dots,K$ of (\ref{AA23}) is given by: \begin{equation}\label{AO_Sol_box} \tilde{x}_j = \begin{cases} -t ,\ \text{if} \ q^1_{j} < x_{0}^{-}(\tilde{\theta},\beta,x_{0,j}), \\ t ,\ \text{if} \ q^1_{j} > x_{0}^{+}(\tilde{\theta},\beta,x_{0,j}), \\ \frac{\beta \biggl( {\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2}x_{0,j}\tilde{\theta} + \sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} q^1_{j} \biggr)}{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2 \beta \tilde{\theta} + 2 \lambda \rho_{\mathsmaller{d}}} ,\ \text{otherwise}, \end{cases} \end{equation} where \begin{align} x_{0}^{-}(\tilde{\theta},\beta,x_{0,j})&=-t \biggl(\tilde{\theta}\sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} + \frac{2 \lambda \rho_{\mathsmaller{d}}}{\beta\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\mathsmaller{\hat{H}}} } \biggr) - \sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} x_{0,j}\tilde{\theta},\label{eq:x0j-}\\ x_{0}^{+}(\tilde{\theta},\beta,x_{0,j})& = t \biggl(\tilde{\theta}\sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} + \frac{2 \lambda \rho_{\mathsmaller{d}}}{\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\mathsmaller{\hat{H}}} \beta} \biggr) - \sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} x_{0,j} \tilde{\theta}.\label{eq:x0j+} \end{align} {{To simplify notation, define $\xi = \sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}}$, then $x_{0}^{-}(\tilde{\theta},\beta,x_{0,j}) =-t\bigl({\xi}\tilde{\theta} + \frac{2 \lambda\rho_{\mathsmaller{d}}}{\xi \beta} \bigr) - {\xi} x_{0,j}\tilde{\theta}$, and $x_{0}^{+}(\tilde{\theta},\beta,x_{0,j}) =t\bigl({\xi}\tilde{\theta} + \frac{2 \lambda\rho_{\mathsmaller{d}}}{\xi \beta} \bigr) - {\xi} x_{0,j}\tilde{\theta}$}}. With these notations at hand, the above optimization problem reduces to the following SO \begin{align}\label{SO4} & \ \underset{\beta > 0}{\operatorname{\max}} \ \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\boldsymbol{1}}) := \frac{ \beta \| {\bf g} \|^2}{2\tilde{\theta}K} + \frac{ \beta \tilde{\theta} }{2 } - \frac{ \beta^2}{4} + \frac{\beta\tilde{\theta} \rho_{\mathsmaller{d}} \| {{\bf x}}_0 \|^2}{2 K} + \sqrt{\rho_{\mathsmaller{d}}} \beta \frac{1}{K}\tilde{{\bf h}}^{T} {{\bf x}}_0+ \frac{1}{K}\sum_{j = 1}^{K} v (\tilde{\theta},\beta ; q^1_{j}), \end{align} where \begin{equation}\label{soft_TH} v( \tilde{\theta},\beta ; q^1_{j}) = \begin{cases} t \bigl(\tilde{c}_j +\beta \xi q^1_j \bigr), \ \text{if} \ q^1_{j} < x_{0}^{-}(\tilde{\theta},\beta,x_{0,j}), \\ t \bigl( \tilde{d}_j - \beta \xi q^1_j \bigr), \ \text{if} \ q^1_{j} > x_{0}^{+}(\tilde{\theta},\beta,x_{0,j}), \\ -\frac{\beta^2 \bigl( \xi^2 x_{0,j} \tilde{\theta}+\xi q^1_{j} \bigr)^2}{2\xi^2 \beta\tilde{\theta} + 4 \lambda \rho_{\mathsmaller{d}}} ,\ \text{otherwise}, \end{cases} \end{equation} where $\tilde{c}_j = \frac{-\beta \xi}{2} x_{0}^{-}(\tilde{\theta},\beta,x_{0,j}) + \frac{\beta \tilde{\theta}\xi^2}{2 }x_{0,j}$, and $\tilde{d}_j = \frac{\beta \xi}{2} x_{0}^{+}(\tilde{\theta},\beta,x_{0,j}) - \frac{\beta \tilde{\theta}\xi^2}{2 }x_{0,j}$. \subsection{ Asymptotic analysis of the SO problem} After simplifying the (AO) as in (\ref{SO4}), we are now in a position to analyze its limiting behavior. Using the Weak Law of Large Numbers (WLLN) \footnote{We write $\overset{P}{\longrightarrow}$ to denote convergence in probability as $K \to \infty$.}, $\frac{1}{K} \| {\bf g} \|^2 \overset{P}{\longrightarrow} \frac{N}{K} := \delta$, $\frac{1}{K} {{\bf x}}_0^T \tilde{{\bf h}} \overset{P}{\longrightarrow} 0$, and $\frac{1}{K} \|{{\bf x}}_{0} \|^2 \overset{P}{\longrightarrow} 1$. {{To analyze the behavior of the summand, recall that each $x_{0,j}$ takes values $\pm1/\sqrt{\mathcal{E}}, \pm3/\sqrt{\mathcal{E}},..., \pm(M-1)/\sqrt{\mathcal{E}}$ with equal probability $1/M$.}} Let $i = \pm1, \pm3,..., \pm(M-1)$ and denote by $\ell_i =-t(\xi\tilde{\theta}+\frac{2\lambda \rho_d}{\xi \beta})-\frac{\xi i\tilde{\theta}}{ \sqrt{\mathcal{E}}}$, $\mu_i =t(\xi\tilde{\theta}+\frac{2\lambda\rho_d}{\xi \beta})-\frac{\xi i \tilde{\theta}}{ \sqrt{\mathcal{E}}}$, $c_i = \frac{-\beta \xi}{2} \ell_i + \frac{\beta \xi^2 i\tilde{\theta}}{2 \sqrt{\mathcal{E}}}$, and $d_i = \frac{\beta \xi}{2} \mu_i - \frac{\beta \xi^2 \tilde{\theta}i}{2 \sqrt{\mathcal{E}} }$.\\ Hence, it can be shown that for all $\tilde{\theta}>0$ and $\beta > 0$, \begin{equation*} \frac{1}{K} \sum_{j = 1}^{K} v ( \tilde{\theta},\beta ; q^1_{j}) \overset{P}{\longrightarrow} Y(\tilde{\theta},\beta), \end{equation*} where \begin{equation} Y(\tilde{\theta},\beta):= \frac{1}{M} \sum_{i= \pm1,\pm3,\cdots,\pm(M-1)} \tilde{Y}(\tilde{\theta},\beta,i) \end{equation} with \begin{align} \tilde{Y}(\theta,\beta,i)&:=\mathbb{E}_{h \thicksim\mathcal{N}(0,1)} [v (\tilde{\theta},\beta;h,\ell_i,\mu_i) ]\nonumber\\ &= -\frac{\beta^2}{{2 \xi^2 \beta\tilde{\theta}} + 4 \lambda\rho_{\mathsmaller{d}}} \int_{\ell_{i}}^{\mu_{i}} \bigg( \frac{\xi^2 i \tilde{\theta}}{\sqrt{\mathcal{E}} } + \xi h \bigg)^2 p(h) {\rm{d}}h +\int_{- \infty}^{\ell_{i}} t(c_i +\beta \xi h ) p(h) {\rm{d}}h+ \int_{\mu_{i}}^{\infty} t (d_i -\beta \xi h ) p(h) {\rm{d}}h \nonumber \\ =& \ t \big(c_i Q(-\ell_i) + d_i Q(\mu_i) \big) - \beta \xi t \big( p(\ell_i) + p(\mu_i) \big) -\frac{\beta^2}{{2 \xi^2 \beta\tilde{\theta}} + 4 \lambda\rho_{\mathsmaller{d}}} \int_{\ell_{i}}^{\mu_{i}} \bigg( \frac{\xi^2 i\tilde{\theta}}{\sqrt{\mathcal{E}} } + \xi h \bigg)^2 p(h) \text{d}h \nonumber \\ = \ & t \big(c_i Q(-\ell_i) + d_i Q(\mu_i) \big) - \beta \xi t \big( p(\ell_i) + p(\mu_i) \big) -\frac{\beta^2}{{2 \xi^2 \beta}\tilde{\theta} + 4 \lambda \rho_{\mathsmaller{d}}} \bigg( \bigg(\xi^2 + \frac{\xi^4 i^2\tilde{\theta}^2}{\mathcal{E} }\bigg)\big(Q(\ell_i) - Q(\mu_i) \big) \nonumber \\ +& \xi \big(\xi \ell_i + \frac{2 \xi^2 i \tilde{\theta}}{\sqrt{\mathcal{E}} } \big) p(\ell_i)- \xi \big(\xi\mu_i + \frac{2 \xi^2 i\tilde{\theta}}{\sqrt{\mathcal{E}} } \big) p(\mu_i) \bigg). \end{align} For a given $\beta$, consider the sequence of functions $$\varphi_K:\tilde{\theta}\mapsto \frac{1}{K}\sum_{j=1}^{K}v( \tilde{\theta},\beta ; q^1_{j}). $$ We can easily see that this sequence of functions is concave in $\tilde{\theta}$ since it has been derived by taking the infimum of linear functions in $\tilde{\theta}$ (cf. \eqref{AA23}). Hence, $\tilde{\theta}\mapsto Y(\theta,\beta)$ is concave in $\tilde{\theta}$. Since the convergence of concave functions is uniform over compact sets \cite[Theorem.II.1]{cox}, $\tilde{\theta}\mapsto \varphi_K(\tilde{\theta})$ converges uniformly to $\tilde{\theta}\mapsto Y(\tilde{\theta},\beta)$. Moreover, it is easy to prove that $\tilde{\theta} \mapsto \frac{\beta \|{\bf g}\|^2}{2\tilde{\theta}K}+\frac{\beta\tilde{\theta}}{2}+\frac{\beta \tilde{\theta}\rho_{\mathsmaller{d}}\|{\bf x}_0\|^2}{2K}$ converges uniformly to $\tilde{\theta}\mapsto \frac{\beta\delta}{2\tilde{\theta}} +\frac{\beta\tilde{\theta}}{2}+\frac{\beta\tilde{\theta}\rho_{\mathsmaller{d}}}{2}$ on the compact set $[\epsilon,C]$. Combining both results yields that $\tilde{\theta}\mapsto \widetilde{D}(\tilde{\theta},\beta, {\bf g},{\bf q}^{\bf 1})$ converges uniformly to $\tilde{\theta}\mapsto \overline{D}(\theta,\beta)$, where $$ \overline{D}(\tilde{\theta},\beta):=\frac{\beta\delta}{2\tilde{\theta}}-\frac{\beta^2}{4}+\frac{\beta\tilde{\theta}}{2}+\frac{\beta\tilde{\theta}\rho_{\mathsmaller{d}}}{2}+Y(\tilde{\theta},\beta). $$ As a consequence, $$ \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\bf 1})\to \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \overline{D}(\tilde{\theta},\beta). $$ We need now to prove that the supremum over $\beta$ converges to the supremum of the right-hand side of the above equation. To this end, note that the function $\beta \mapsto \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\bf 1})$ is concave and converges pointwise to $\beta\mapsto \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \overline{D}(\tilde{\theta},\beta)$. Moreover, it is easy to check that $\lim_{\beta\to\infty} \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \overline{D}(\tilde{\theta},\beta)=-\infty$. Using Lemma 10 in \cite{thrampoulidis2018precise}, we conclude that: \begin{equation} \phi= \sup_{\beta\geq 0} \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\bf 1}) \overset{P}{\longrightarrow} \overline{\phi}:=\sup_{\beta\geq 0}\underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \overline{D}(\tilde{\theta},\beta). \label{eq:supre} \end{equation} \subsection{Proof of the uniqueness of $(\tilde{\theta}_\star,\beta_\star)$ solving $\sup_{\beta\geq 0} \min_{\epsilon<\tilde{\theta}<C}\overline{D}(\tilde{\theta},\beta)$} Based on the above convergence, it follows from the CGMT that the optimal cost of the (PO) converges to the asymptotic limit of the (AO) which is given by $\sup_{\beta >0}\min_{\epsilon\leq \tilde{\theta} <C} \overline{D}(\tilde{\theta},\beta)$. However, our interest does not directly concern the characterization of the asymptotic limit of the (PO) but that of functionals of the vector ${\bf w}={\bf x}-{\bf x}_0$ that can be linked to some important metrics like MSE or SEP. As explained in Remark \ref{remark_imp}, proving that the max-min problem in \eqref{eq:supre} admits a unique solution $(\beta_\star,\tilde{\theta}_\star)$ would allow us to transfer any property of the solution of the (AO) to that of the (PO). Unfortunately, the objective in the max-min problem \eqref{eq:supre} is not convex in $\tilde{\theta}$, and hence the same approach pursued in \cite{thrampoulidis2018precise} could not be used here. A new approach to handle this problem is thus proposed. To begin with, we notice that since $\beta\mapsto -\frac{\beta^2}{4}$ is strictly concave, $\beta\mapsto \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \overline{D}(\tilde{\theta},\beta)$ is strictly concave in $\beta$. It thus has a unique maximum as it satisfies $\lim_{\beta\to\infty} \underset{\epsilon <\tilde{\theta}<C }{\operatorname{\min}} \overline{D}(\tilde{\theta},\beta)=-\infty$. Denote by $\beta_\star$ such a maximum. Let us prove that there exists a unique $\theta_\star$ that minimizes function $h$ defined as $h:\tilde{\theta}\mapsto \overline{D}(\tilde{\theta},\beta_\star)$. The proof of this result will be carried out into the following steps: \begin{enumerate} \item First, we prove that the minimum should be in the interior domain of $(\epsilon,C)$ for $C$ sufficiently large and $\epsilon$ sufficiently small. \item Next, we establish that $Y(\tilde{\theta},\beta_\star)$ satisfies: \begin{equation} \left|\tilde{\theta}\frac{\partial^3 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^3}\right|< 3\left|\frac{\partial^2 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}\right|. \label{eq:req} \end{equation} \item Starting from the observation that $\tilde{\theta}_\star$ is in the interior domain of the optimization set and based on the previously established results, we prove that $h$ admits a unique minimum. \end{enumerate} We start by establishing the first statement. It is obvious that the optimum could not be reached when $\tilde{\theta}$ is in the vicinity of zero since $\lim_{\tilde{\theta}\to 0^+} \overline{D}(\tilde{\theta},\beta_\star)=\infty$. Similarly, to prove that the minimum is not reached when $\tilde{\theta}$ grows to infinity, it suffices to check that $\lim_{\tilde{\theta}\to\infty} \overline{D}(\tilde{\theta},\beta_\star)=\infty$. Simple calculations lead to: \begin{align*} Y(\tilde{\theta},\beta_\star)\underset{\tilde{\theta}\to\infty}{\sim} -\frac{\beta \xi^2(M-1)^2}{M\mathcal{E}}\tilde{\theta}&=-\frac{3\beta_\star \xi^2(M-1)^2}{M(M^2-1)}\tilde{\theta}\\ &=-\frac{3\beta_\star \rho_{\mathsmaller{d}}\sigma_{\mathsmaller{\hat{H}}^2}(M-1)}{M(M+1)}\tilde{\theta}. \end{align*} Using this approximation, we thus have: $$ \overline{D}(\tilde{\theta},\beta_\star)\underset{\tilde{\theta}\to\infty}{\sim}\tilde{\theta}\beta_\star\left( -\frac{3 \rho_{\mathsmaller{d}}\sigma_{\mathsmaller{\hat{H}}}^2(M-1)}{M(M+1)} + \frac{1}{2}+\frac{\rho_{\mathsmaller{d}}}{2} \right). $$ It is easy to check that for $M\geq 2$, $\frac{3(M-1)}{M(M+1)}\leq \frac{1}{2}$. As $\sigma_{\mathsmaller{\hat{H}}}^2<1$, we thus have $\lim_{\theta\to\infty} \overline{D}(\tilde{\theta},\beta_\star)=\infty$. To prove \eqref{eq:req}, we need to compute the first three derivatives of the function $\tilde{\theta}\mapsto Y(\tilde{\theta},\beta_\star)$. After simple calculations, we can establish that: \begin{align} \frac{\partial Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}}=\frac{1}{M}& \sum_{\substack{i=\pm 1, \cdots,\\ \pm(M-1)}}\Big[\int_{\ell_i}^{\mu_i} 2\beta_\star^3\xi^2\left(\frac{\frac{\xi^2i\tilde{\theta}}{\sqrt{\mathcal{E}}}+\xi h}{2\xi^2\beta_\star\tilde{\theta}+4\lambda\rho_{\mathsmaller{d}}}\right)^2 p(h)dh\nonumber\\ &-\frac{2\beta_\star^2\xi^2i}{\sqrt{\mathcal{E}}}\int_{\ell_i}^{\mu_i}\left(\frac{\frac{\xi^2i\tilde{\theta}}{\sqrt{\mathcal{E}}}+\xi h}{2\xi^2\beta_\star\tilde{\theta}+4\lambda\rho_{\mathsmaller{d}}}\right)p(h)dh +\int_{-\infty}^{\ell_i} t^2\beta_\star \frac{\xi^2}{2}p(h)dh+\int_{\mu_i}^{\infty} t^2\beta_\star \frac{\xi^2}{2}p(h)dh\Big]. \end{align} Based on this expression, we compute the second and third derivatives of $Y(\tilde{\theta},\beta_\star)$ as: \begin{align} &\frac{\partial^2 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}=-2\beta_\star^2\frac{1}{M}\!\!\!\sum_{\substack{i=\pm 1, \cdots,\\ ,\pm(M-1)}}\!\!\!\int_{\ell_i}^{\mu_i}\frac{(4\lambda\rho_{\mathsmaller{d}}\frac{\xi^2i}{\sqrt{\mathcal{E}}}-2\xi^3\beta_\star h)^2 }{(2\xi^2\beta_\star\tilde{\theta}+4\lambda\rho_{\mathsmaller{d}})^3}p(h)dh,\label{sec} \end{align} \begin{align} &\frac{\partial^3 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^3}=6\beta_\star^2\frac{1}{M}\!\!\!\sum_{\substack{i=\pm 1,, \cdots,\\ \pm(M-1)}}\!\!\!\int_{\ell_i}^{\mu_i}\frac{2\xi^2\beta_\star(4\lambda\rho_{\mathsmaller{d}}\frac{\xi^2i}{\sqrt{\mathcal{E}}}-2\xi^3\beta_\star h)^2 }{(2\xi^2\beta_\star\tilde{\theta}+4\lambda\rho_{\mathsmaller{d}})^4}p(h)dh.\label{third} \end{align} Leveraging \eqref{sec} and \eqref{third}, it is easy to check that: \begin{align*} &\tilde{\theta}\frac{\partial^3 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^3}=-3\frac{\partial^2 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2} -24\beta_\star^2\frac{1}{M}\!\!\!\sum_{\substack{i=\pm 1,\\ \cdots,\pm(M-1)}}\!\!\!\int_{\ell_i}^{\mu_i}\frac{4\lambda\rho_{\mathsmaller{d}}(4\lambda\rho_{\mathsmaller{d}}\frac{\xi^2i}{\sqrt{\mathcal{E}}}-2\xi^3\beta_\star h)^2 }{(2\xi^2\beta_\star\tilde{\theta}+4\lambda\rho_{\mathsmaller{d}})^4}p(h)dh, \end{align*} from which we deduce that $$ \left|\tilde{\theta} \frac{\partial^3 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^3}\right| < 3\left|\frac{\partial^2 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}\right|. $$ With this result at hand, we are now ready to prove that function $h$ admits a unique minimum. We already proved that any minimum should lie in the interior domain of $(\epsilon,C)$. Assume that there exists two minimizers of $h$ which we denote by $\tilde{\theta}_{\star,1}$ and $\tilde{\theta}_{\star,2}$ such that $\tilde{\theta}_{\star,1}<\tilde{\theta}_{\star,2}$. The first order and second order conditions imply that: \begin{equation} \frac{{\rm{d}} h}{{\rm{d}} \tilde{\theta}}\Big|_{\tilde{\theta}=\tilde{\theta}_{\star,i}}=0 \ \ \textnormal{and} \ \ \ \frac{{\rm{d}}^2 h}{{\rm{d}}\tilde{\theta}^2}\Big|_{\tilde{\theta}=\tilde{\theta}_{\star,i}}\geq 0, \ \ i=1,2. \label{eq:cond1} \end{equation} Hence, there exists $\tilde{\theta}_3\in(\tilde{\theta}_{\star,1},\tilde{\theta}_{\star,2})$ such that \begin{equation}\frac{{\rm{d}}^2 h}{{\rm{d}}\tilde{\theta}^2}\Big|_{\tilde{\theta}=\tilde{\theta}_3}=0.\label{eq:cond2}\end{equation} We will prove that this will lead to contradiction unless $\tilde{\theta}_{\star,1}=\tilde{\theta}_{\star,2}$. To this end, first we notice that: $$ \frac{{\rm{d}}^2 h}{{\rm{d}}\tilde{\theta}^2}=-\beta_\star\delta \tilde{\theta}^{-3}+\frac{\partial^2Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}. $$ Hence, from \eqref{eq:cond1} and \eqref{eq:cond2} we obtain the following relations \begin{align} &\beta_\star\tilde{\delta}+\tilde{\theta}_{\star,1}^3\frac{\partial^2Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}\Big|_{\tilde{\theta}=\tilde{\theta}_{\star,1}}\geq 0,\label{eq:1}\\ &\beta_\star\tilde{\delta}+\tilde{\theta}_{\star,2}^3\frac{\partial^2Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}\Big|_{\tilde{\theta}=\tilde{\theta}_{\star,2}}\geq 0,\label{eq:2}\\ & \beta_\star\tilde{\delta}+\tilde{\theta}_{\star,3}^3\frac{\partial^2Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}\Big|_{\tilde{\theta}=\tilde{\theta}_{\star,3}}=0. \label{eq:3} \end{align} Consider function $k:\tilde{\theta}\mapsto \beta\tilde{\delta}+ \tilde{\theta}^3 \frac{\partial^2Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}$. The derivative of $k$ with respect to $\tilde{\theta}$ is given by: $$ k'(\tilde{\theta})= \tilde{\theta}^{2}\left(3\frac{\partial^2 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^2}+\tilde{\theta}\frac{\partial^3 Y(\tilde{\theta},\beta_\star)}{\partial \tilde{\theta}^3}\right). $$ From \eqref{eq:req}, $k'(\tilde{\theta})< 0$ and as such $k$ is decreasing. Hence, the relations \eqref{eq:1}, \eqref{eq:2} and \eqref{eq:3} could not simultaneously hold. Hence, $\tilde{\theta}_{\star,1}=\tilde{\theta}_{\star,2}$, and as a consequence $h$ admits a unique minimizer which we denote by $\tilde{\theta}_\star$. Now, since for any $\beta>0$, $\tilde{\theta}\mapsto\overline{D}(\tilde{\theta},\beta)$ goes to infinity when $\tilde{\theta}$ approaches zero or grows to infinity, we thus have: \begin{equation} \min_{\epsilon\leq\tilde{\theta}\leq C}\overline{D}(\tilde{\theta},\beta) = \inf_{\tilde{\theta}\geq 0}\overline{D}(\tilde{\theta},\beta), \ \ \forall \ \ \beta>0. \label{eq:rel} \end{equation} The above relation holds for all $\beta>0$. We already proved in Section B that the optimal solution in $\beta$ is almost surely away from zero. Thus, \begin{equation} \sup_{\beta>0} \min_{\epsilon\leq\tilde{\theta}\leq C}\overline{D}(\tilde{\theta},\beta) = \sup_{\beta>0} \inf_{\tilde{\theta}>0}\overline{D}(\tilde{\theta},\beta). \end{equation} \subsection{Asymptotic behavior of metrics depending on the solution of the (PO) } So far, we proved that the PO cost converges to the asymptotic cost of the (AO). We prove now that the uniqueness of the minimizer $\tilde{\theta}_\star$ allows us to carry over this convergence to metrics depending on the solution of the (PO). The recipe is as follows. Let $\eta>0$ and define $$\mathcal{S}_\eta=\left\{{\bf v} \ | \ {\bf v}\in\mathcal{D}, \ \textnormal{and} \ \frac{1}{K}\|{\bf v}\|^2\in \left(\frac{\delta}{\tilde{\theta}_\star^2}-1-\eta,\frac{\delta}{\tilde{\theta_\star}^2}-1+\eta\right) \right\}.$$ Conside the ``perturbed'' version of the (AO) in \eqref{eq:AO1} as follows: \begin{align} {\phi}_\eta:= \frac{1}{\sqrt{K}} \min_{{\bf v}\notin \mathcal{S}_\eta} &\max_{{\bf u}}\frac{1}{K} \|{\bf v}\|{\bf g}^{T}{\bf u}-\frac{1}{K}\|{\bf u}\|{\bf q}^{T}{\bf v} -\frac{1}{\sqrt{K}}{\bf u}^{T}{\bf z} -\frac{1}{4\sqrt{K}}\|{\bf u}\|^2+\frac{1}{\sqrt{K}}\lambda \|{\bf Cv}\|^2. \end{align} Following the same analysis carried out previously, we lower bound $\phi_{\eta}$ by $$ \phi_{\eta}\geq \max_{\beta\geq 0} \min_{\substack{\epsilon\leq \tilde{\theta}\leq C\\ \left|\frac{\|{\bf g}\|^2}{\tilde{\theta}^2K}-\frac{\delta}{\tilde{\theta}_\star^2}\right|>\eta}}\widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\bf 1}). $$ It is easy to note that if $\tilde{\theta}$ in $\left(\epsilon, C\right)$ is such that $\left|\frac{\|{\bf g}\|^2}{K\tilde{\theta}^2}-\frac{{\delta}}{\tilde{\theta}_\star^2}\right|>\eta$ then $$ \left|\tilde{\theta}-\tilde{\theta}_\star\frac{\|{\bf g}\|}{\sqrt{K}\sqrt{\delta}}\right| \geq \frac{\eta \tilde{\theta}^2\tilde{\theta}_\star^2}{\sqrt{\delta}\left(\tilde{\theta}_\star\frac{\|{\bf g}\|}{\sqrt{K}}+\tilde{\theta}\sqrt{\delta}\right)}\geq \frac{\eta\epsilon^2\tilde{\theta}_\star^2}{\sqrt{\delta}\left(C\sqrt{\delta}+\tilde{\theta}_\star\frac{\|{\bf g}\|}{\sqrt{K}}\right)}, $$ or also $$ \left|\tilde{\theta}_\star-\tilde{\theta}\right|> \frac{\eta \epsilon \tilde{\theta}_\star}{\frac{1}{\epsilon}+\frac{\sqrt{\delta}}{\tilde{\theta}_\star}}-\tilde{\theta} \left|1-\frac{\|{\bf g}\|}{\sqrt{K}\sqrt{\delta}}\right|. $$ Since $\left|1-\frac{\|{\bf g}\|}{\sqrt{K}\sqrt{\delta}}\right|$ converges to zero almost surely, there exists $\tilde{\eta}>0$ such that with probability approaching $1$, $$ \epsilon\leq \tilde{\theta}\leq C \ \text{and} \ \left|\frac{\|{\bf g}\|^2}{K\tilde{\theta}^2}-\frac{\delta}{\tilde{\theta}_\star^2}\right|\geq \eta \ \Longrightarrow \ \left|\tilde{\theta}-\tilde{\theta}_\star\right|\geq \tilde{\eta}. $$ Hence, with probability approaching $1$, $$ \phi_{\eta}\geq \sup_{\beta\geq 0} \min_{\substack{\epsilon\leq\tilde{\theta}\leq C\\ \left|\tilde{\theta}-\tilde{\theta}_\star\right|\geq \tilde{\eta}}} \widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\bf 1}). $$ Following the same asymptotic analysis as in Section C, we can prove similarly that $$ \sup_{\beta\geq 0} \min_{\substack{\epsilon\leq\tilde{\theta}\leq C\\ \left|\tilde{\theta}-\tilde{\theta}_\star\right|\geq \tilde{\eta}}} \widetilde{D}(\tilde{\theta},\beta,{\bf g},{\bf q}^{\bf 1})\overset{P}{\longrightarrow}\overline{\phi}_\eta:= \sup_{\beta\geq 0} \inf_{\substack{\tilde{\theta}\geq 0\\ \left|\tilde{\theta}-\tilde{\theta}_\star\right|\geq \tilde{\eta}}} \overline{D}(\tilde{\theta},\beta). $$ Clearly, $$ \overline{\phi}_\eta\geq \inf_{\substack{\tilde{\theta}\geq 0 \\ \left|\tilde{\theta}-\tilde{\theta}_\star\right|\geq \tilde{\eta}}} \overline{D}(\tilde{\theta},\beta_\star). $$ As $\tilde{\theta}_\star$ is the unique minimizer of $\inf_{\tilde{\theta}\geq 0}\overline{D}(\tilde{\theta},\beta_\star)$, $$ \overline{\phi}_{\eta}> \overline{\phi}. $$ Based on the CGMT in Theorem \ref{eq:th_CGMT} and recalling Remark \ref{remark_imp}, we thus have: \begin{equation} \lim_{K\to \infty }\mathbb{P}\left[{\bf v}_{\rm PO}\in\mathcal{S}_\eta\right]=1, \label{eq:v} \end{equation} where ${\bf v}_{\rm PO}$ is the solution in ${\bf v}$ of the (PO) in \eqref{POprob}, or equivalently: $$ \frac{1}{K} \|{\bf v}_{\rm PO} \|^2 \overset{P}{\longrightarrow} \frac{\delta}{\tilde{\theta}_\star^2}-1 = \delta\theta_\star^2-1, $$ where $\theta_\star=\frac{1}{\tilde{\theta}_\star}$. \subsection{Convergence of Lipschitz functions of the estimated vector $\widehat{\bf x}$} The objective here is to study the asymptotic behavior of Lipschitz functions of the solution to the PO which we denote by $\hat{\bf x}$. As will be seen in the next section, such a result is fundamental for the asymptotic analysis of the symbol error rate and can be of independent interest to analyze any other performance metric. Let $\beta_\star$ and $\tilde{\theta}_\star$ be the unique solutions of the optimization problem $\sup_{\beta>0}\inf_{\tilde{\theta}>0}\overline{D}(\tilde{\theta},\beta)$. Recall that ${\bf x}_0$ represents the transmitted vector, whose elements are drawn with equal probability from the $M$-PAM constellation. \begin{lemma} For $j=1,\cdots, K$, and for fixed $\tilde{\theta}$ and $\beta$, define $\kappa_j(.;\tilde{\theta},\beta,x_{0,j}):\mathbb{R}\to\mathbb{R}$ as: $$ \kappa_j(x;\tilde{\theta},\beta,x_{0,j})=\left\{\begin{array}{l} -t, \ \ \textnormal{if} \ \ x<x_{0}^{-}(\tilde{\theta},\beta,x_{0,j}) \\ t, \ \ \textnormal{if} \ \ x>x_{0}^{+}(\tilde{\theta},\beta,x_{0,j})\\ \frac{\beta\left(\rho_{\mathsmaller{d}}\sigma_{\hat{H}}^2x_{0,j}\tilde{\theta}+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}x\right)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta\tilde{\theta}+2\lambda\rho_{\mathsmaller{d}}}, \ \ \textnormal{otherwise}, \end{array} \right. $$ where $x_{0}^{-}(\tilde{\theta},\beta,x_{0,j})$ and $x_{0}^{+}(\tilde{\theta},\beta,x_{0,j})$ are given by \eqref{eq:x0j-} and \eqref{eq:x0j+}. Let $\widehat{\bf x}$ be the solution of the (PO). Then for all for all Lipschitz functions $\psi:\mathbb{R}\to\mathbb{R}$ with Lipschitz constant $L$, it holds: \begin{equation} \frac{1}{K}\sum_{i=1}^K \psi(\widehat{x}_i)-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\psi(\kappa_j(q_j;\tilde{\theta}_\star,\beta_\star,x_{0,j}))\right] \overset{P}{\longrightarrow} 0, \label{eq:conv} \end{equation} where $q_1,\cdots,q_K$ are independent and identically distributed standard Gaussian random variables and $(\beta_\star,\tilde{\theta}_\star)$ is the unique solution to the optimization problem $\sup_{\beta\geq 0} \inf_{\tilde{\theta}\geq 0}\overline{D}(\tilde{\theta},\beta)$. \label{lem:conv} \end{lemma} \begin{proof} To avoid heavy notations, we will remove $x_{0,j}$ from the notations of $\kappa_j(\tilde{\theta},\beta,x_{0,j})$ and that of $x_{0}^{-}(\tilde{\theta},\beta,x_{0,j})$ and $x_{0}^{+}(\tilde{\theta},\beta,x_{0,j})$ as it will not play any role in the proof. To prove \eqref{eq:conv}, we consider the set: $$ \mathcal{S}_{\epsilon}=\left\{{\bf x} \ \ | \ \ \left|\frac{1}{K}\sum_{i=1}^K \psi(x_i)-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\psi(\kappa_j(q_j;\tilde{\theta}_\star,\beta_\star))\right]\right|<\epsilon\right\}. $$ Then, in view of the CGMT, for \eqref{eq:conv} to hold true, it suffices to show that with probability approaching 1, \begin{equation} \max_{\beta>0} \min_{\substack{-t<x_j<t\\ j=1,\cdots,K\\ {\bf x}\notin \mathcal{S}_\epsilon }}\hat{\mathcal{H}}(\beta,{\bf x})\geq \overline{\phi},\label{eq:suf} \end{equation} where we recall that $\hat{\mathcal{H}}(\beta,{\bf x})$ is the objective of the optimization problem in \eqref{eq:pr1}. Noting that $$ \max_{\beta>0} \min_{\substack{-t<x_j<t\\ j=1,\cdots,K\\ {\bf x}\notin \mathcal{S}_\epsilon }}\hat{\mathcal{H}}(\beta,{\bf x})\geq \min_{\substack{-t<x_j<t\\ j=1,\cdots,K\\ {\bf x}\notin \mathcal{S}_\epsilon }}\hat{\mathcal{H}}(\beta_\star,{\bf x}), $$ the proof of \eqref{eq:suf} boils down to proving that \begin{equation} \min_{\substack{-t<x_j<t\\ j=1,\cdots,K \\ {\bf x}\notin \mathcal{S}_\epsilon }}\hat{\mathcal{H}}(\beta_\star,{\bf x})>\overline{\phi}. \label{eq:pbt} \end{equation} A key step towards showing \eqref{eq:pbt} is to analyze the asymptotic behavior of the following optimization problem: \begin{equation} \min_{\substack{-t<x_j<t\\ j=1,\cdots,K }}\hat{\mathcal{H}}(\beta_\star,{\bf x}). \label{eq:H} \end{equation} Particularly, the following statements will be shown in the sequel: \begin{itemize} \item[(i)] The following convergence holds true: \begin{equation} \min_{\substack{-t<x_j<t\\ j=1,\cdots,K }}\hat{\mathcal{H}}(\beta_\star,{\bf x}) \overset{P}{\longrightarrow}\overline{\phi}=\sup_{\beta\geq 0}\min_{\tilde{\theta}\geq 0}\overline{D}(\tilde{\theta},\beta) \label{eq:conv_p} \end{equation} \item[(ii)] Let $\hat{\tilde{{\bf x}}}=\left[\hat{\tilde{x}}_1,\cdots,\hat{\tilde{x}}_K\right]^{T}$ be the solution to the optimization problem in \eqref{eq:H}. Then, it holds with probability approaching 1, \begin{equation} \forall \ {\bf x}\in [-t,t]^{K}\backslash \mathcal{S}_\epsilon, \ \ \frac{1}{\sqrt{K}} \|{\bf x}-\hat{\tilde{{\bf x}}}\| \geq \frac{\epsilon}{2L}. \label{eq:21} \ \ \end{equation} \item[(iii)] For any ${\bf x}=\left[x_1,\cdots,x_K\right]^{T}\in \left[-t,t\right]^{K}$, there exists a constant $\overline{C}$ such that: \begin{equation} \hat{\mathcal{H}}(\beta_\star,{\bf x}) \geq \hat{\mathcal{H}}(\beta_\star,\hat{\tilde{{\bf x}}}) +\frac{\overline{C}}{2K}\|{\bf x}-\hat{\tilde{{\bf x}}}\|^2. \label{eq:22} \end{equation} \end{itemize} Prior to proving the above statements, let us see how they lead to the desired inequality \eqref{eq:pbt}. Putting together \eqref{eq:conv_p} and \eqref{eq:22} shows that for any $\ell>0$, with probability approaching $1$, \begin{equation} \hat{\mathcal{H}}(\beta_\star,{\bf x})\geq \overline{\phi}-\ell+\frac{\overline{C}}{2K}\|{\bf x}-\hat{\tilde{{\bf x}}}\|^2. \label{eq:ll} \end{equation} From \eqref{eq:21}, we have for any ${\bf x}\in [-t,t]^{K}\backslash \mathcal{S}_\epsilon$, \begin{equation} \frac{1}{K}\|{\bf x}-\hat{\tilde{{\bf x}}}\|^2\geq \frac{\epsilon^2}{4L}. \label{eq:ineq} \end{equation} Now, setting $\ell=\frac{\overline{C}\epsilon^2}{16L}$ in \eqref{eq:ll}, and using \eqref{eq:ineq} we get: $$ \hat{\mathcal{H}}(\beta_\star,{\bf x})\geq \overline{\phi}+\frac{\overline{C}\epsilon^2}{16L}. $$ The above inequality holds for any ${\bf x}\in [-t,t]^{K}\backslash \mathcal{S}_\epsilon$ hence, $$ \min_{\substack{-t<x_j<t\\ j=1,\cdots,K\\ {\bf x}\notin\mathcal{S}_\epsilon}} \hat{\mathcal{H}}(\beta_\star,{\bf x})\geq \overline{\phi}+\frac{\overline{C}\epsilon^2}{16L}>\overline{\phi}, $$ thus proving \eqref{eq:pbt}. \noindent\underline{Proof of \eqref{eq:conv_p}} Following the same calculations used in the analysis of the (AO), we can prove that for sufficiently small $\epsilon$ and large constant $C$, with probability approaching $1$, \begin{align} \!\!\min_{\substack{-t\leq x_j\leq t\\ j=1,\cdots,K }}\hat{\mathcal{H}}(\beta_\star,{\bf x})&\!\!=\!\! \min_{\epsilon\leq \tilde{\theta}\leq C} \widetilde{D}(\tilde{\theta},\beta_\star,{\bf g},{\bf q}^{\bf 1}). \end{align} Based on similar asymptotic analysis to that carried out in Section B, we can prove that $\tilde{\theta}\mapsto \widetilde{D}(\tilde{\theta},\beta_\star,{\bf g},{\bf q}^{\bf 1})$ converges uniformly to $\tilde{\theta}\mapsto \overline{D}(\tilde{\theta},\beta_\star)$ and hence, \begin{equation} \min_{\substack{-t\leq x_j\leq t\\ j=1,\cdots,K }}\hat{\mathcal{H}}(\beta_\star,{\bf x})\overset{P}{\longrightarrow} \overline{\phi}=\min_{\epsilon\leq \tilde{\theta}\leq C}\overline{D}(\tilde{\theta},\beta_\star). \label{eq:conv_u} \end{equation} \noindent\underline{Proof of \eqref{eq:21}} Let $\hat{\tilde{\theta}} \in\left\{\argmin_{\epsilon\leq\tilde{\theta}\leq C} \widetilde{D}(\tilde{\theta},\beta_\star,{\bf g},{\bf q}^{\bf 1})\right\}$. In view of \eqref{AO_Sol_box}, for $j=1,\cdots,K$, $\left\{\hat{\tilde{x}}_j=\kappa_j(q_j^1,\hat{\tilde{\theta}},\beta_\star)\right\}$ is a solution to \eqref{eq:H}. On the other hand, as the minimum of $\tilde{\theta}\mapsto \overline{D}(\tilde{\theta},\beta_\star)$ is unique, we conclude that $\hat{\tilde{\theta}}$ converges in probability to $\tilde{\theta}_\star$. From this convergence, we argue that \begin{equation} \max_{1\leq j\leq K}\left|\kappa_j(q_j^{1},\hat{\tilde{\theta}},\beta_\star)-\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star)\right|\overset{P}{\longrightarrow} 0. \label{eq:kappa_jconv} \end{equation} Prior to showing \eqref{eq:kappa_jconv}, let us explain how it leads to \eqref{eq:21}. Indeed from the Lipschitz assumption it holds that: \begin{equation} \max_{1\leq j\leq K} \left|\psi(\kappa_j(q_j^{1},\hat{\tilde{\theta}},\beta_\star))-\psi(\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star))\right|\overset{P}{\longrightarrow} 0. \label{eq:comb} \end{equation} Moreover, from the law of large numbers, $$ \frac{1}{K}\sum_{j=1}^{K}\psi(\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star))-\mathbb{E}\frac{1}{K}\sum_{j=1}^{K}\psi(\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star))\overset{P}{\longrightarrow}0, $$ which combined with \eqref{eq:comb} yields: $$ \frac{1}{K}\sum_{j=1}^{K}\psi(\kappa_j(q_j^{1},\hat{\tilde{\theta}},\beta_\star))-\mathbb{E}\frac{1}{K}\sum_{j=1}^{K}\psi(\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star))\overset{P}{\longrightarrow}0. $$ Hence, for $\epsilon>0$, with probability approaching one, $$ \left|\frac{1}{K}\sum_{j=1}^{K}\psi(\kappa_j(q_j^{1},\hat{\tilde{\theta}},\beta_\star))-\mathbb{E}\frac{1}{K}\sum_{j=1}^{K}\psi(\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star))\right|\leq \epsilon. $$ By definition of the set $\mathcal{S}_\epsilon$ and the triangle inequality, it holds with probability approaching 1 that for all ${\bf x}\in [-t,t]^{K}\backslash \mathcal{S}_\epsilon$ $$ \left|\frac{1}{K}\sum_{j=1}^{K}\psi(x_i)-\frac{1}{K}\sum_{j=1}^{K}\psi(\hat{\tilde{x}}_j))\right|\geq \frac{\epsilon}{2}. $$ Then, based on the Lipshitz property of $\psi$, it holds that: $$ \left\|{\bf x}-\hat{\tilde{\bf x}}\right\|\geq \frac{\epsilon}{2L}, $$ which shows \eqref{eq:21}. Now, to prove \eqref{eq:kappa_jconv}, note that since $\hat{\tilde{\theta}}\overset{P}{\longrightarrow}\tilde{\theta}_\star$, for any $\eta>0$, with probability approaching one, \begin{equation} -\eta\leq \hat{\tilde{\theta}}-\tilde{\theta}_\star\leq \eta, \label{eq:thet} \end{equation} from which we deduce that: $$ \max_{1\leq j\leq K} \left|x_{0}^{+}(\hat{\tilde{\theta}},\beta_\star)-x_{0}^{+}(\tilde{\theta}_\star,\beta_\star)\right|\leq\overline{C}\eta, $$ where $\overline{C}=\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}(\max_{1\leq j\leq K}|x_{0,j}|+t)$ and similarly, $$ \left|x_{0}^{-}(\hat{\tilde{\theta}},\beta_\star)-x_{0}^{-}(\tilde{\theta}_\star,\beta_\star)\right|\leq \overline{C}\eta. $$ Using the fact that $x_{0}^{-}(\tilde{\theta}_\star,\beta_\star)<x_{0}^{+}(\tilde{\theta}_\star,\beta_\star)$, and choosing $\eta$ sufficiently small, we conclude that if for some $j=1,\cdots,K$, $q_j^{1}\leq x_{0}^{-}(\tilde{\theta}_\star,\beta_\star)$, then $q_j^{1}\leq x_{0}^{+}(\tilde{\hat{\theta}},\beta_\star)$, and similarly, if $q_j^{1}\geq x_{0}^{+}(\tilde{\theta}_\star,\beta_\star)$, then $q_j^{1}\geq x_{0}^{-}(\tilde{\hat{\theta}},\beta_\star)$. As a consequence, \begin{align} &\max_{1\leq j\leq K}\left|\kappa_j(q_j^{1},\hat{\tilde{\theta}},\beta_\star,)-\kappa_j(q_j^{1},\tilde{\theta}_\star,\beta_\star)\right|\nonumber\\ &\leq \left|t+\frac{\beta_\star(\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2x_{0,j}\hat{\tilde{\theta}}+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}q_j^1)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta_\star\hat{\tilde{\theta}}+2\lambda\rho_{\mathsmaller{d}}}\right| {\bf 1}_{\{x_{0}^{-}(\hat{\tilde{\theta}},\beta_\star)\leq q_j^{1}\leq x_{0}^{-}(\theta_\star,\beta_\star)\}}\nonumber\\ &+\left|t+\frac{\beta_\star(\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2x_{0,j}{\tilde{\theta}_\star}+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}q_j^1)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta_\star{\tilde{\theta}}_\star+2\lambda\rho_{\mathsmaller{d}}}\right| {\bf 1}_{\{x_{0}^{-}({\tilde{\theta}}_\star,\beta_\star)\leq q_j^{1}\leq x_{0}^{-}(\hat{\tilde{\theta}},\beta_\star)\}}\nonumber\\ &+\left|t-\frac{\beta_\star(\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2x_{0,j}\hat{\tilde{\theta}}+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}q_j^1)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta_\star\hat{\tilde{\theta}}+2\lambda\rho_{\mathsmaller{d}}}\right| {\bf 1}_{\{x_{0}^{+}(\tilde{\theta}_\star,\beta_\star)\leq q_j^{1}\leq x_{0}^{+}(\hat{\tilde{\theta}},\beta_\star)\}}\nonumber\\ &+\left|t-\frac{\beta_\star(\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2x_{0,j}\tilde{\theta}_\star+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}q_j^1)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta_\star\tilde{\theta}_\star+2\lambda\rho_{\mathsmaller{d}}}\right| {\bf 1}_{\{x_{0}^{+}(\hat{\tilde{\theta}},\beta_\star)\leq q_j^{1}\leq x_{0}^{+}(\tilde{\theta}_\star,\beta_\star)\}}\nonumber\\ &+\left|\frac{\beta_\star(\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2x_{0,j}{\tilde{\theta}_\star}+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}q_j^1)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta_\star{\tilde{\theta}}_\star+2\lambda\rho_{\mathsmaller{d}}}-\frac{\beta_\star(\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2x_{0,j}\hat{\tilde{\theta}}+\sqrt{\rho_{\mathsmaller{d}}}\sigma_{\hat{\mathsmaller{H}}}q_j^1)}{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2\beta_\star\hat{\tilde{\theta}}+2\lambda\rho_{\mathsmaller{d}}}\right| {\bf 1}_{\{\max(x_{0}^{-}(\tilde{\theta}_\star,\beta_\star),x_{0}^{-}(\hat{\tilde{\theta}},\beta_\star))\leq q_j^1 \leq \min\left(x_{0}^{+}(\hat{\tilde{\theta}},\beta_\star),x_{0}^{+}(\tilde{\theta}_\star,\beta_\star)\right)\}}.\label{eq:formula} \end{align} Each term of the right-hand side of \eqref{eq:formula} can be bounded by a linear function of $\eta$ using \eqref{eq:thet}, thereby proving \eqref{eq:kappa_jconv}. \noindent\underline{Proof of \eqref{eq:22}} It can be checked that ${\bf x}\mapsto \hat{\mathcal{H}}(\beta_\star,{\bf x})$ is strongly convex, and its Hessian satisfies $\nabla^2 \hat{\mathcal{H}}(\beta_\star,{\bf x}) \succeq \frac{2\lambda}{K}\rho_{\mathsmaller{d}}{\bf I}_K$. Hence, for any ${\bf x}\in[-t,t]^{K}$, $$ \hat{\mathcal{H}}(\beta_\star,{\bf x})\geq \hat{\mathcal{H}}(\beta_\star,\hat{\tilde{{\bf x}}}) + \frac{2\lambda}{K}\rho_{\mathsmaller{d}} \left\|{\bf x}-\hat{\tilde{{\bf x}}}\right\|^2. $$ \end{proof} \subsection{From Lipschitz to the indicator function of solutions to the (PO)} \begin{lemma} Let $\hat{\bf x}$ be the solution to the (PO). Let $c\in\mathbb{R}$ such that $c\notin \left\{-t,t\right\}$. Then, $$ \frac{1}{K}\sum_{j=1}^K {\bf 1}_{\{{\hat{x}_j}\leq c\}}-\frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[{\kappa_j(q,\tilde{\theta}_\star,\beta_\star,x_{0,j})}\leq c\right] \overset{P}{\longrightarrow}0, $$ where $q$ is assumed to be drawn from a standard normal distribution. \label{lem:indicator} \end{lemma} \begin{proof} Similar to the proof of Lemma \ref{lem:conv}, for $j=1,\cdots,K$, to easy notations, we shall remove $x_{0,j}$ from the notation $\kappa_j(q,\tilde{\theta}_\star,\beta_\star,x_{0,j})$. Let $\eta>0$, and consider the following functions parametrized by $\eta$, $$\overline{\psi}_\eta(\alpha):=\left\{\begin{array}{ll} 1,& \alpha\leq c\\ 1-\frac{1}{\eta}(\alpha-c), & c\leq \alpha\leq c+\eta\\ 0, & \alpha\geq c+\eta, \end{array}\right. $$ and $$\underline{\psi}_\eta(\alpha):=\left\{\begin{array}{ll} 1,& \alpha\leq c-\eta\\ -\frac{1}{\eta}(\alpha-c), & c-\eta\leq \alpha\leq c\\ 0, & \alpha\geq c. \end{array} \right. $$ Both functions are Lipschitz with Lipschitz constant $\frac{1}{\eta}$. Moreover, for any $\alpha$, $$ \underline{\psi}_\eta(\alpha)\leq {\bf 1}_{\{{\alpha\leq c\}}} \leq \overline{\psi}_\eta(\alpha). $$ Define also function $\tilde{\psi}_\eta(\alpha)=\overline{\psi}_\eta(\alpha)-\underline{\psi}_\eta(\alpha)$. Then it is easy to see that: \begin{equation} \tilde{\psi}_\eta(\alpha)\leq {\bf 1}_{\{c-\eta\leq \alpha \leq c+\eta\}}. \label{eq:tilde_psi} \end{equation} Hence, \begin{equation} \frac{1}{K}\sum_{j=1}^K\underline{\psi}_\eta(\hat{x}_j)\leq \frac{1}{K}\sum_{j=1}^K{\bf 1}_{\{{\hat{x}_j\leq c\}}} \leq \frac{1}{K}\sum_{j=1}^K\overline{\psi}_\eta(\hat{x}_j), \label{eq:xj} \end{equation} and \begin{align} & \frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\underline{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right] \leq \frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\kappa_j(q,\tilde{\theta}_\star,\beta_\star)\leq c\right]\nonumber\\ &\leq \frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\overline{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]. \label{eq:xj1} \end{align} Using \eqref{eq:xj} and \eqref{eq:xj1}, it follows that: \begin{align} &\frac{1}{K}\sum_{j=1}^K\underline{\psi}_\eta(\hat{x}_j)-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\overline{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right] \nonumber\\ &\leq\frac{1}{K}\sum_{j=1}^K{\bf 1}_{\{{\hat{x}_j\leq c\}}}- \frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\kappa_j(q,\tilde{\theta}_\star,\beta_\star)\leq c\right]\nonumber\\ &\leq \frac{1}{K}\sum_{j=1}^K\overline{\psi}_\eta(\hat{x}_j)-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\overline{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]. \end{align} From Lemma \ref{lem:conv}, for $\epsilon>0$, with probability approaching one: \begin{equation} \left|\frac{1}{K}\underline{\psi}_\eta(\hat{x}_j)-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\underline{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]\right|\leq \epsilon, \end{equation} and \begin{equation} \left|\frac{1}{K}\overline{\psi}_\eta(\hat{x}_j)-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\overline{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]\right|\leq \epsilon. \end{equation} Hence, \begin{align} &-\epsilon-\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\tilde{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]\nonumber\\ &\leq\frac{1}{K}\sum_{j=1}^K{\bf 1}_{\{{\hat{x}_j\leq c\}}}- \frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\kappa_j(q,\tilde{\theta}_\star,\beta_\star)\leq c\right]\nonumber\\ &\leq \epsilon+\frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\tilde{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]. \label{eq:ine3} \end{align} From \eqref{eq:tilde_psi}, \begin{align*} & \lim_{\eta\to 0} \frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\tilde{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]\\ &\leq \lim_{\eta\to 0} \max_{1\leq j\leq K} \mathbb{P}\left[c-\eta \leq \kappa_j(q,\tilde{\theta}_\star,\beta_\star)\leq c+\eta\right]. \end{align*} As $c\notin\left\{-t,t\right\}$, the right-hand side of the above inequality converges to zero. Hence, there exists $\eta_0$ such that for all $\eta\leq \eta_0$, \begin{equation} \frac{1}{K}\sum_{j=1}^{K}\mathbb{E}\left[\tilde{\psi}_\eta(\kappa_j(q,\tilde{\theta}_\star,\beta_\star))\right]\leq \epsilon. \label{eq:ine1} \end{equation} Combining \eqref{eq:ine3} and \eqref{eq:ine1}, we get the desired result, that is that for $\epsilon>0$, with probability approaching $1$, $$ \left|\frac{1}{K}\sum_{j=1}^K{\bf 1}_{\{{\hat{x}_j\leq c\}}}- \frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\kappa_j(q,\tilde{\theta}_\star,\beta_\star)\leq c\right]\right|\leq 2\epsilon. $$ \end{proof} \begin{corollary} Consider the setting of Lemma \ref{lem:indicator}. We thus have: $$ \frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\hat{x}_j\leq c\right] -\frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\kappa_j(q,\tilde{\theta}_\star,\beta_\star,x_{0,j})\leq c \right] \to 0. $$ \label{cor:indicator} \end{corollary} \begin{proof} The proof follows straightforwardly by applying the dominated convergence theorem. \end{proof} \subsection{{{Applying the CGMT: MSE of Box-RLS}}} Let $\widehat{\bf x}$ be the solution of \eqref{eq:Box-RLS matrix}. Recall that the MSE is given by: $$ {\rm MSE}=\frac{1}{K}\|\widehat{\bf x}-{\bf x}_0\|^2, $$ which can be also written as: \begin{align*} {\rm MSE}&=\frac{1}{\rho_d\sigma_{\mathsmaller{\hat{H}}}^2}\left(\frac{1}{K}\|{\bf v}\|^2-\frac{\rho_d}{K}\sigma_{\mathsmaller{\Delta}}^2\|{\bf x}_0\|^2\right).\\ \end{align*} As $\frac{1}{K}\|{\bf v}\|^2\overset{P}{\longrightarrow} \delta\theta_\star^2-1$, and $\frac{1}{K}\|{\bf x}_0\|^2\overset{P}{\longrightarrow} 1$, we thus have: $$ {\rm MSE}\overset{P}{\longrightarrow} \frac{1}{\rho_d\sigma_{\mathsmaller{\hat{H}}}^2}\left(\delta \theta_\star^2-1-{\rho_d}\sigma_{\mathsmaller{\Delta}}^2\right). $$ \subsection{{{Applying the CGMT: SEP for Box-RLS}}} In this subsection, we study the limiting behavior of the SEP defined in \eqref{eq:SEP}. For $j=1,\cdots,K$, consider the output of the (PO) problem which denoted by $\hat{\bf x}$ . Recall the expression of the SEP $$ {\rm SEP}=\frac{1}{K}\sum_{j=1}^{K}\mathbb{P}\left[\hat{s} \neq x_{0,j}, \text{with} \ \ \hat{s}=\argmin_{s \in \mathcal{C}} |\frac{\hat{x}_j}{B}-s|\right]. $$ In PAM-constellations, we distinguish inner symbols when ${x}_{0,j}$ belongs to $\frac{1}{\sqrt{\mathcal{E}}}\{\pm1,\pm3,\cdots,\pm(M-3) \}$ from edge symbols when ${x}_{0,j}=\pm \frac{M-1}{\sqrt{\mathcal{E}}}$. Let us consider first the case where ${x}_{0,j}$ is a certain inner symbol. In this case, there is an error if and only if $| \frac{\hat{x}_j }{B}-x_{0,j} | > \frac{1}{\sqrt{\mathcal{E}}}$, where $B = \frac{ \xi^2 \beta_\star \tilde{\theta}_\star }{\xi^2 {\beta_\star}\tilde{\theta}_\star + 2 \lambda \rho_{\mathsmaller{d}}}$. Similarly, considering the edge points $x_{0,j}=\pm\frac{M-1}{\sqrt{\mathcal{E}}}$, we deduce that there is an error if $ \frac{\hat{x}_j }{B}-x_{0,j} > \frac{1}{\sqrt{\mathcal{E}}}$ when $x_{0,j}=\frac{M-1}{\sqrt{\mathcal{E}}}$ and if $\frac{\hat{x}_j }{B}-x_{0,j} < -\frac{1}{\sqrt{\mathcal{E}}}$ when $x_{0,j}=-\frac{M-1}{\sqrt{\mathcal{E}}}$. The SEP thus becomes: \begin{align*} {\rm SEP}&=\frac{1}{K}\sum_{j=1}^K\frac{1}{M}\sum_{\substack{i=\pm 1,\pm 3,\\ \cdots,\pm (M-2)}}\mathbb{P}\left[\left|\frac{\hat{x}_j}{B}-{ x}_{0,j}\right|> \frac{1}{\sqrt{\mathcal{E}}} \ | x_{0,j}=\frac{i}{\sqrt{\mathcal{E}}}\right]\\ &+\frac{1}{K}\sum_{j=1}^{K}\frac{1}{M}\mathbb{P}\left[\frac{\hat{x}_j}{B}-{ x}_{0,j}< -\frac{1}{\sqrt{\mathcal{E}}} \ | \ x_{0,j}=\frac{M-1}{\sqrt{\mathcal{E}}}\right]\\ &+\frac{1}{K}\sum_{j=1}^{K}\frac{1}{M}\mathbb{P}\left[\frac{\hat{x}_j}{B}-{ x}_{0,j}> \frac{1}{\sqrt{\mathcal{E}}} \ | \ x_{0,j}=-\frac{M-1}{\sqrt{\mathcal{E}}}\right].\\ \end{align*} Based on Corollary \ref{cor:indicator}, we have $$ {\rm SEP}-\widetilde{{\rm SEP}} \to 0, $$ where $\widetilde{{\rm SEP}}$ follows after some tedious but straightforward calculations and is given in \eqref{eq:SEP_BoX}. \begin{figure*} \begin{equation} \label{eq:SEP_BoX} \begin{aligned} \widetilde{\rm SEP}&=\frac{4}{M}\sum_{i=1,3,\dots,M-3}{\bf 1}_{\{\frac{t}{B}\geq\frac{i+1}{\sqrt{\mathcal{E}}}\}}Q\left(\frac{\xi\tilde{\theta}_\star}{\sqrt{\mathcal{E}}}\right)+\frac{2}{M}\sum_{i=1,3,\cdots,M-3}\left\{{\bf 1}_{\{\frac{i-1}{\sqrt{\mathcal{E}}}\leq \frac{t}{B}\leq \frac{i+1}{\sqrt{\mathcal{E}}}\}}Q\left(\frac{\xi\tilde{\theta}_\star}{\sqrt{\mathcal{E}}}\right)+{\bf 1}_{\{\frac{t}{B}\leq \frac{i-1}{\sqrt{\mathcal{E}}}\}}\right\}\\ &+\frac{2}{M}{\bf 1}_{\{\frac{t}{B}\geq \frac{M-2}{\sqrt{\mathcal{E}}}\}}Q\left(\frac{\xi\tilde{\theta}_\star}{\sqrt{\mathcal{E}}}\right)+\frac{2}{M}{\bf 1}_{\{\frac{t}{B}\leq \frac{M-2}{\sqrt{\mathcal{E}}}\}}. \end{aligned} \end{equation} \hrule \end{figure*} \section{Un-Boxed RLS Proofs}\label{sec:unbox} The analysis of the Un-Boxed RLS scheme is similar to the analysis of the Box-RLS. Below we provide a brief sketch of the proof. Following the same analysis as before, we identify the same (PO) and (AO) with the single difference that the constraints on $\left\{x_j \right\}_{j=1}^{K}$ are now removed. Particularly, the (AO) associated with the RLS writes as: \begin{align} \phi= & \ \underset{\beta > 0}{\operatorname{\max}} \ \underset{0\leq \tilde{\theta} \leq C}{\operatorname{\min}}\ \frac{ \beta \| {\bf g} \|^2}{2\tilde{\theta}K} + \frac{ \beta \tilde{\theta}}{2 } - \frac{\beta^2}{4} + \frac{\beta \tilde{\theta}\rho_{\mathsmaller{d}} \| {{\bf x}}_0 \|^2}{2 K} + \sqrt{\rho_{\mathsmaller{d}}} \beta \frac{1}{K}{{\bf x}}_0^{T} \tilde{{\bf h}} \nonumber \\ &+ \frac{1}{K}\sum_{j = 1}^{K} \biggl[ \underset{ x_j\in\mathbb{R}}{\operatorname{\min}} \ \biggl(\frac{\beta \tilde{\theta}\rho_{\mathsmaller{d}}\sigma_{\mathsmaller{\hat{H}}}^2}{2} + \lambda \rho_{\mathsmaller{d}} \biggr) x_j^2 - \beta \biggl( \rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2 {x}_{0,j}\tilde{\theta}+\sqrt{\rho_{\mathsmaller{d}}} \sigma_{\mathsmaller{\hat{H}}} q^{1}_{j} \biggr) {x}_j \biggr]. \end{align} which is similar to \eqref{AA23} with the difference that the optimization over $x_j$ is on the whole real axis. Optimizing over the variables $x_j,j=1,\cdots,K$, we thus obtain: \begin{align} \phi&= \ \underset{\beta > 0}{\operatorname{\max}} \ \underset{0\leq \tilde{\theta} \leq C}{\operatorname{\min}}\ \frac{ \beta \| {\bf g} \|^2}{2\tilde{\theta}K} + \frac{ \beta \tilde{\theta}}{2 } - \frac{\beta^2}{4} + \frac{\beta \tilde{\theta}\rho_{\mathsmaller{d}} \| {{\bf x}}_0 \|^2}{2 K} + \sqrt{\rho_{\mathsmaller{d}}} \beta \frac{1}{K}{{\bf x}}_0^{T} \tilde{{\bf h}}-\frac{1}{K}\sum_{j=1}^{K} \frac{\beta^2(\xi^2 x_{0,j}\tilde{\theta}+\xi q_j^{1})^2}{2\xi^2\beta\tilde{\theta}+4\lambda \rho_{\mathsmaller{d}}}. \label{eq:cost} \end{align} Using the same approach as that in the Box-RLS, we can prove that $\phi$ converges to: \begin{align} \phi\overset{P}{\rightarrow} \overline{\phi}:=\sup_{\beta>0} \inf_{\tilde{\theta}>0} \ \ &\frac{\beta \delta}{2\tilde{\theta}}+\frac{\beta\tilde{\theta}}{2}-\frac{\beta^2}{4} + \frac{\beta\tilde{\theta}\rho_{\mathsmaller{d}}}{2}-\frac{\beta^2\xi^2\tilde{\theta}^2+\xi^2}{2\xi^2\beta\tilde{\theta}+4\lambda\rho_{\mathsmaller{d}}}. \end{align} Using the change of variable $\theta=\frac{1}{\tilde{\theta}}$, this brings us to solve the following max-min problem: $$ \overline{\phi}=\sup_{\beta >0}\inf_{\theta>0}\beta\theta\frac{\delta}{2}+\frac{\beta}{2\theta}(1+\rho_{\mathsmaller{d}})-\frac{\beta^2}{4}-\frac{\beta^2\sigma_{\hat{\mathsmaller{H}}}^2}{\frac{2\beta\sigma_{\mathsmaller{H}}^2}{\theta}+4\lambda}(1+\frac{\rho_{\mathsmaller{d}}\sigma_{\hat{\mathsmaller{H}}}^2}{\theta^2}),$$ for which we prove that there exists a unique solution $(\theta_\star,\beta_\star)$. As a matter of fact, writing the first order optimality conditions, we obtain: \begin{subequations}\label{all_derv} \begin{align}\label{deriv_t} \delta \beta - \frac{\beta}{\theta^2}-\frac{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 \beta}{\theta^2} - \frac{\beta \sigma_{\mathsmaller{\hat{H}}}^2 (\beta^2 \sigma_{\mathsmaller{\hat{H}}}^2 + 4 \rho_{\mathsmaller{d}} \lambda^2 )}{( \beta \sigma_{\mathsmaller{\hat{H}}}^2 + 2 \lambda \theta )^2} = 0, \\ \label{deriv_b} \delta \theta + \frac{1}{\theta} - \beta + \frac{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2}{\theta} - \frac{\sigma_{\mathsmaller{\hat{H}}}^2 \theta(\beta^2\sigma_{\mathsmaller{\hat{H}}}^2 + 4 \lambda \theta \beta - 4 \rho_{\mathsmaller{d}}\lambda ^2)}{( \beta \sigma_{\mathsmaller{\hat{H}}}^2 + 2 \lambda \theta )^2} = 0. \end{align} \end{subequations} Combining the two equations together $\big(\frac{1}{ \beta}$ (\ref{deriv_t}) $+ \frac{1}{ \theta}$ (\ref{deriv_b})$\big)$, gives \begin{equation} \delta - \frac{\beta}{2 \theta} - \frac{\beta \sigma_{\mathsmaller{\hat{H}}}^2 }{ \beta \sigma_{\mathsmaller{\hat{H}}}^2 + 2 \lambda \theta } =0, \end{equation} which is equivalent to a second order polynomial in $\theta$, the solution of which is given by: \begin{equation}\label{eq:tau} \theta = \frac{1}{2 \lambda'} \Upsilon(\lambda', \delta) \beta, \end{equation} where, $\Upsilon(\lambda', \delta) = \frac{-(\delta - \lambda' -1)+\sqrt{(\delta - \lambda' -1)^2 + 4 \lambda' \delta}}{2 \delta}$, and $\lambda' = \frac{\lambda}{ \sigma_{\mathsmaller{\hat{H}}}^2}$. Substituting (\ref{eq:tau}) into (\ref{all_derv}) and after some algebraic manipulations, the unique solution $(\theta_\star,\beta_\star)$ of the system is \begin{subequations} \begin{align} \theta_\star = \sqrt{\frac{\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\hat{H}}}^2 \kappa^2+ \rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1 }{\delta-(1-\kappa)^2}}, \label{tau:eq} \\ \beta_\star = 2 \biggl( (\delta -\lambda' -1) + \delta \Upsilon(\lambda', \delta) \biggr) \theta_\star, \label{beta:eq} \end{align} \end{subequations} where $\kappa = \frac{\Upsilon(\lambda', \delta)}{1+ \Upsilon(\lambda', \delta)}$. Substituting $\kappa$ back gives the same expression as $\theta_\star$ in Theorem \ref{MSE-RLS}. {{Similar to the Box-RLS case, we can obtain the same MSE and SEP expressions as before. The only difference is that $\theta_\star$ and $\beta_\star$ are now given by the closed form expressions in (\ref{tau:eq}) and (\ref{beta:eq}) respectively.}} \section{Proof of \eqref{eq:HH}} \label{app:pp} To begin with, we perform the change of variable ${\bf s}=\sigma_{\hat{H}}{\bf x}-{\bf x}_0$. Function $\hat{\mathcal{H}}({\beta},{\bf x})$ can be lower-bounded as: \begin{align*} \hat{\mathcal{H}}({\beta},{\bf x})\geq & {\beta}\frac{\|{\bf g}\|}{\sqrt{K}}\sqrt{\rho_d} -\frac{\tilde{\beta}^2}{4}-\tilde{\beta}\sqrt{\rho_d}\frac{{\bf s}^{T}{\bf q}^{\bf 1}}{K}-{\beta}\sqrt{\rho_d} \frac{{\bf x}_0^{T}{\bf q}^{\bf 1}}{K} +{\beta}\sqrt{\rho_{\mathsmaller{d}}} \frac{1}{K}{\bf x}_0^{T}\tilde{\bf h} +\frac{\lambda \rho_d}{\sigma_{\hat{H}}^2} \frac{1}{K}\left(\|{\bf s}\|^2+\|{\bf x}_0\|^2+2{\bf s}^{T}{\bf x}_0\right). \end{align*} Denote by $\kappa$ the norm of $\frac{1}{\sqrt{K}}\|{\bf s}\|$. Minimizing the lower-bound over ${\bf s}$, we obtain: \begin{align*} \hat{\mathcal{H}}({\beta},{\bf x})\geq \min_{\kappa\geq 0} & \tilde{\beta}\frac{\|{\bf g}\|}{\sqrt{K}}\sqrt{\rho_{\mathsmaller{d}}}-\frac{{\beta}^2}{4}-{\beta}\sqrt{\rho_d}\frac{{\bf x}_0^T{\bf q}^{\bf 1}}{K} +\tilde{\beta}\sqrt{\rho_d}\frac{1}{K}{\bf x}_0^{T}\tilde{\bf h}\\ &+\frac{\lambda\rho_{\mathsmaller{d}}}{\sigma_{\hat{\mathsmaller{H}}}^2} \kappa^2 +\frac{\lambda\rho_{\mathsmaller{d}}}{\sigma_{\hat{H}}^2} \|{\bf x}_0\|^2-\kappa \left\|\tilde{\beta}\sqrt{\rho_d}\frac{1}{\sqrt{K}}{\bf q}^{\bf 1}-2\frac{\lambda \rho_{\mathsmaller{d}}}{\sqrt{K}\sigma_{\hat{\mathsmaller{H}}}^2}{\bf x}_0 \right\| \\ &={{\beta}}\frac{\|{\bf g}\|}{\sqrt{K}}\sqrt{\rho_{\mathsmaller{d}}}-\frac{{\beta}^2}{4}-{\beta}\sqrt{\rho_{\mathsmaller{d}}}\frac{{\bf x}_0^T{\bf q}^{\bf 1}}{K} +{\beta}\sqrt{\rho_{\mathsmaller{d}}}\frac{1}{K}{\bf x}_0^{T}\tilde{\bf h} +\frac{\lambda \rho_{\mathsmaller{d}}}{\sigma_{\hat{\mathsmaller{H}}}^2}\|{\bf x}_0\|^2 -\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda \rho_{\mathsmaller{d}} K} \|2\frac{\lambda\rho_{\mathsmaller{d}}}{\sigma_{\hat{\mathsmaller{H}}}^2}{\bf x}_0-{\beta}\sqrt{\rho_{\mathsmaller{d}}}{\bf q}^{\bf 1}\|^2. \end{align*} In the asymptotic regime with $K$ and $N$ tending to infinity, and taking ${\beta}$ as fixed, the right-hand side of the above equation converges to: $$ {\beta}\sqrt{\rho_d}\sqrt{\delta }-\frac{{\beta^2}}{4}-{\beta}^2\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda}, $$ which simplifies to $\frac{\rho_{\mathsmaller{d}}\delta}{1+\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda}} $ when ${\beta}$ is replaced by ${\beta}_0:=\frac{2\sqrt{\rho_{\mathsmaller{d}}}\sqrt{\delta}}{1+\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda}}$. We thus obtain almost surely $$ \hat{\mathcal{H}}({\beta}_0,{\bf x})\geq \frac{1}{2}\frac{\rho_{\mathsmaller{d}}\delta}{1+\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda}}, $$ and as such, almost surely, $$ \min_{\substack{-t\leq x_j\leq t\\ j=1,\cdots,K}}\hat{\mathcal{H}}({\beta}_0,{\bf x})\geq \frac{1}{2}\frac{\rho_{\mathsmaller{d}}\delta}{1+\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda}}. $$ Setting $\Theta=\frac{1}{2}\frac{\rho_{\mathsmaller{d}}\delta}{1+\frac{\sigma_{\hat{\mathsmaller{H}}}^2}{4\lambda}}$ ends up the proof of \eqref{eq:HH}. \section{{ Monotonicity of the MSE and SEP of the RLS decoder}}\label{Azx} We showed that for the LS case, optimizing the power allocation in MSE sense is equivalent to optimizing the SEP and it boils down to maximizing $\rho_{\text{eff}}$. In this appendix, we will show that this holds also true for the RLS decoder that employs optimal regularization coefficient. Towards this goal, we proceed with the following change of variables $J=\frac{1}{\rho_\text{eff}}, c_1 = 2 (1+\delta)$, and $c_2 =(1-\delta)^2$. Then, the MSE and SEP write as: \begin{align} \widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}}&=\frac{1}{2}\bigg( -J +(1-\delta) +\sqrt{J^2+c_1 J+c_2}\bigg),\label{eq:MSE_RLS}\\ \widetilde{\rm{ SEP}}_{\text{\tiny{RLS}}}&=2\left(1-\frac{1}{M}\right) Q\left(\sqrt{\frac{\delta}{\mathcal{E}\left(\frac{1}{2}\bigg( J +(1-\delta) +\sqrt{J^2+c_1 J+c_2}\bigg)\right)}}\right).\label{eq:SER_RLS} \end{align} It appears from \eqref{eq:MSE_RLS} and \eqref{eq:SER_RLS} that to minimize the MSE or the SEP, it suffices to minimize for all $i\in\left\{0,1\right\}$, function $\mathcal{F}_i(J)=(-1)^i J+ \sqrt{J^2+c_1J+c_2}$. We can check easily that the first derivative of $\mathcal{F}_i$ is given by: $\mathcal{F}_i^{'}(J)=(-1)^{i}+\frac{2J+c_1}{2\sqrt{J^2+c_1J+c_2}}$ which is strictly positive for all $i\in\{0,1\}$. It follows thus that both $\widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}}$ and $\widetilde{\rm{ SER}}_{\text{\tiny{RLS}}}$ are increasing functions of $\frac{1}{\rho_{\text{eff}}}$ and hence minimizing them amounts to maximizing $\rho_{\text{eff}}$. Then, $\widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}} =\frac{1}{2}\bigg( -J +(1-\delta) +\sqrt{J^2+c_1 J+c_2}\bigg)$. On the other hand, from \eqref{SER_MSE_RLS}, it is clear that to minimize the SEP we need to maximize the argument of the $Q$-function, which means to minimize $\widetilde{\rm{ MSE}}_{\text{\tiny{RLS}}} +J$. \section{Optimal Power Allocation Derivation: Proof of Theorem~\ref{Power_Th}}\label{power_proof} Here, we derive the optimal power allocation given in Theorem~\ref{Power_Th}. First, rewrite $\rho_\text{eff}$ as follows \begin{align*} \rho_\text{eff}&= \frac{\alpha \rho \frac{\tau}{\tau_\mathsmaller{d}}. (1-\alpha) \rho \tau}{(1+ \alpha \rho\frac{\tau}{\tau_\mathsmaller{d}}) + (1- \alpha)\rho \tau} \nonumber \\ & =\frac{(\rho \tau)^2}{\tau_\mathsmaller{d}} \cdot \frac{\alpha (1-\alpha)}{1+ \rho \tau - \alpha \rho \tau (1 - \frac{1}{\tau_\mathsmaller{d}}) } \nonumber \\ & = \frac{\rho \tau}{\tau_\mathsmaller{d} -1} \cdot \frac{\alpha (1- \alpha)}{-\alpha + \frac{1 + \rho \tau}{\rho \tau(1- \frac{1}{\tau_\mathsmaller{d}})}}. \end{align*} We need to maximize $\rho_\text{eff}$ over $0< \alpha <1$. To do so, we consider the following cases:\\ 1) $\tau_\mathsmaller{d} =1$: \begin{align*} \rho_\text{eff} = \frac{(\rho \tau)^2}{1 + \rho \tau} \alpha (1-\alpha). \end{align*} In this case, $\alpha_\star = \frac{1}{2}$.\\ 2) $\tau_\mathsmaller{d} >1$: \begin{align*} \rho_\text{eff} = \frac{\rho \tau}{\tau_\mathsmaller{d} -1} \cdot \frac{\alpha (1-\alpha)}{-\alpha +\vartheta}, \quad \vartheta = \frac{1+\rho \tau}{\rho \tau(1- \frac{1}{\tau_\mathsmaller{d}})} >1. \end{align*} Hence, the optimal $\alpha_\star$ that maximizes $\rho_{\text{eff}}$ is given by: \begin{align*} \alpha_\star &= \argmax_{\substack{0<\alpha<1 \\ \vartheta>1}} \frac{\alpha(1-\alpha)}{-\alpha+ \vartheta} \\ &= \vartheta -\sqrt{\vartheta(\vartheta-1)}. \end{align*} 3) $\tau_\mathsmaller{d} <1$: \begin{align*} \rho_\text{eff} = \frac{\rho \tau}{1-\tau_\mathsmaller{d} } \cdot \frac{\alpha (1-\alpha)}{\alpha -\vartheta}, \quad \vartheta = \frac{1+\rho \tau}{\rho \tau(1- \frac{1}{\tau_\mathsmaller{d}})} <0. \end{align*} In this case, we have \begin{align*} \alpha_\star &= \argmax_{\substack{0<\alpha<1 \\ \vartheta<0}} \frac{\alpha(1-\alpha)}{\alpha- \vartheta} \\ &= \vartheta +\sqrt{\vartheta(\vartheta-1)}. \end{align*} \section{Optimal Power and Training Time Allocation Derivation based on Goodput}\label{goodput_proof} In this section, we determine the optimal power and training time allocation that optimizes the asymptotic value of the goodput for LS decoder which we denote here by $\widetilde{G}_{LS}$. To this end, we proceed with the change of variable $ \gamma = \frac{T_\mathsmaller{p}}{T}$. Then, $\tau_\mathsmaller{p} =\frac{T_\mathsmaller{p}}{K} = \frac{T_\mathsmaller{p}}{T} $, $ \frac{T}{K} = \gamma \tau, \delta' = \frac{\delta-1}{\mathcal{E}}$, $\rho_\mathsmaller{p} = \frac{(1-\alpha) \rho}{\gamma}$, and $\rho_\mathsmaller{d} = \frac{\alpha \rho}{1-\gamma}$. The SEP for LS case is \begin{align*} \widetilde{\text{SEP}}_{\tiny{\text{LS}}} &= 2(1- \frac{1}{M}) Q \bigg(\sqrt{\frac{\delta -1}{\mathcal{E}} \rho_{\text{eff}}}\bigg) \\ & = 2(1- \frac{1}{M}) Q \bigg(\sqrt{\frac{\delta -1}{\mathcal{E}} \cdot \frac{\rho_\mathsmaller{d} \rho_\mathsmaller{p} \tau_\mathsmaller{p}}{1+ \rho_\mathsmaller{d} + \rho_\mathsmaller{p} \tau_\mathsmaller{p}}}\bigg)\\ & = 2(1- \frac{1}{M}) Q \bigg(\sqrt{\frac{\delta -1}{\mathcal{E}} \cdot \frac{\frac{\alpha \rho}{1-\gamma} \frac{(1-\alpha) \rho}{\gamma} \gamma \tau}{1+ \frac{\alpha \rho}{1-\gamma}+ \frac{(1-\alpha)\rho}{\gamma} \gamma \tau} }\bigg)\\ & =2\big(1- \frac{1}{M}\big) Q \bigg(\sqrt{ \frac{\delta' \alpha (1-\alpha) \rho^2 \tau}{1+\alpha \rho +(1-\alpha) \rho \tau - \gamma (1 +(1-\alpha) \rho \tau)}}\bigg) \\ &= 2\big(1- \frac{1}{M}\big) Q \bigg(\sqrt{\frac{\frac{\delta' \alpha (1-\alpha) \rho^2 \tau}{1 +(1-\alpha) \rho \tau}}{\frac{1+ \alpha \rho +(1-\alpha) \rho \tau}{1 +(1-\alpha) \rho \tau} - \gamma}} \bigg)\\ & = \widetilde{M} Q \bigg(\sqrt{\frac{b(\alpha)}{a(\alpha) -\gamma}} \bigg), \end{align*} where $\widetilde{M} = 2\big(1- \frac{1}{M}\big), a(\alpha)= \frac{1+ \alpha \rho +(1-\alpha) \rho \tau}{1 +(1-\alpha) \rho \tau}>1$ , and $b(\alpha) = \frac{\delta' \alpha (1-\alpha) \rho^2 \tau}{1 +(1-\alpha) \rho \tau}>0$. The asymptotic goodput become \begin{align*} \widetilde{G}_{\tiny{\text{LS}}}(\alpha,\gamma) &= (1- \gamma) (1- \widetilde{\text{SEP}}_{\tiny{\text{LS}}})\\ & =(1-\gamma)\bigg(1- \widetilde{M} Q\bigg(\sqrt{\frac{b(\alpha)}{a(\alpha) -\gamma}} \bigg) \bigg). \end{align*} The power allocation problem amounts thus to solving: \begin{equation} (\alpha_\star,\gamma_\star) = \argmax_{\substack{0 < \alpha < 1 \\ \frac{1}{\tau} \leq \gamma < 1}} \widetilde{G}_{\tiny{\text{LS}}}(\alpha,\gamma), \end{equation} Recall that we need $T_{\mathsmaller{p}} \geq K$ or $\tau_{\mathsmaller{p}} \geq 1$, but $\tau_{\mathsmaller{p}} = \gamma \tau$, hence $\gamma \geq \frac{1}{\tau}$. We also require $T_{\mathsmaller{p}} < T$, hence $\gamma <1$. This justifies the constraint imposed on $\gamma$ above.\\ To begin with, it is easy to see that the optimal $\alpha$ is the one that maximizes $\rho_{\rm eff}$ and this is for any $\gamma$. It remains thus to optimize the goodput in terms of $\gamma$. We will solve this by proving that the good-put is a decreasing function with respect to $\gamma$. To proceed, let us make the change of variables: $x =\sqrt{\frac{b}{a-\gamma}}$, then $\gamma = a -\frac{b}{x^2}$. Hence, for any $0<\alpha<1$, the goodput is \begin{equation*} \widetilde{G}_{\rm LS}(\alpha,\gamma) = \overline{G}_{\text{\tiny LS}}(x):=\bigg(1- a +\frac{b}{x^2} \bigg) \bigg(1- \widetilde{M} Q(x)\bigg). \end{equation*} Taking the derivative of $\overline{G}_{\tiny{\text{LS}}}(x)$ with respect to $x$ yields \begin{align*} \overline{G}_{\tiny{\text{LS}}}'(x) &=\frac{-2 b}{x^3}\bigg(1- \widetilde{M} Q(x)\bigg) + \bigg(1- a +\frac{b}{x^2}\bigg)\bigg(\frac{\widetilde{M}}{\sqrt{2 \pi}} e^{\frac{-x^2}{2}}\bigg)\\ & = \widetilde{M} e^{\frac{-x^2}{2}}\bigg[\frac{-2 b}{x^3}e^{\frac{x^2}{2}}\bigg(\frac{1}{\widetilde{M} }- Q(x)\bigg) + \frac{1}{\sqrt{2 \pi}}\bigg(1- a +\frac{b}{x^2}\bigg) \bigg]. \end{align*} We need to study the sign of $\overline{G}_{\tiny{\text{LS}}}'(x)$. To do so, first write the Taylor series expansion of $e^{\frac{x^2}{2}}\bigg(\frac{1}{\widetilde{M}}- Q(x)\bigg)$ as:\\ $e^{\frac{x^2}{2}}\bigg(\frac{1}{\widetilde{M}}- Q(x)\bigg) = \frac{1}{2(M-1)} + \frac{x}{\sqrt{2 \pi}} + \frac{x^2}{4(M-1)}+ \cdots$, then \begin{align*} \overline{G}_{\tiny{\text{LS}}}'(x) &= \widetilde{M} e^{\frac{-x^2}{2}}\bigg[ \frac{-b}{(M-1) x^3}- \frac{b}{\sqrt{2 \pi} x^2} -\frac{b}{4(M-1) x}+ \cdots +\frac{1}{\sqrt{2 \pi}} (1- a) \bigg]. \end{align*} Recall that $a>1$ and note that all the terms in $\overline{G}_{\tiny{\text{LS}}}'(x)$ expression above are negative. Hence, $\overline{G}_{\tiny{\text{LS}}}'(x)<0$ for all $\alpha$. Now, by the chain rule: $\frac{{\rm d} \overline{G}_{\tiny{\text{LS}}}}{{\rm d} x} = \frac{d \overline{G}_{\tiny{\text{LS}}}}{{\rm d} \gamma}\cdot \frac{{\rm d} \gamma}{{\rm d} x}$, but $\frac{{\rm d} \gamma}{{\rm d} x} =\frac{2 b}{x^3}>0$, then $\frac{{\rm d} \overline{G}_{\tiny{\text{LS}}}}{{\rm d} \gamma}<0$.\\ Hence, $\frac{\partial {G}_{\tiny{\text{LS}}}(\alpha, \gamma)}{\partial \alpha}<0$ for any $\alpha$. This suggests that we choose $\gamma$ as small as possible to maximize $\widetilde{G}_{\tiny{\text{LS}}}(\alpha, \gamma)$.\\ So, $\gamma_\star = \frac{1}{\tau}$. Or, $\tau_{\mathsmaller{p}}^{\star} = \gamma_\star \tau$, then $\tau_{\mathsmaller{p}}^{\star} =1.$\\ The proof above is done for LS but the same conclusions hold for both RLS and also for the Box-RLS under the conjecture that for Box-RLS, the optimal $\alpha$ is the one that maximizes $\rho_{\rm eff}$. We omit details for briefness. \section{Comparison with the LMMSE Decoder}\label{LMMSE_Append} In this appendix we will show that the LMMSE estimator of ${\bf x}_0$ is equivalent to an RLS estimator with the optimal regularizer $\lambda_\star = \frac{1}{\rho_\mathsmaller{d}}+ \sigma_{\mathsmaller{\Delta}}^2$. The LMMSE estimate of ${\bf x}_0$ is given by \cite{kay1993fundamentals} \begin{equation} \widehat{{\bf x}}_{\text{LMMSE}} = {\bf C}_{x y} {\bf C}_{y y}^{-1} {\bf y}, \end{equation} where $ {\bf C}_{x y} = \mathbb{E} [ ({\bf x}_0 -\mathbb{E}[{\bf x}_0]) ({\bf y} -\mathbb{E}[{\bf y}])^T]$, and $ {\bf C}_{y y} = \mathbb{E} [ ({\bf y} -\mathbb{E}[{\bf y}]) ({\bf y} -\mathbb{E}[{\bf y}])^T]$. It can be shown that $\mathbb{E}[{\bf y}] =\mathbb{E}[{\bf x}_0] = \mathbf{0}$, and \begin{equation} {\bf C}_{x y} = \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \widehat{{\bf H}}^T. \end{equation} To find $ {\bf C}_{y y}$, let us write ${\bf y}$ as \begin{align} {\bf y}=& \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} (\widehat{{\bf H}}+\hbox{\boldmath$\Delta$}) {\bf x}_0 +{\bf z}, \nonumber \\ =&\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \widehat{{\bf H}} {\bf x}_0 +\widetilde{{\bf z}}, \end{align} where $\widetilde{{\bf z}} \triangleq \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \hbox{\boldmath$\Delta$} {\bf x}_0 +{\bf z}$ which is a zero-mean vector with ${\bf C}_{\tilde{z} \tilde{z}} =\frac{\rho_{\mathsmaller{d}}}{K}\mathbb{E}_\mathsmaller{{{\bf x}_0,\Delta}}[\hbox{\boldmath$\Delta$}{\bf x}_0 {\bf x}_0^T \hbox{\boldmath$\Delta$}^T]+{\bf C}_{zz}=\frac{\rho_{\mathsmaller{d}}}{K}\mathbb{E}_\mathsmaller{{\Delta}}[\hbox{\boldmath$\Delta$} \mathbb{E}_{{\bf x}_0}[{\bf x}_0 {\bf x}_0^T] \hbox{\boldmath$\Delta$}^T]+{\bf C}_{zz}=\frac{\rho_{\mathsmaller{d}}}{K}\mathbb{E}_\mathsmaller{{\Delta}}[\hbox{\boldmath$\Delta$} {\bf C}_{x x} \hbox{\boldmath$\Delta$}^T]+{\bf C}_{zz} =\frac{\rho_{\mathsmaller{d}}}{K}\mathbb{E}_\mathsmaller{{\Delta}}[\hbox{\boldmath$\Delta$} \hbox{\boldmath$\Delta$}^T]+{\bf I}_N=(\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1) {\bf I}_N$, then, \begin{equation} {\bf C}_{y y} =\frac{\rho_{\mathsmaller{d}}}{K} \widehat{{\bf H}} \widehat{{\bf H}}^T +(\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1) {\bf I}_N. \end{equation} Note that we used ${\bf C}_{xx} ={\bf I}_K$, ${\bf C}_{zz} ={\bf I}_N$, and $\mathbb{E}[\hbox{\boldmath$\Delta$} \hbox{\boldmath$\Delta$}^T]= K\sigma_{\mathsmaller{\Delta}}^2 {\bf I}_N$.}\\ Hence, \begin{align}\label{LMMSE_a} \widehat{{\bf x}}_{\text{LMMSE}} =& \sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \widehat{{\bf H}}^T \bigg(\frac{\rho_{\mathsmaller{d}}}{K} \widehat{{\bf H}} \widehat{{\bf H}}^T + (\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1) {\bf I}_N \bigg)^{-1} {\bf y}, \nonumber\\ =&\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \bigg(\frac{\rho_{\mathsmaller{d}}}{K} \widehat{{\bf H}}^T \widehat{{\bf H}} + (\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 +1) {\bf I}_K \bigg)^{-1} \widehat{{\bf H}}^T {\bf y}, \nonumber \\ =& \big({\bf A}^T {\bf A} +(1+\rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2 ){\bf I}_K \big)^{-1} {\bf A}^T {\bf y}, \end{align} where ${\bf A} =\sqrt{\frac{\rho_{\mathsmaller{d}}}{K}} \widehat{{\bf H}}$, and the second equality follows from the \emph{matrix inversion Lemma}. The LMMSE estimate in \eqref{LMMSE_a} is equivalent to the RLS solution as given in \eqref{eq:LS matrixb} with $\lambda \rho_{\mathsmaller{d}} = \lambda_\star \rho_{\mathsmaller{d}}= 1+ \rho_{\mathsmaller{d}} \sigma_{\mathsmaller{\Delta}}^2$. This shows that the RLS with optimal regularizer is nothing but the popular LMMSE decoder. Finally, the LMMSE estimate can be written in terms of $\widehat{{\bf H}}$ as \begin{align} \widehat{{\bf x}}_{\text{LMMSE}} &=\sqrt{\frac{K}{\rho_{\mathsmaller{d}}}} \bigg( \widehat{{\bf H}}^T \widehat{{\bf H}} + \frac{\sigma_{\mathsmaller{\hat{H}}}^2}{\rho_{\text{eff}}} K {\bf I}_K \bigg)^{-1} \widehat{{\bf H}}^T {\bf y} \nonumber \\ & = \widehat{{\bf x}}_{\text{RLS}}(\lambda_\star). \end{align} \newpage \clearpage \bibliographystyle{IEEEbib}
{'timestamp': '2022-06-08T02:03:55', 'yymm': '2008', 'arxiv_id': '2008.06993', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06993'}
arxiv
\section{Introduction} \label{sec:introduction} Frailty models is a useful and flexible class of models that allow the inclusion of latent effects related to an individual or a group in order to accommodate possible non-observed covariates. The most simple way to introduce a frailty term in a model is through an unstructured effect ensuring that the hazard is always positive for all sample units. However this approach does not handle with structured effects including the case of spatial data. Papers as \citet{henderson2002modeling}, \citet{li2002modeling} and \citet{banerjee2003frailty} propose the use of frailty models to incorporate spatial structure into the latent effects. The latter used consolidated spatial models as the conditional autoregressive model (CAR) \citep{besag1974spatial} for areal data and the Gaussian model for georeferenced data \citep{cressie1992statistics}. Spatial models are widely studied in the literature and are important in practice to modeling spatially correlated data. In addition to the development of robust models, there are works focused on identifying (and solving) any limitations of such kind of approach. A possible limitation of spatial models is the spatial confounding \citep{reich2006effects, hughes2013dimension, hanks2015restricted, thaden2018structural, prates2018alleviating}. This problem resembles the multicollinearity in linear models that can distort the results and even lead to wrong conclusions. Spatial confounding occurs when the spatial effect brings similar information to that coming from the fixed effects. Thus, the point estimate of the regression coefficient related to the covariate becomes biased and leads to variance inflation. Advances in technology, data storage and data quality allow the fitting of increasingly complex models aiming for better fit and more interpretability. To the best of our knowledge the spatial confounding in frailty models for areal data is an unexplored field which needs attention due to the importance of such models mainly for health sciences. The usual approaches for areal data cannot be directly applied for such kind of model as a result of the difference in the support of the spatial structure (areal level) and the fixed effects (sample unit level). Moreover in some applications there is a huge number of individuals in each area which leads to a computational challenge using this models' family. In this paper we provide a tool to alleviate the impact of spatial confounding in frailty models that works for a wide list of basal hazard functions and censoring schemes. The computational limitation is overcame using a trick that allow us to relief the spatial confounding issue using a reduction of the data dimension instead of working in the original one. We also propose a variance inflation factor (VIF) measure through the posterior sample of the spatial model (restricted and unrestricted). This measure allow us to validate the existence of spatial confounding and identify the covariates that are affect. As an application we have the lifetime of 72,612 individuals suffering from respiratory cancer (lung and bronchus) in California - US. This dataset is provided by SEER (surveillance, epidemiology, and end results program) \citep{seer}. This paper is organized as follows. In section (\ref{sec:data_sources}) we present the dataset used in this work. In section (\ref{sec:methodology}) we have a review of spatial frailty models and spatial confounding. We show the proposed solution theory and the mathematical challenges of the restricted spatial frailty models in section (\ref{sec:restricted_spatial_frailty_models}). For model check and illustration, simulations and an application to the SEER respiratory cancer are performed in sections (\ref{sec:simulation}) and (\ref{sec:application}) respectively. Section (\ref{sec:final_remarks}) is reserved for conclusion and general discussion about the model and future work. \section{Bronchus and lung cancer in California - US} \label{sec:data_sources} According to the Surveillance, Epidemiology, and End Results Program (SEER) \citet{seer}, lung and bronchus cancer reaches about $220.000$ men and women per year in the US. Just $20\%$ of them are expected to be alive five years after diagnosis. Therefore, it is disease with high mortality rates that must be investigated carefully. Our goal is to model the time until death by lung and bronchus cancer in California - US. To motivate our contributions we use individual-level as well as areal-level covariates to characterize individuals and regions in study. Therefore, two main data sources are in use in our analysis and are described below. \subsection{Datasets} To add county-level information we are using the County Health Rankings \& Roadmaps (CHRR) \citep{chrr} which provides several important indices collected from different sources in the US. The CHRR is provided by the University of Wisconsin, Population Health Institute and is used to include inputs that describe characteristics of each California's county. The proportion of adults that smoke every day or most days between 2010 and 2016 for every California's county is accounted as an important risk factor for our analysis. Additional information about covariates as well as the dataset can be obtained in the CHRR website \href{https://www.countyhealthrankings.org/}{https://www.countyhealthrankings.org/}. The main database in this work is provided by the SEER. The SEER program collects data on cancer cases from several locations and sources since 1973 in the United States. The data is provided by the National Cancer Institute (NHI) the American national leader in cancer research. The SEER datasets are not publicly available for free download. However, it can be requested following NIH/NCI SEER data access options via the link \href{https://seer.cancer.gov/data/options.html}{https://seer.cancer.gov/data/options.html}. \subsection{Time until death by bronchus and lung cancer} The data set provided by SEER has cases of lung and bronchus cancer for 72,612 individuals (between 2010 and 2016 after data cleaning) in the California state. In this data set, important covariates are present as gender and the stage of the disease for each individual. However, important covariates are missing as the case of tobacco consumption. To work around this problem, we are using the areal level covariate that indicates the percentage of adults that smoke every day or most days in each county. Because people can start in the program in different years (2010 - 2016), we picked the corresponding annual statistic in the CHRR dataset to be a proxy of how likely the person is a smoker. Table~\ref{tab:survival_covariates} presents some summary information about the individual covariates used from the SEER program as well as the areal level covariate. Continuous covariates are represented by median (quantiles 25\% and 75\%) and categorical variables are represented by its observed proportion. \begin{table}[hhh] \centering \caption{Summary statistics of SEER and CHRR covariates. For categorical variables the sample size and the percentage. For continuous variables median and quantiles 25\% and 75\%.} \label{tab:survival_covariates} \begin{tabular}{@{}ll@{}} \toprule Variable & N = 72612 \\ \midrule Time until event/censure & 10.0 [4.00; 25.0] \\ Status & \\ ~~~~ 0 & 31013 (42.7\%) \\ ~~~~ 1 & 41599 (57.3\%) \\ Gender & \\ ~~~~ Female & 34625 (47.7\%) \\ ~~~~ Male & 37987 (52.3\%) \\ Race & \\ ~~~~ Non-black & 66723 (91.9\%) \\ ~~~~ Black & 5889 (8.11\%) \\ Cancer stage & \\ ~~~~ In situ & 519 (0.71\%) \\ ~~~~ Localized & 15870 (21.9\%) \\ ~~~~ Regional & 16792 (23.1\%) \\ ~~~~ Distant & 39431 (54.3\%) \\ Age at diagnosis & 69.0 [62.0; 77.0] \\ \% Smokers & 0.14 [0.12; 0.15] \\ \bottomrule \end{tabular} \end{table} The time is measured in months being the median 10 months. The time variable was scaled (time/max$\{$time$\}$) in our models to avoid computational instabilities. For each individual, we assign a status of 1 if the individual died by lung or bronchus cancer and zero if the individual died by other causes or is still alive. Therefore, it can be seen as a right censoring scheme with about 43\% censured cases. Given the current dataset structure, it can be seen as a type I censoring scheme. In our sample we have more cases of lung and bronchus cancer for men than for women as expected following the literature \citep{seer}. For simplicity the race variable was coded as black and non-black for each individual. ``In situ'' refers to abnormal cells that are present in the lung or bronchus but have not spread to nearby. ``Located'' corresponds to the stage where the cancer is limited to where it started and has not spread yet. In the ``regional'' phase, cancer has spread to nearby lymph nodes or organs. The last and more severe phase is the ``distant'' stage. In the ``distant'' stage, cancer has spread to distant parts of the body. Therefore, we expect an increase in the risk of death following this logical order. Finally, the median age is 69, which corresponds to an elderly population. \section{Methodology} \label{sec:methodology} \subsection{Spatial models}\label{sec:spatial_models} Modeling the sources of variation is important for countless fields and can help researchers identifying spatial patterns and make decisions. In many cases, the data is spatially structured which makes the models capable of identifying the influence of these structures indispensable. In Statistics the most common types of spatial data are those in which observations are collected in a continuous space (geostatistical data) or when they represent a region in space (areal data). In the areal data context, it is commonly incorporated the neighborhood structure information into modeling to capture the spatial heterogeneity. This is done to capture the spatial behavior of a possible unobserved or latent covariate. There are several approaches for modeling spatially structured data in the areal context as the cases of conditional autoregressive (CAR) \citep{besag1974spatial, banerjee2014hierarchical}, simultaneous autoregressive (SAR) \citep{whittle1954stationary, ord1975estimation}, Leroux \citep{leroux1999estimation}, mixture neighborhood structure \citep{rodrigues2012bayesian} and, directed acyclic graph autoregressive (DAGAR) \citep{datta2018spatial}. In applied sciences, the most common approach for areal data is the Intrinsic CAR (ICAR) \citep{besag:york:mollie} model due to the model simplicity. Although any of the mentioned methodologies are valid and can be easily explored in our framework, in this work we adopt the ICAR model. Let $Y_1, \ldots, Y_n$, random variables observed in $n$ areas and take $\mathbf{\Theta} = \PC{\theta_1, \ldots, \theta_n}^T$, random effects with zero mean, related to each location. The traditional ICAR defined by CAR($1$, $\frac{1}{\sigma^2}$) model defines the conditional distributions as \begin{equation*} \label{eq:car_improper} \PC{\theta_i|\mathbf{\theta_{-i}}} \sim N\PC{\sum_{j \sim i}\frac{\theta_j}{w_{i+}}, \frac{\sigma^2}{w_{i+}}}, \end{equation*} where $\mathbf{\theta_{-i}}$ represents the vector $\mathbf{\Theta}$ except the element $\theta_i$, and $j\sim i$ indicates that the areas $i$ and $j$ are neighbors. $\mathbf{W}$ is the adjacency matrix, where $w_{ij} = 1$ if and only if $i$ and $j$ are neighbors and $0$ elsewhere. The notation $w_{i+}$ indicates the sum of the elements of the $i_{th}$ line of $\mathbf{W}$, and therefore represents the number of neighbors in the $i_{th}$ region. If we change the expected mean to $\displaystyle \sum_{j\sim i}\rho\frac{\theta_j}{w_{i+}}$ this model is called CAR($\rho$, $\frac{1}{\sigma^2}$) and $\rho$ is the spatial dependence parameter responsible to indicates the dependence intensity between regions \citep{banerjee2014hierarchical}. The CAR dependence matrix structure is given by $\bm{Q} = \tau(\bm{D_w} - \rho\bm{W})$ where $\tau = \frac{1}{\sigma^2}$ and $\bm{D_w}$ is a diagonal matrix with entries $w_{i+}$ representing the number of neighbors of each region. The ICAR prior model is obtained by setting $\rho = 1$. \subsection{Spatial confounding}\label{sec:spatial_confounding} A current limitation in spatial statistics is the so-called spatial confounding. This problem resembles what occurs in linear models when two or more covariates bring the same information about the response variable. In linear models, this is called multicollinearity and inflates the variance of the regression coefficient estimators. This inflation, in some cases, changes the model interpretation leading the researcher, occasionally, to get to wrong conclusions about the necessity and importance of the covariate in the model. An extension of the multicollinearity problem to the spatial context is the so called spatial confounding and it occurs when the spatial effect brings similar information to one or a linear combination of the covariates in the model. Differently from the multicollinearity, spatial confounding determines an inflation in the variance of the regression estimators and also a bias in the point estimate, possibly changing conclusions drastically \citep{reich2006effects}. Recently, several works as \citep{reich2006effects, hughes2013dimension, hanks2015restricted, hefley2017bayesian, guan2018computationally, thaden2018structural, prates2018alleviating} approached the spatial confounding problem either for generalized linear mixed models areal or geostatistical data. \cite{reich2006effects} mathematically formulated the problem of spatial confounding for spatial linear regression models. The authors employed the ICAR prior in the following modelling: \begin{align} \label{eq:reich_model} & \bm{Y}|\bm{\beta}, \bm{\psi}, \tau_{\epsilon} \sim \text{Normal}(\bm{X\beta} + \bm{\psi}, \tau_{\epsilon}\bm{I}_n), \\ & \bm{\psi}|\tau_{\psi} \sim \text{Normal}(0, \tau_{\psi}\bm{Q}), \nonumber \end{align} \noindent where $\bm{\psi}$ is the ICAR spatial effect, $\bm{Q}$ is the ICAR precision matrix aforementioned, $\tau_{\epsilon}$ and $\tau_{\psi}$ are precision parameters related to the Gaussian observations and the ICAR, respectively. Note that in our parametrization the Gaussian distribution is being represented by its precision matrix rather than its covariance matrix. In the case of spatial linear regression, it is possible to analytically calculate the expected mean and variance integrating out the latent effect as: \begin{align} \label{eq:reich_model_mean_variance} & E(\bm{\beta}|\tau_{\epsilon}, \tau_{\psi}, \bm{y}) = \displaystyle (\bm{X^TX})^{-1}\bm{X}^T(\bm{y} - \hat{\bm{\psi}}) = \bm{\beta}_{ols} - (\bm{X^TX})^{-1}\bm{X}^T\hat{\bm{\psi}}, \\ & Var^{-1}(\bm{\beta}|\tau_{\epsilon}, \tau_{\psi}, \bm{y}) = \displaystyle \tau_{\epsilon}(\bm{X^TX}) - \bm{X}^T Var(\bm{\psi}|\bm{\beta}, \tau_{\epsilon}, \tau_{\psi}, \bm{y})\bm{X}, \nonumber \end{align} where $\bm{\beta}_{ols} = (\bm{X^TX})^{-1}\bm{X}^T\bm{y}$ and $\hat{\bm{\psi}} = E(\bm{\psi}|\tau_{\epsilon}, \tau_{\psi}, \bm{y})$. Carefully investigating Equation~\eqref{eq:reich_model_mean_variance} it is possible to conclude that the predicted $\bm{y}$ value is given by $\bm{X}(\bm{X^TX})^{-1}\bm{X}^T(\bm{y} - \bm{\hat{\psi}}) = \bm{P}(\bm{y}- \hat{\bm{\psi}}) = \bm{Py} - \bm{P}\hat{\bm{\psi}}$, a projection of $\bm{y}$ onto the space of $\bm{X}$ minus a projection of the latent effect $\hat{\bm{\psi}}$ onto the space of $\bm{X}$. When the spatial confounding is present it indicates the existence of duplicated information in the model. One way to alleviate this problem is by using a projection-based approach. That is done by decomposing the spatial effect into the projection onto the space of the covariates and the projection onto the orthogonal space of the covariates as in Equation~\eqref{eq:projection_based}. \begin{align} \label{eq:projection_based} & \bm{Y}|\bm{\beta}, \bm{\psi}, \tau_{\epsilon} \sim \text{Normal}(\bm{X\beta} + \bm{P\psi} + \bm{P^{\bot}\psi}, \tau_{\epsilon}\bm{I_n}), \\ & \bm{\psi}|\tau_{\psi}, \sim \text{Normal}(0, \tau_{\psi}\bm{Q}), \nonumber \end{align} in which, $\bm{P^{\bot}} = (\bm{I} - \bm{P})$ is the projection matrix onto orthogonal space of $\bm{X}$. Therefore, in Equation~\eqref{eq:projection_based} $\bm{P\psi}$ corresponds to the information of $\bm{\psi}$ on the space of $\bm{X}$ which in other words represents the duplicated information. Thus, one way to alleviate the spatial confounding is by removing $\bm{P\psi}$ from the model. This approach is known as restricted spatial regression (RSR) and is also applicable for generalized linear mixed models (GLMMs). However, for GLMMs, it is not possible to analytically evaluate the impacts of the latent effect on the coefficients estimates as the analytical solution of the involved integrals are not available. Hereafter, we will refer to this approach as the RHZ model. \cite{hanks2015restricted} focused their effort into geostatistical data instead of areal data as the previous work. Also, the authors reported several simulation studies about inference under model misspecification. For geostatistical data, one must assume that the correlation structure may be a function of the distance between points in the space and some parameters might govern the spatial relationship between areas. One of the most common covariance structure for continuous spatial correlation is the Mat\'{e}rn structure \citep{cressie1992statistics}. In this model, each $\bm{\Sigma}$ (covariance matrix) entry of is defined as $$\Sigma_{ij} = \sigma^2\frac{1}{\Gamma(\nu)2^{\nu-1}}\PC{\sqrt{2\nu}\frac{d_{ij}}{\phi}}^{\nu}K_{\nu}\PC{\sqrt{2\nu}\frac{d_{ij}}{\phi}}$$ where $d_{ij}$ is the Euclidean distance between the $i_{th}$ and the $j_{th}$ observations, $\sigma^2$ is the partial sill parameter, $\nu$ is a smoothness parameter, $\phi$ is the range parameter, and $K_{\nu}$ is the modified Bessel function of the second kind. In the RHZ model, $\bm{\Sigma} = \bm{Q}^{-1}$ is fixed, then it is possible to compute $\bm{Q}$ just once. However, in the continuous case, the matrix $\bm{\Sigma}$ may vary given the parameters $\{\sigma^2, \nu, \phi\}$. Thus, an approach similar to the previously mentioned may not be feasible because each step of MCMC (or the step in a numerical optimization routine) would require the matrix $\bm{Q} = \bm{\Sigma}^{-1}$ to evaluate the likelihood. To obtain an efficient algorithm \cite{hanks2015restricted} suggest the use of the conditioning by kriging technique \citep{rue2005gaussian}. The idea is to sample from the unrestricted model $\bm{\psi^{\ast}} \sim \text{Normal}(\bm{0}, \bm{\Sigma})$ and then to have a sample, under the restriction $\bm{P\psi} = \bm{0}$, take $\bm{\psi} = \bm{\psi}^{\ast} - \bm{\Sigma X}(\bm{X\Sigma X})^{-1}\bm{X}^T\bm{\psi}^{\ast}$. Through simulations, the authors showed that using the conditioning by kriging technique the inference for fixed effects is more appropriate by comparing the Type-S error \citep{gelman2000diagnostic}. A Type-S error occurs when the regression parameters are equal to zero and the $95\%$ posterior credibility interval does not contain the zero value. Another important contribution of this work is the possibility to get a sample from both models (restricted and unrestricted) concurrently, along the MCMC. This is possible because there is an equivalence between the RHZ model and the unrestricted model: \begin{align*} E(Y_i|\bm{\beta}) &= \bm{X\beta}_{rsr} + \bm{\psi}_{rsr} \\ &= \bm{X\beta}_{rsr} + \bm{(I-P)\psi}_{sr} \\ &= \bm{X\beta}_{rsr} + \bm{\psi}_{sr} - \bm{P\psi}_{sr} \\ &= \bm{X\beta}_{rsr} + \bm{\psi}_{sr} - \bm{X(X^TX)^{-1}X^T}\psi_{sr} \\ &= \bm{X(\beta}_{rsr} - (\bm{X}^T\bm{X})^{-1}\bm{X}^T\bm{\psi}_{sr}) + \bm{\psi}_{sr} \\ &= \bm{X\beta}_{sr} + \bm{\psi}_{sr}, \end{align*} where $\bm{\beta}_{rsr}$ refers to the coefficients of the restricted model proposed by \cite{reich2006effects}, $\beta_{sr}$ corresponds to the unrestricted model, $\bm{\psi}_{rsr}$ are the latent effects of the restricted model and $\bm{\psi}_{sr}$ the latent effects of the unrestricted model. \subsubsection{Measures of spatial confounding} \label{subsec:svif} A common confounding measure for spatial models is the spatial VIF (SVIF) as proposed by \cite{reich2006effects}. This measure is equivalent, for each $\beta_j$, to the ratio between the variance of $\beta_j$ for the spatial model and the variance for the model without spatial component as in Equation~\eqref{eq:VIF_regression}. This measure reflects the increment in the variance after adding the spatial component. For linear regression models, it is possible to calculate the exact value of these two quantities (Equation~\eqref{eq:reich_model_mean_variance}). \cite{reich2006effects} also note that this measure depends only on $r = \frac{\tau_{\psi}}{\tau_{\epsilon}}$ where $\tau_{\epsilon}$ is the precision of the Gaussian response, being the scale of the latent effect important in such kind of study \citep{paciorek2010importance}. The SVIF is defined as: \begin{equation}\label{eq:VIF_regression} SVIF(\beta_j|r, \tau_{e}) = \frac{Var(\beta_j)_{slr}}{Var(\beta_j)_{lr}}, \end{equation} where $Var(\beta_j)_{slr}$ is the variance of the coefficient for the spatial linear regression and $Var(\beta_j)_{lr}$ is the variance for the linear regression. Under a GLMM it is not possible to derive a closed form for $Var(\beta_j)$, then the solution is to approximate these quantities by the Fisher information. The same occurs for frailty models and in this case one may use the Fisher information or the empirical variance obtained in a posterior sample (in Bayesian frameworks). Thus one can calculate the SVIF as \begin{equation}\label{eq:VIF_frailty} SVIF(\beta_j) = \frac{Var(\beta_j)_{sm}}{Var(\beta_{j})_{m}}, \end{equation} where $Var(\beta_j)_{sm}$ is the sample variance of the coefficient for the spatial model and $Var(\beta_j)_{m}$ is the sample variance for the model without the spatial component. With the $SVIF(\beta_j)$, one can compare two models and investigate if the variance is inflated after the latent effect inclusion. However, we can also evaluate the effectiveness of the restricted model. An equivalent way to measure the variance's impact is by using the variance retraction factor defined as: \begin{equation}\label{eq:VRF_frailty} SVRF(\beta_j) = \frac{Var(\beta_j)_{u} - Var(\beta_j)_{r}}{Var(\beta_j)_{u}}, \end{equation} where $Var(\beta_j)_{u}$ is the variance of the coefficient for the unrestricted model and $Var(\beta_j)_{r}$ is the variance for the restricted model. This measure is zero if $Var(\beta_j)_u = Var(\beta_j)_r$, greater than zero if $Var(\beta_j)_u > Var(\beta_j)_r$ and less than zero otherwise. A $SVRF(\beta_j) = 0.4$ can be interpreted as a $40\%$ retraction in the coefficient variance under the restricted model in comparison with the unrestricted one. \subsection{Spatial frailty model} \subsubsection{Survival models} Survival models are an important tool in several branches of science mainly in health data analysis. In general, the researcher is interested in using survival models to answer questions about phenomena that can be measured in units of time. Since the response is observed in units of time, it is assumed for it, distributions with support in the positive real numbers. The most commonly employed models make use of simple probability distributions such as exponential, gamma, lognormal or Weibull. More complex models rely on less conventional distributions such as the Birnbaum-Saunders \citep{birnbaum1969new} or semi-parametric approaches as in the case of the piecewise exponential model \citep{friedman1982piecewise}. A great differential of survival models is that in practice the phenomenon of interest is not always observed. To deal with this situation, without loss of information, it is necessary to take advantage of a censoring scheme. There are several censoring schemes in the literature being the right, left and interval censoring schemes the most famous ones. Besides that, the censoring may happen according to some mechanism being the most famous ones the type I and type II censoring mechanisms. The former happens when the study has a fixed endpoint and then people who have not yet experienced the event are censured. The latter occurs when a number of events, defined a priori, is achieved. Thus, all other individuals are censored. For a review of survival models see \cite{hosmer2008applied}. In several cases, as the cited ones, the likelihood fits in Equation~\eqref{eq:likelihood_frailty}. \begin{align} \label{eq:likelihood_frailty} \mathcal{L}(\bm{\theta}; t) = &\prod_{d\in \bm{D}}f_{\bm{\theta}}(t_d) \\ &\prod_{r\in \bm{R}}S_{\bm{\theta}}(t_r) \prod_{l\in \bm{L}}\PC{1-S_{\bm{\theta}}(t_l)} \nonumber \\ &\prod_{k\in \bm{K}}\PC{S_{\bm{\theta}}(t_{k1}) - S_{\bm{\theta}}(t_{k2})} \nonumber, \end{align} \noindent where $\bm{D}$ is the set of observed failure/event times, $\bm{R}$ is the set of right-censored sample units, $\bm{L}$ is the set of left-censored sample units and $\bm{K}$ is the set of interval-censored sample units. The time until failure or the censoring time is denoted by $t$ for left and right censoring schemes. For interval censoring, two times are provided and then we denote the lower bound of this interval as $t_{k1}$ and the upper bound as $t_{k2}$ for a sample unit $k$. The distribution assumed for the phenomenon of interest is represented by $f_{\bm{\theta}}(\bm{t})$ (in parametric models) and $S_{\bm{\theta}}(\bm{t})$ is the survival function. As common choices for $f_{\bm{\theta}}(\bm{t})$ we can cite exponential, gamma, lognormal and Weibull distributions. The function choice leads to different forms of the $h_{\bm{\theta}}(\bm{t})$ called hazard function. It measures the instantaneous risk of occurrence of an event. $S_{\bm{\theta}}(\bm{t})$ is the survival function which indicates the probability of occurrence of the event at a time $T > t$. Any other parameters of $f_{\bm{\theta}}(t)$ are represented by the vector $\bm{\theta}$. The functions $f_{\bm{\theta}}(t)$, $S_{\bm{\theta}}(t)$ and $h_{\bm{\theta}}(t)$ are linked through the following identities: \begin{align} \label{eq:survival_identities} & S_{\bm{\theta}}(t) = \Pr(T > t) = \int _{t}^{{\infty }}f_{\bm{\theta}}(u)\,du = 1-F_{\bm{\theta}}(t), \nonumber \\ & h_{\bm{\theta}}(t)=\lim _{dt\rightarrow 0}{\frac {\Pr(t\leq T<t+dt)}{dt}\times\frac{1}{S_{\bm{\theta}}(t)}}={\frac {f_{\bm{\theta}}(t)}{S_{\bm{\theta}}(t)}}=-{\frac {S_{\bm{\theta}}'(t)}{S_{\bm{\theta}}(t)}}, \\ & f_{\bm{\theta}}(t)=h_{\bm{\theta}}(t)\times S_{\bm{\theta}}(t). \nonumber \end{align} The survival function, $S_{\bm{\theta}}(t)$, has the property that $S_{\bm{\theta}}(0) = 1$ and $S_{\bm{\theta}}(\infty) = 0$. However, in some cases, it is possible to observe that some individuals will never experience the event of interest because they may be not exposed to the phenomenon anymore. In those cases one can use a cure fraction model \citep{boag1949maximum} where there is a proportion of the individuals which will never experience the event of interest. The simpler way to introduce a cure fraction in the modeling is by a mixture model. In this case, the survival function is a mixture of a proper survival function and a point mass at a constant $c$, called cure fraction as above $$S_{\bm{\theta}}(t) = c + (1-c)S^{\ast}_{\bm{\theta}}(t).$$ Other approaches for the cure fraction can be found in the literature as, for example, \citet{tsodikov2003estimating, lambert2007modeling, scudilio2019defective}. In survival analysis, the interest is to model the hazard function to understand factors that impact the risk of an event. Therefore, covariates may be included into the model to measure their impact. Several parametric models are described in the literature as the cases in Table \ref{tab:survival_functions}. \begin{table}[h] \caption{Distributions and its respective set of parameters ($\theta$), probability density function ($f_{\theta}$), survival function ($S_{\theta}$) and hazard function ($h_{\theta}$). The term $\Phi(t)$ represents the cumulative distribution function of a standard Normal distribution.} \label{tab:survival_functions} \centering \begin{tabular}{@{}lllll@{}} \toprule Distribution & $\theta$ & $f_{\theta}(t)$ & $S_{\theta}(t)$ & $h_{\theta}(t)$ \\ \midrule Exponential & $\{\lambda\}$ & $\lambda\exp\{-\lambda t\}$ & $\exp\{\lambda t\}$ & $\lambda$ \\ Lognormal & $\{\mu, \sigma\}$ & $\frac {1}{(2\pi)^{1/2}\sigma t}\exp\chav{-\frac{1}{2}\PC{\frac{log(t) - \mu}{\sigma^2}}^2}$ & $1-\Phi\PC{\frac{\log{t} - \mu}{\sigma}}$ & $\frac{f_{\theta}(t)}{S_{\theta}(t)}$ \\ Gamma & $\{\alpha, \lambda\}$ & $\frac {\lambda ^{\alpha }}{\Gamma (\alpha )}t^{\alpha -1}e^{-\lambda t}$ & 1 - $\frac {1}{\Gamma (\alpha )}\int_0^{\lambda t} u^{\alpha -1}e^{-u}du$ & $\frac{f_{\theta}(t)}{S_{\theta}(t)}$ \\ Weibull & $\{\alpha, \lambda\}$ & $\alpha\lambda t^{\alpha - 1}\exp\{\lambda t^{\alpha}\}$ & $\exp\{-\lambda t^{\alpha}\}$ & $\alpha\lambda t^{\alpha-1}$ \\ \bottomrule \end{tabular} \end{table} A well studied method to include covariates in the modeling is the Cox proportional hazards model \citep{cox1972regression}. Its idea is to insert the covariates on the hazard function in a multiplicative way ensuring that the hazard is never negative. This model assumes proportional hazards meaning that the hazard ratio for two individuals is constant over time. Next equation shows the hazard function under the Cox proportional hazard model: \begin{equation} h_{\bm{\theta}}(t_i|\bm{X}_i) = h^{\ast}_{\bm{\theta}}(t_i)\exp\{\bm{X}_i\bm{\beta}\}, \end{equation} \noindent where $h^{\ast}_{\bm{\theta}}(t_i)$ is called baseline hazard function. However, one can use the partial likelihood technique which makes the baseline hazard specification unnecessary \citep{cox1972regression}. Another alternative, is to create a fully parametric proportional hazard model by replacing $h^{\ast}_{\bm{\theta}}(.)$ by a parametric baseline hazard function \citep{lawless2011statistical}. In many cases, the introduction of covariates is not enough for an appropriate fit. This is explained by the fact that often, important covariates are not observed or they are impossible to measure. In this case, one can introduce a latent effect giving rise to a frailty model. Similarly to GLM models, one can introduce latent effects to take the non-observed covariates and/or clusters effects into consideration. This model family is known as frailty models \citep{wienke2010frailty}. In general, the easiest way to introduce these effects is in a multiplicative way. Because the hazard is a positive quantity it is necessary to guarantee that the multiplicative effect will ensure that the hazard is still positive. One way is to assume that $\bm{\gamma}$, the frailty term, is drawn from a positive probability distribution. \begin{equation*} \label{eq:funcao_risco_fragildiade} h_{\bm{\theta}}(t_{ij}|\bm{X}_{ij}) = h^{\ast}_{\bm{\theta}}(t_{ij})\gamma_j\exp\{\bm{X}_{ij}\bm{\beta}\}, \end{equation*} \noindent where $\gamma_j$ is called frailty (related to cluster $j$) and a common choice for its distribution is the gamma distribution, given rise to the gamma frailty model. However, under this distribution, it is difficult to insert dependence structures between clusters and then they are, in general, considered independent. The main idea in spatial statistics is to insert dependence between geographically close locations. Using the gamma frailty model, the inclusion of spatial structure is not trivial. Several approaches in the literature try to deal with spatially structured effects in frailty models as \cite{henderson2002modeling}, \cite{li2002modeling} and \cite{banerjee2003frailty}. The latter proposed a frailty model that allows the insertion of already known structures of spatial models. In this case, the spatial effect enters the model in an additive way, but within the exponential term, which gives rise to the model presented in Equation~\eqref{eq:spatial_frailty_model}. Take $j = 1, \ldots, n_i $, indices of $n_i$ sample units observed in the location $i$ for $i = 1, \ldots, n $, $n$ locations. The hazard function of the spatial frailty model is given by: \begin{align} \label{eq:spatial_frailty_model} h_{\bm{\theta}}(t_{ij}|\bm{X}_{ij}) & = h_{\bm{\theta}}^{\ast}(t_{ij}) \times \gamma_i \times e^{\bm{X}_{ij} \bm{\beta}}\nonumber \\ & = h_{\bm{\theta}}^{\ast}(t_{ij}) \times e^{\bm{X}_{ij}\bm{\beta} + log(\gamma_i)} \\ & = h_{\bm{\theta}}^{\ast}(t_{ij}) \times e^{\bm{X}_{ij}\bm{\beta} + \psi_i} \nonumber, \end{align} \noindent where $\psi_i$ is Gaussian and consequently the vector $\bm{\psi}$ is a multivariate normal distribution. This setting is convenient since several spatial models use the multivariate normal distribution as in the case of this work. \section{Restricted Spatial Frailty models} \label{sec:restricted_spatial_frailty_models} \subsection{Method} \label{chap:survival} The likelihood of the spatial frailty model depends on the hazard function which is related to the baseline hazard function, covariates, and latent effects. As a consequence, this likelihood can be written according to Equation~\eqref{eq:spatial_frailty_likelihood}. Let $h_{\bm{\theta}}^{0}$ and $H_{\bm{\theta}}^{0}$ be the baseline hazard function and the cumulative baseline hazard function, respectively. Let $\bm{\psi} = \PR{\psi_1, \ldots, \psi_n}^T$ be a vector of latent effects related to each location. Define $\bm{\epsilon}$ as a vector with entries $\epsilon_{ij}$ $i = 1, \ldots, n$; $j = 1, \ldots, n_i$ where $\epsilon_{ij}$ is an unstructured latent effect related to the sample unit $j$ at location $i$. The likelihood is given by \begin{small} \begin{align} \label{eq:spatial_frailty_likelihood} & \mathcal{L}(t, \bm{\theta}, \bm{\beta}, \bm{\psi}, \bm{\epsilon}) = \prod_{i=1}^{n}\prod_{j=1}^{n_i} \Big[\PR{h_{\bm{\theta}}(t_{ij})S_{\bm{\theta}}(t_{ij})}^{\Delta_D}S_{\bm{\theta}}(t_{ij})^{\Delta_R}\PC{1-S_{\bm{\theta}}(t_{ij})}^{\Delta_L}\PC{S_{\bm{\theta}}(t_{ij1}) - S_{\bm{\theta}}(t_{ij2})}^{\Delta_K} \Big ], \nonumber \\ & h_{\theta}(t_{ij}) = h_{\theta}^0(t_{ij})\exp\chav{\bm{X}_{ij}\bm{\beta} + \psi_i + \epsilon_{ij}}, \\ & S_{\theta}(t_{ij}) = \exp\chav{-H_{\theta}^0(t_{ij})\exp\chav{\bm{X}_{ij}\bm{\beta} + \psi_i + \epsilon_{ij}}}, \nonumber \end{align} \end{small} \vspace{-0.2cm} \noindent and $\bm{\Delta} = \chav{\Delta_D, \Delta_R, \Delta_L, \Delta_K}$ are indicator functions of events, right-censored sample units, left-censored sample units and interval-censored sample units, respectively, and represent, for each individual, which term will contribute in the likelihood. In this model there is more sample units than locations which implies in different supports for $\bm{X}_{N\times p}$ and $\bm{\psi}_{n\times 1}$, where $N = \sum_{i = 1}^n n_i$. As mentioned by \cite{hanks2015restricted}, the projection-based approach is intuitive when the support of the observations is identical to spatial support, but we might be careful when this is not true as in the case of spatial frailty models. That said, in the conventional projection-based approach, the projection matrix is given by $\bm{P}_{(N\times N)} = \bm{X}(\bm{X}^T\bm{X})^{-1}\bm{X}^T$ and, therefore, it is not possible to make the projection of $\bm{\psi}_{n\times 1}$ onto the orthogonal space of $\bm{X}_{N\times p}$ directly. The simpler solution is to create a new vector of the same length as $\bm{X}$ by repeating the spatial effects according to the areas where $\bm{X}$ were collected. Define $\bm{\Psi} = [\psi_1\times \bm{1}_{n_1}, \ldots, \psi_n\times \bm{1}_{n_n}]^T$ where $\bm{1}_{m}$ is a length $m$ row vector of ones. For notation simplification we are considering that the $\bm{X}$ matrix is sorted by regions althoug it is not necessary. Thus, $\bm{\Psi}$ is represented in Equation~\eqref{eq:big_spatial_effect} \begin{equation} \label{eq:big_spatial_effect} \bm{\psi}_{n\times 1} = \begin{bmatrix} \psi_1 \\ \psi_2 \\ \vdots \\ \psi_n \end{bmatrix}; ~~~~ \bm{\Psi}_{N\times 1} = \begin{array}{c@{\!\!\!}l} \left[ \begin{array}[c]{ccccc} \psi_1 \\ \vdots \\ \psi_1 \\ \vdots \\ \psi_n \\ \vdots \\ \psi_n \end{array} \right] & \begin{array}[c]{@{}l@{\,}l} \left. \begin{array}{c} \vphantom{0} \\ \vphantom{\vdots} \\ \vphantom{0} \end{array} \right\} & \text{$n_1$ times} \\ \vphantom{\vdots} \\ \left. \begin{array}{c} \vphantom{0} \\ \vphantom{\vdots} \\ \vphantom{0} \end{array} \right\} & \text{$n_n$ times} \end{array} \end{array}. \end{equation} Then we can rewrite the hazard function in terms of the new vector in matrix format. \begin{equation} \label{eq:unrestricted_spatial_frailty} h_{\bm{\theta}}(t) = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X}\bm{\beta} + \bm{\Psi} + \bm{\epsilon}}. \end{equation} Given this configuration, we can apply a projection-based approach and decompose the vector $\bm{\Psi}$ into $\bm{P\Psi}$ and $\bm{P^{\bot}\Psi}$ where $\bm{P}^{\bot} = (\bm{I} - \bm{P})$ \begin{equation} \label{eq:decomposed_frailty_model} h_{\bm{\theta}}(t) = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta} + \bm{P\Psi} + \bm{P}^{\bot}\bm{\Psi} + \bm{\epsilon}}. \end{equation} The duplicated information in Equation~\eqref{eq:decomposed_frailty_model} is the vector $\bm{P\Psi}$ and may promote the bias and variance inflation. To alleviate it, a convenient solution is to remove this quantity giving rise to the following model \begin{equation} h_{\bm{\theta}}(t) = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta}_{rsf} + \bm{P}^{\bot}\bm{\Psi} + \bm{\epsilon}}, \end{equation} \noindent as $\bm{P} = \bm{X}(\bm{X}^T\bm{X})^{-1}\bm{X}^T$, we expect that this information will be incorporated by the coefficients as $\bm{\beta}_{rsf} = \bm{\beta} + (\bm{X}^T\bm{X})^{-1}\bm{X}^T\bm{\Psi}$ where ``rsf'' means ``restricted spatial frailty''. However, this solution implies in a limitation to the model. The spatial effect ($\bm{P}^{\bot}\bm{\Psi}$), free of spatial confounding, is a $N\times 1$ vector which does not have a meaning as we have just $n$ locations. Therefore, we propose a summarization of this information creating two vectors. The first vector contains the means by regions of $\bm{P}^{\bot}\bm{\Psi}$ and the second one contains the deviations from these means. Define $\bm{\psi}_{rsf} = \PR{\psi_{rsf_{1}}, \ldots, \psi_{rsf_{n}}}^T$ the vector containing the $n$ means of $\bm{P^{\bot}\Psi}$, one for each region $i = 1, \ldots, n$, and $\tilde{\bm{\psi}} = \PR{\tilde{\psi}_{11}, \ldots, \tilde{\psi}_{nn_n}}^T$, where $\tilde{\psi}_{ij}$ represents the individual distance of each element of $\bm{P^{\bot}\Psi}$ to its respective mean $\psi_{rsf_{i}}$. In this case, $\bm{\Psi}_{rsf} = \PR{\psi_{rsf_1}\times \bm{1}_{n_1}, \ldots, \psi_{rsf_n}\times \bm{1}_{n_n}}^T$ is a vector of remaining mean effects of each location and $\tilde{\bm{\psi}}$ represents, for each sample unit, an individual distance from the mean as in Equation~\eqref{eq:final_spatial_effect}. In this case, both $\bm{\Psi}_{rsf}$ and $\tilde{\bm{\psi}}$ are $N\times 1$ vectors \begin{small} \begin{equation} \label{eq:final_spatial_effect} \bm{\Psi}_{rsf} = \begin{array}{c@{\!\!\!}l} \left[ \begin{array}[c]{ccccc} \psi_{rsf_1} \\ \vdots \\ \psi_{rsf_1} \\ \vdots \\ \psi_{rsf_n} \\ \vdots \\ \psi_{rsf_n} \end{array} \right] & \begin{array}[c]{@{}l@{\,}l} \left. \begin{array}{c} \vphantom{0} \\ \vphantom{\vdots} \\ \vphantom{0} \end{array} \right\} & \text{$n_1$ times} \\ \vphantom{\vdots} \\ \left. \begin{array}{c} \vphantom{0} \\ \vphantom{\vdots} \\ \vphantom{0} \end{array} \right\} & \text{$n_n$ times} \end{array} \end{array}; ~~~~ \tilde{\bm{\psi}} = \begin{bmatrix} \tilde{\psi}_{11} \\ \vdots \\ \tilde{\psi}_{11} \\ \vdots \\ \tilde{\psi}_{nn_n} \end{bmatrix}, \end{equation} \end{small} \noindent and then we can rewrite the model as in Equation~\eqref{eq:frailty_decomposition} \begin{equation} \label{eq:frailty_decomposition} h_{\bm{\theta}}(t) = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta}_{rsf} + \bm{\Psi}_{rsf} + \tilde{\bm{\psi}} + \bm{\epsilon}}. \end{equation} Once $\tilde{\bm{\psi}}$ is a vector of the same length of $\bm{\epsilon}$, it is not possible to estimate both of them but just the sum. Let's call $\tilde{\bm{\psi}} + \bm{\epsilon}$ as $\bm{\epsilon}_{rsf}$ and finally our final model is given by Equation \eqref{eq:frailty_decomposition_final}. \begin{equation} \label{eq:frailty_decomposition_final} h_{\theta}(t) = h_{\theta}^0(t)\exp\chav{\bm{X\beta}_{rsf} + \bm{\Psi}_{rsf} + \bm{\epsilon}_{rsf}}. \end{equation} Our main aim is to fit the restricted spatial frailty model. However, we would like to have estimates of the unrestricted model as well as the restricted model estimates. Therefore, we need to find equivalences between the restricted quantities and the unrestricted ones. With this equivalence, it is possible to have samples from both models concurrently. Equation~\eqref{eq:frailty_equivalence} presents this equivalence. \begin{align} \label{eq:frailty_equivalence} h_{\bm{\theta}}(t) & = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta}_{rsf} + \bm{\Psi}_{rsf} + \bm{\epsilon}_{rsf}} \\ & = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta}_{rsf} + \bm{\Psi}_{rsf} + \tilde{\bm{\psi}} + \bm{\epsilon}_{sf}} \nonumber \\ & = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta}_{rsf} + \bm{P^{\bot}\Psi}_{sf} + \bm{\epsilon}_{sf}} \nonumber \\ & = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X(\beta}_{rsf} - (\bm{X}^T\bm{X})^{-1}\bm{X}^T\bm{\Psi}_{sf}) + \bm{\Psi}_{sf} + \bm{\epsilon}_{sf}} \nonumber \\ & = h_{\bm{\theta}}^0(t)\exp\chav{\bm{X\beta}_{sf} + \bm{\Psi}_{sf} + \bm{\epsilon}_{sf}}, \nonumber \end{align} \noindent where ``sf'' means ``spatial frailty'' and represent the conventional spatial method and ``rsf'' means ``restricted spatial frailty'' and represents the model referred in Equation~\eqref{eq:frailty_decomposition_final}. Given the unrestricted model, we can calculate the restricted quantities since $\bm{\beta}_{rsf} = \bm{\beta_{sf}} + (\bm{X}^T\bm{X})^{-1}X^T\bm{\Psi}_{sf}$, $\bm{P}^{\bot}\bm{\Psi}_{sf} = \bm{\Psi}_{rsf} + \tilde{\bm{\psi}}$ and $\bm{\epsilon}_{rsf} = \bm{\epsilon}_{sf} + \tilde{\bm{\psi}}$. With these equivalences it is possible to have estimates of all parameters of the restricted model. The general formulation in Equation~\eqref{eq:frailty_equivalence} shows how to obtain the restricted models estimates for the proportional hazard family including the Cox model (when $h_{\bm{\theta}}^0(t)$ is not defined). In other words, we just need a sample from the unrestricted model to get estimates from both unrestricted and restricted models. These results are applied for the entire family of proportional hazards models. It is important to notice that even if we fit a model without the $\bm{\epsilon}$ (independent) term, under the restricted model, the component $\bm{\epsilon}_{rsf}$ will appear. \subsection{Reduction operator} Although enlarging the spatial effect vector is a straightforward solution in Equation~\eqref{eq:decomposed_frailty_model}, the projection approach requires, for each element of a posterior sample, the calculations: \begin{itemize} \item $\bm{\beta}_{rsf} = \bm{\beta}_{sf} + (\bm{X}^T\bm{X})^{-1}\bm{X}^T\bm{\Psi}_{sf}$, \item $\bm{P}^{\bot}\bm{\Psi}_{sf} = (\bm{I}-\bm{X}(\bm{X}^T\bm{X})^{-1}\bm{X}^T)\bm{\Psi}_{sf} = \bm{\Psi}_{rsf} + \tilde{\bm{\psi}}$, \end{itemize} \noindent which requires products of matrices with support equal to the sample size ($N$). It is not unusual to work with data sets in which, for each area, several individuals are observed. As this number increases, the total sample size $N$ also increases, but not the number of areas, $n$, that remains fixed. Said that, the computation of the restricted model increases as $N$ increases. However, because $\bm{\Psi}_{sf}$ is constant by area, it is possible to get the same desired results but computing it with a reduced version of $\bm{P}$ and $\bm{P}^{\bot}$ matrices in which the new matrices are $(n\times n)$-dimensional instead of $(N\times N)$-dimensional. Let's define an operator that will help us to achieve the computational improvement. Let $\bm{X}_{N\times p}$ be a matrix with entries $X_{ijk}$ for an index $i$, an element $j$ and column $k$, and $\bm{G}_{N\times 1}$ is a vector of indices indicating, for each row of $\bm{X}_{N\times p}$, an index $i$ in a set of indices starting from $1$ until $n$ ($n \ll N$). Then the reduction operator $\circled{r}$ is defined by: \begin{equation} \bm{X}_{N\times p} \circled{r} \bm{G} = \bm{x}_{n\times p}, \end{equation} \noindent in which $\displaystyle x_{ik} = \sum_{j = 1}^{n_i}X_{ijk}$, and $n_i$ is the number of elements related with index $i$. This operator has several properties that allow us to simplify the computational procedure. Let $c$ be a constant, $\bm{r}_{n\times 1}$ is a column vector, $R = [r_{G_1}, \ldots, r_{G_N}]^T$ is a $N\times 1$ vector with repeated entries for each index of $\bm{G}$ (constant by indices), $\bm{P}_{p\times p}$ is a squared matrix and, $\bm{Q}_{m\times p}$ is a matrix. Therefore, the following properties are true: \begin{enumerate} \item $(\bm{X}_1 + \bm{X}_2) \circled{r} \bm{G} = (\bm{X}_1 \circled{r} \bm{G}) + (\bm{X}_2 \circled{r} \bm{G})$, \item $(c\bm{X}) \circled{r} \bm{G} = c(\bm{X} \circled{r} \bm{G})$, \item $\bm{X^TR} = (\bm{X} \circled{r} \bm{G})^T\bm{r}$, \item $(\bm{QX^T}) \circled{r} \bm{G}^T = \bm{Q}(\bm{X} \circled{r} \bm{G})^T$, \item $(\bm{XPX^T}) \circled{r} \bm{G} = (\bm{X} \circled{r} G)\bm{P}\bm{X}^T$, \item $((\bm{XPX^T}) \circled{r} \bm{G}) \circled{r} \bm{G}^T = (\bm{X} \circled{r} \bm{G})\bm{P}(\bm{X} \circled{r} \bm{G})^T$, \item $(\bm{XPX^TR}) \circled{r} \bm{G} = (\bm{X} \circled{r} \bm{G})\bm{P}(\bm{X} \circled{r} \bm{G})^T\bm{r}$. \end{enumerate} The proofs of these properties are in Appendix \ref{apendix:proofs}. Using the reduction operator it is possible to compute $\bm{\beta_{rsf}}$ efficiently (by property 4): \begin{align} \label{eq:beta_rsf} \bm{\beta}_{rsf} & = \bm{\beta}_{sf} + (\bm{X^TX})^{-1}\bm{X^T\Psi}_{sf} \\ & = \bm{\beta}_{sf} + (\bm{X^TX})^{-1}(\bm{X} \circled{r} \bm{G})^T\bm{\psi}_{sf} \nonumber, \end{align} \noindent that is a product on a smaller dimension because $(\bm{X}^T\bm{X})^{-1}(\bm{X} \circled{r} \bm{G})^T$ is a $p\times n$ matrix. Also, to compute $\bm{\psi}_{rsf}$, using properties 1, 3 and 4, and defining $\bm{N}_{N\times N}$ as a diagonal matrix with $N_{ii} = n_{G_i}$ being the number of elements in each area, and $\bm{n}_{n\times n}$ being a diagonal matrix with $n_{jj} = n_{G_j}$ it is the same as \begin{align} \label{eq:psi_rsf} \bm{\psi}_{rsf} & = \bm{N}^{-1}(\bm{I_N}-\bm{X}(\bm{X}^T\bm{X})^{-1}\bm{X}^T)\bm{\Psi}_{sf} \circled{r} \bm{G}\\ & = (\bm{N}^{-1}\bm{\Psi}_{sf}-\bm{N}^{-1}\bm{X}(\bm{X}^T\bm{X})^{-1}\bm{X}^T\bm{\Psi}_{sf}) \circled{r} \bm{G} \nonumber \\ & = (\bm{N}^{-1}\bm{\Psi}_{sf}) \circled{r} \bm{G} -\bm{N}^{-1}(\bm{X}(\bm{X}^T\bm{X})^{-1}\bm{X}^T\bm{\Psi}_{sf}) \circled{r} \bm{G} \nonumber \\ & = (\bm{N}^{-1} \circled{r} \bm{G})^T\bm{\psi}_{sf} \circled{r} \bm{G} -\bm{N}^{-1}\bm{X}(\bm{X}^T\bm{X})^{-1}(\bm{X} \circled{r} \bm{G})^T\bm{\psi}_{sf} \circled{r} \bm{G} \nonumber \\ & = \bm{\psi}_{sf} -(\bm{N}^{-1}\bm{X} \circled{r} \bm{G})(\bm{X}^T\bm{X})^{-1}(\bm{X} \circled{r} \bm{G})^T\bm{\psi}_{sf} \nonumber \\ & = (\bm{I_n} - \bm{n}^{-1}(\bm{X} \circled{r} \bm{G})(\bm{X}^T\bm{X})^{-1}(\bm{X}^T\circled{r} \bm{G}))\bm{\psi}_{sf}. \nonumber \end{align} Then, for both $\bm{\beta}_{rsf}$ and $\bm{\psi}_{rsf}$ it is possible to calculate their values using small length matrices which is computationally attractive. \section{Simulation} \label{sec:simulation} This study is divided into two sections. First, the computational improvement will be presented by a simulation study that shows the reduction operator efficiency. Next, the capacity to recover the model parameters and the efficiency of the proposed correction will be evaluated. The methodology presented here does not depend on the method used to get samples from the unrestricted model. We provide one implementation for our methodology in the \texttt{RASCO} \texttt{R} package (\href{https://github.com/douglasmesquita/RASCO}{https://github.com/douglasmesquita/RASCO}). The package relies on the \texttt{R-INLA} package for inference because its computational benefits. It uses the \texttt{inla.posterior.sample} function to generate posterior samples of the parameters involved. This function allows us to have a sample from the approximated posterior distribution. The hyperparameters are sampled from the grid used in the numerical integration and the latent field is sampled from the Gaussian approximation conditioned on the hyperparameters. Although it is an approximation and not exact like a MCMC procedure, as will be shown in this section, the obtained results are reliable and takes advantage of the computation efficiency of the INLA method. Based on the posterior sample of the unrestricted model and using Equation~\eqref{eq:frailty_equivalence} we obtained posterior samples from the restricted model. Finally, the method does not depend on the parametric model chosen for the baseline hazard. Therefore, we opted to choose the widely applied Weibull proportional hazard model. \subsection{Computational improvement} \label{subsec:comp_time} To show the computational improvement using the reduction operator, we performed a simulation study. The time spent to get samples from the restricted model using the methodology described in Section~\ref{chap:survival} and the time spent applying the reduction operator were recorded. The data were generated from the Weibull proportional hazard model for a spatial structure (polygons) containing $92$ areas. We vary the number of individuals in each area in the following grid: $2, 4, 8, 16, 32, 64 ~\text{and}~ 128$. Therefore, the total sample size $N$ is $92\times 2 = 184$ in the first scenario and $92\times 128 = 11,776$ in the last one. For each case, a posterior sample of size $5000$ was obtained and the restricted estimates were made based on it. This is a two-step technique, first, we get samples from the unrestricted model and then by Equation~\eqref{eq:frailty_equivalence} we get samples from the restricted model. Thus, we are able to record the time to fit the model and also the time to perform the correction. It is interesting to notice that, in both cases, the time spent to fit the unrestricted model should be the same and therefore we are not reporting it. Using the reduction operator, the correction step has always the same length matrix although the matrix $\bm{X}$ becomes larger at each step. Figure~\ref{fig:reduction_operator} shows the computational cost for applying these two approaches, varying according to the number of subjects in each area. The boxplots are based on $100$ repetitions. \begin{figure}[h] \centering \includegraphics[width = 0.95\textwidth]{reduction_operator.pdf} \caption{Time spent to fit the Weibull proportional hazard model with and without the reduction operator in seconds. Right: Original scale in seconds; Left: Logarithmic scale.} \label{fig:reduction_operator} \end{figure} As one can see, the computational cost is increasing as $N$ increases for the model without the reduction step. The increment in time for the pure model increases drastically because for each posterior sample we must calculate $\bm{P^{\bot}}\bm{\Psi}_{sf}$. This is a product of a $N\times N$ matrix by a $N \times 1$ vector (this product is repeated $5,000$ times). Instead, the model with the reduction operator calculates $((\bm{P}^{\bot} \circled{r} \bm{G}) \circled{r} \bm{G})\bm{\psi}_{sf}$ which is a product of a $n\times n$ matrix by a $n \times 1$ vector). The time spent to calculate $(\bm{P}^{\bot} \circled{r} \bm{G}) \circled{r} \bm{G}$ also increases as $N$ increases, but this calculation occurs just once. Also, it is a straightforward calculation that is not strongly affected by the sample size. Thus, since the computational cost to calculate the reduced model is preferable and the fact that the results are strictly the same, we will use the reduction operator for the rest of the work. \subsection{Confounding alleviation} \label{subsec:conf_correction} To evaluate the model ability to estimate the parameters, the data were generated from the Weibull proportional hazard model \begin{align} & h(t_i) =\alpha t_i^{\alpha - 1}\exp\chav{\beta_1X_{i1} + \beta_2X_{i2} + \psi_i}, \\ & \bm{\psi} \sim \text{ICAR}(\bm{W}, \tau_{\psi}), \nonumber \nonumber \end{align} \noindent where $\alpha = 1.2$, $\beta_1 = -0.3$, $\beta_2 = 0.3$ and $\tau_{\psi} = 0.75$. To evaluate the performance in terms of recovering the parameters in this model, we are considering the right censoring scheme and 4 censoring levels: 0\%, 25\%, 50\% and 75\%. We generated 1,000 datasets under each setup and 2 scenarios: 1) $\bm{X}_1$ and $\bm{X}_2$ are random variables and therefore no spatial confounding is expected; 2) $\bm{X}_1$ is a random variable but $\bm{X}_2$ is the set of centroids' latitudes of each county. The set of weakly informative priors was taken as follow $\alpha \sim \Gamma(0.001, 0.001)$, $\beta_{j} \sim \text{Normal}(0, 0.001), ~ j = 0, 1, 2,$ $\tau_{\psi} \sim \Gamma(0.5, 0.0005).$ Table \ref{tab:simulation_frailty} presents the mean of the estimated values (Mean), the mean of the standard deviations (SD), the coverage rate for a nominal rate of 95\% (Cov) and the mean squared error (MSE) for each scenario. \begin{table}[h] \caption{Simulation results the spatial frailty model experiment. The results are shown by mean, standard deviation (SD), coverage rate for a nominal rate of 95 \% (Cov) and mean square error (MSE).} \label{tab:simulation_frailty} \centering \resizebox{.99\textwidth}{!}{% \begin{tabular}{@{}llllllllllllll@{}} \toprule \multirow{3}{*}{Censure} & \multirow{3}{*}{Parameter} & \multicolumn{6}{l}{Without spatial confounding} & \multicolumn{6}{l}{with spatial confounding} \\ \cmidrule(l){3-14} & & SFM & & & RSFM & & & SFM & & & RSFM & & \\ \cmidrule(l){3-14} & & Mean (SD) & COV & MSE & Mean (SD) & COV & MSE & Mean (SD) & COV & MSE & Mean (SD) & COV & MSE \\ \midrule 00.00\% & $\alpha$ & 1.18 (0.07) & 83.20\% & 0.0071 & 1.18 (0.07) & 83.20\% & 0.0071 & 1.17 (0.07) & 77.80\% & 0.0087 & 1.17 (0.07) & 77.80\% & 0.0087 \\ & $\beta_1$ & 0.29 (0.08) & 93.90\% & 0.0060 & 0.29 (0.07) & 94.80\% & 0.0053 & 0.29 (0.08) & 93.60\% & 0.0061 & 0.29 (0.07) & 94.90\% & 0.0053 \\ & $\beta_2$ & -0.29 (0.08) & 93.70\% & 0.0062 & -0.30 (0.07) & 93.80\% & 0.0054 & -0.28 (0.20) & 83.40\% & 0.0609 & -0.29 (0.07) & 93.00\% & 0.0062 \\ \midrule 25.00\% & $\alpha$ & 1.20 (0.08) & 80.40\% & 0.0097 & 1.20 (0.08) & 80.40\% & 0.0097 & 1.18 (0.08) & 69.10\% & 0.0118 & 1.18 (0.08) & 69.10\% & 0.0118 \\ & $\beta_1$ & 0.30 (0.09) & 93.70\% & 0.0082 & 0.30 (0.08) & 94.40\% & 0.0073 & 0.29 (0.09) & 92.80\% & 0.0083 & 0.29 (0.08) & 94.40\% & 0.0072 \\ & $\beta_2$ & -0.30 (0.09) & 92.80\% & 0.0083 & -0.30 (0.08) & 93.60\% & 0.0074 & -0.28 (0.19) & 77.10\% & 0.0723 & -0.29 (0.09) & 93.60\% & 0.0085 \\ \midrule 50.00\% & $\alpha$ & 1.21 (0.09) & 80.00\% & 0.0137 & 1.21 (0.09) & 80.00\% & 0.0137 & 1.17 (0.08) & 72.80\% & 0.0131 & 1.17 (0.08) & 72.80\% & 0.0131 \\ & $\beta_1$ & 0.30 (0.10) & 94.30\% & 0.0116 & 0.30 (0.10) & 93.60\% & 0.0106 & 0.29 (0.10) & 93.60\% & 0.0114 & 0.29 (0.10) & 95.10\% & 0.0104 \\ & $\beta_2$ & -0.30 (0.11) & 93.20\% & 0.0129 & -0.30 (0.10) & 94.10\% & 0.0112 & -0.28 (0.17) & 63.80\% & 0.0936 & -0.28 (0.11) & 93.10\% & 0.0131 \\ \midrule 75.00\% & $\alpha$ & 1.20 (0.11) & 82.30\% & 0.0185 & 1.20 (0.11) & 82.30\% & 0.0185 & 1.18 (0.11) & 83.30\% & 0.0158 & 1.18 (0.11) & 83.30\% & 0.0158 \\ & $\beta_1$ & 0.30 (0.14) & 92.20\% & 0.0223 & 0.30 (0.14) & 93.30\% & 0.0211 & 0.30 (0.14) & 93.20\% & 0.0210 & 0.30 (0.14) & 94.30\% & 0.0194 \\ & $\beta_2$ & -0.29 (0.14) & 93.10\% & 0.0236 & -0.29 (0.14) & 93.80\% & 0.0215 & -0.30 (0.17) & 56.30\% & 0.1418 & -0.30 (0.15) & 92.80\% & 0.0264 \\ \bottomrule \end{tabular} } \end{table} It is possible to observe that, without spatial confounding, the SFM (Spatial Frailty Model) and the RSFM (Restricted Spatial Frailty Model) approaches present similar values for mean, coverage and mean squared error. Under spatial confounding, it is possible to observe that the point estimates (mean) are accurate for all parameters and both models. However, the standard deviation of $\beta_2$ is, on average, greater for the SFM model than for the RSFM model. Also, it is possible to observe that the MSE of $\beta_2$ is greater for the SFM than for the RSFM. The coverage rate seems adequate for both models except for the parameter $\alpha$. However, this inconsistency is observed in all models and for the INLA method $\alpha$ is considered as a hyperparameter with marginal posterior approximation obtained by numerical integration. This can be a possible explanation for why the \texttt{R-INLA} package might not be providing an appropriate coverage for this parameter. Anyhow, the true understanding of the reason that is causing this phenomenon is out of the scope of the current manuscript and does not affect our analysis and conclusions. a pursue of the investigation of the reason that is causing this phenomenon is out of the scope of the current manuscript. For the INLA method $\alpha$ is a hyperparameter and its posterior approximation is obtained by numerical integration that might now be providing an appropriate approximation in this case. However, this inconsistency is observed in all models a pursue of the investigation of the reason that is causing this phenomenon is out of the scope of the current manuscript. Another interesting conclusion is that as much the censure level increases the standard deviations also increase in all cases. It is showing that, in those models with bigger censoring rates, the estimates are less accurate as expected. The projection-based approach aims to estimate $\bm{\beta}^{\ast} = \bm{\beta}_{sf} + \bm{P}^{\bot}\bm{\Psi}$. In this case, we reported Figure \ref{fig:parameters_frailty} for $\displaystyle (\bm{\theta} - \bm{\theta}^{\ast})$ where $\bm{\theta} = \{\alpha, \beta_1, \beta_2\}$. \begin{figure}[h] \centering \includegraphics[width = 0.99\textwidth]{parameters_frailty.pdf} \caption{Boxplot of $(\bm{\theta} - \bm{\theta}^{\ast})$ for $\bm{\theta} = \{\alpha, \beta_1, \beta_2 \}$ in the spatial frailty model. Dashed line represents the value 0.} \label{fig:parameters_frailty} \end{figure} We expect all the values to be around 0, which means that the estimate is not biased. We can see, for $\alpha$ and $\beta_1$, that the estimates are similar for both SFM and RSFM models. However, for $\beta_2$ the behavior changes for the model with and without confounding. In the model without spatial confounding, as expected, $\beta_2$ behaves in the same way for $\beta_1$. For the model with spatial confounding, we can observe that the $\displaystyle (\bm{\theta} - \bm{\theta}^{\ast})$ tends to be around 0 for the SFM and also for the RSFM. Although they are centered at 0, the dispersion of SFM seems to be bigger than the dispersion of the RSFM model which, in this case, suggests variance inflation. From the perspective of the level of censorship, we can see a smooth increment in the coefficients' variance for all cases. This result is explained by the fact that, with the increment of the censoring rate, we have less cases and therefore less information about the effect of each covariate. Figures \ref{fig:parameters_frailty_sd}, \ref{fig:parameters_frailty_vif}, show for SFM and RSFM, the standard deviations and the SVIF (defined in Section \ref{subsec:svif}) comparing with the non-spatial model. An SVIF equal to 1 indicates that the variances of both models are the same. However, because the spatial model is more complex it is expected an increment in the variance. \begin{figure}[h] \centering \includegraphics[width = 0.99\textwidth]{parameters_frailty_sd.pdf} \caption{Boxplot of $\displaystyle \sigma_{\theta}$ for $\bm{\theta} = \{\beta_{1}, \beta_{2}\}$ for the SFM and RSFM where $\sigma_{\theta}$ represents the standard deviation of $\theta$.} \label{fig:parameters_frailty_sd} \end{figure} \begin{figure}[h] \centering \includegraphics[width = 0.99\textwidth]{parameters_frailty_VIF.pdf} \caption{Boxplot of the SVIF (log scale) between spatial models (SFM and RSFM) and the baseline model (Weibull proportional hazard model). Dashed line marks the value 0, which in the log scale represent the equality of variances.} \label{fig:parameters_frailty_vif} \end{figure} We can observe in Figure \ref{fig:parameters_frailty_sd} that the standard deviations are similar in all cases except for $\beta_2$ in the scenario with spatial confounding. In this case, we can see that the higher the level of censorship, the more similar is the standard deviation. In Figure~\ref{fig:parameters_frailty_vif}, we can observe a downward trend in the SVIF for both models when the level of censorship increases. It means that the efficiency of the correction decreases with the increment of the censured individuals, which is in agreement with Figure \ref{fig:parameters_frailty}. The behavior for $\beta_1$ and $\beta_2$ in the model without spatial confounding are similar and this is also true for the behavior of $\beta_1$ under spatial confounding. However, the parameter $\beta_2$ under spatial confounding presents huge inflation of variances for the model without correction. In some cases, we experienced a variance $\exp\{3\} \approx 20$ times bigger. In these cases, the restricted model behaves well and it keeps the variance stable. \section{Respiratory cancer in California} \label{sec:application} To fit the model, we use a right censoring scheme with the Weibull proportional hazard model. Our baseline model is the Non-spatial (NS) model given by the Weibull proportional hazard model and five covariates: 1) gender; 2) race; 3) disease stage; 4) age at diagnosis; 5) the percentage of people who smoke every day or most days (areal level). The spatial frailty model (SFM) also includes the ICAR spatial term, and the restricted spatial frailty model (RSFM) alleviates possible spatial confounding. In Table \ref{tab:frailty_results}, $\alpha$ is the shape parameter of the Weibull distribution and the estimate was almost the same in the NS and SFM models (RSFM estimate is the same of the SFM for hyperparameters). The parameter $\tau_w$ represents the precision for the ICAR model. The other parameters are related with the covariates in the modeling. \begin{table}[] \caption{Time until death by lung and bronchus cancer in California (US). Results are presented as mean, standard deviation (SD) and the 95 \%credibility interval (ICr).} \label{tab:frailty_results} \centering \resizebox{.95\textwidth}{!}{ \begin{tabular}{@{}lllllll@{}} \toprule \multirow{2}{*}{Parameter} & NS & & SFM & & RSFM & \\ \cmidrule(l){2-7} & Mean (SD) & ICr & Mean (SD) & ICr & Mean (SD) & ICr \\ \midrule $\alpha$ & 0.85 (0.0032) & (0.85; 0.86) & 0.86 (0.0033) & (0.85; 0.86) & 0.86 (0.0033) & (0.85; 0.86) \\ $\tau_{\psi}$ & & & 22.75 (6.8306) & (10.99; 36.49) & 22.75 (6.8306) & (10.99; 36.49) \\ $\beta_0$ & -4.07 (0.2048) & (-4.44; -3.65) & -3.58 (0.2091) & (-4.02; -3.20) & -4.06 (0.2001) & (-4.47; -3.69) \\ Gender & & & & & & \\ ~~~~ Female & ref. & & ref. & & ref. & \\ ~~~~ Male & 0.19 (0.0099) & (0.17; 0.21) & 0.19 (0.0098) & (0.18; 0.21) & 0.19 (0.0098) & (0.18; 0.21) \\ Race & & & & & & \\ ~~~~ Non-black & ref. & & ref. & & ref. & \\ ~~~~ Black & 0.16 (0.0177) & (0.13; 0.20) & 0.17 (0.0176) & (0.13; 0.20) & 0.17 (0.0175) & (0.13; 0.20) \\ Cancer stage & & & & & & \\ ~~~~ In situ & & & & & & \\ ~~~~ Localized & 1.51 (0.1985) & (1.12; 1.87) & 1.51 (0.1940) & (1.13; 1.90) & 1.51 (0.1940) & (1.13; 1.90) \\ ~~~~ Regional & 2.60 (0.1984) & (2.20; 2.96) & 2.60 (0.1935) & (2.25; 3.01) & 2.60 (0.1935) & (2.25; 3.02) \\ ~~~~ Distant & 3.73 (0.1985) & (3.35; 4.11) & 3.74 (0.1936) & (3.37; 4.14) & 3.74 (0.1936) & (3.37; 4.14) \\ Age at diagnosis & 0.02 (0.0005) & (0.02; 0.02) & 0.02 (0.0005) & (0.02; 0.02) & 0.02 (0.0005) & (0.02; 0.02) \\ \% Smokers & 2.13 (0.1821) & (1.79; 2.49) & -0.90 (0.3848) & (-1.68; -0.21) & 2.13 (0.1819) & (1.79; 2.51) \\ \bottomrule \end{tabular} } \end{table} From the epidemiological point of view, the NS model reflects the theory that patients in a more advanced stage of the disease have a higher risk of death (In situ $<$ Localized $<$ Regional $<$ Distant). Also, males have a higher risk when compared to females. Same way, black people have a higher risk when compared with non-black people. Further, the older the individual the greater is the risk. The coefficient for the percentage of smokers in the county indicates an increment in the risk of death due to lung and bronchus cancer. This covariate is our best proxy about individual tobacco consumption. When we compare the results from the NS model with those of the SFM, one can notice that for gender, race, stage of the disease and age at diagnosis, the results are similar with small differences in the estimates. However, for the coefficient of the percentage of smokers, the point estimate changes drastically and there is variance inflation (variance is about 5 times greater for the SFM). In the SFM model the credibility interval changes drastically pointing that the percentage of smokers is a protective factor for lung and bronchus cancer death. The restricted spatial frailty model (RSFM) was applied and we can notice that it returns similar estimates to those from the NS model, as expected. The credibility interval is now pointing that the higher the percentage of smokers, higher is the risk for cancer death. Figure~\ref{fig:frailty_effects} shows the spatial effect $\exp\{\bm{\psi}\}$ for the SFM and RSFM. \begin{figure}[h] \centering \includegraphics[width = 0.95\textwidth]{frailty_effects.pdf} \caption{Spatial risk effects for death by lung and bronchus cancer in California (US).} \label{fig:frailty_effects} \end{figure} We can see that the patterns are smoother for the RSFM case. However, the pattern remains similar to the SFM model being higher in the north of the state, less intense in the center and again high in the south. This result might be useful to create new policies or new health care centers for lung and bronchus cancer in California. We can conclude that the employment of the proposed restricted model is important in several ways. The first advantage is that the model conclusions retains the interpretability of the baseline model, keeping important conclusions about the model's covariates. Secondly, the computational improvement provided by the reduction operator appears as an important feature because it allows for the model to scale for large $N$. Third, it allows the user to apply its preferable software to get posterior samples from the unrestricted model and with its posterior sample correct for possible spatial confounding without refitting the model. Fourth, under spatial confounding, the variances of coefficients are not inflated as it is for the conventional model. Finally, the spatial pattern is similar when compared with the unrestricted model which shows that the correction maintain the underlying the spatial patterns. \section{Final remarks} \label{sec:final_remarks} Spatial confounding is a limitation of spatial models that needs attention since it can imply in wrong conclusions about important covariates effects. The conventional solution based on projections cannot be directly applicable for the spatial frailty models due to the fact that the support of fixed and random effects does not match. This work showed an alternative to alleviate the effects of spatial confounding in the spatial frailty framework. We provided an efficient way to fit the restricted spatial frailty model based on a posterior sample of the unrestricted model. To solve the difference in the supports of fixed and spatial effects, we proposed a reduction operator that is not only adequate to alleviate the spatial confounding but also has computational benefits. The method adequacy and efficiency were shown by a simulation study that proved its relevance and importance. We have applied the methodology in the data provided by the SEER. We enrich the data set with some county-level information provided by the CHRR. The spatial frailty model was employed to model the time until death by lung and bronchus cancer in California between 2010 and 2016. Our method provided alleviation of the spatial confounding while keeping the model interpretability. For future work, we may investigate the effects of spatio-temporal confounding in frailty models. To the best of our knowledge, up to now, no attention is paid to these extension. Moreover, the reduction operator seems an easy and applicable tool for statistical models. It can be directly employed for discrete models in which the math involves products of a matrix and a variable that is constant by groups (counts for example). Therefore, it is possible to think in a discretization of continuous variables aiming to reduce the computational effort keeping the desired accuracy. Finally, the proposed methodology is available in the \texttt{RASCO} \texttt{R} package with more methods and examples. Up to now the package is able to work with GLMM, Shared Component models (with two outcomes) and the aforementioned restricted spatial frailty model. The first version is available at \href{https://github.com/douglasmesquita/RASCO}{https://github.com/douglasmesquita/RASCO}. \section{Appendix} \label{apendix:proofs} In this section we present the proofs of the properties of the reduction operator. Let $\bm{X}_{N\times p}$ be a matrix with entries $X_{ijk}$ for an index $i$, an element $j$ and column $k$, and $\bm{G}_{N\times 1}$ a vector of indices indicating for each line of $\bm{X}_{N\times p}$ an index $i$ in a set of indices starting from $1$ until $n$ ($n \ll N$). Then the reduction operator $\circled{r}$ is defined by: \begin{equation} \bm{X}_{N\times p} \circled{r} \bm{G} = \bm{x}_{n\times p}, \end{equation} in which $\displaystyle x_{ik} = \sum_{j = 1}^{n_i}X_{ijk}$, and $n_i$ is the number of elements associated with index $i$. For $\bm{X}_1$ and $\bm{X}_2$, $N\times p$ matrices with entries $X_{dijk}$ for $d = 1, 2$, it is true that $(\bm{X}_1 + \bm{X}_2) \circled{r} \bm{G} = (\bm{X}_1 \circled{r} \bm{G}) + (\bm{X}_2 \circled{r} \bm{G})$. \begin{proof} Consider the general term \begin{align*} \PR{(\bm{X}_1 + \bm{X}_2) \circled{r} \bm{G}}_{ik} = & \sum_{j = 1}^{n_i}\PC{X_{1ijk} + X_{2ijk}} \\ = & \sum_{j = 1}^{n_i}X_{1ijk} + \sum_{j = 1}^{n_i}X_{2ijk} \\ = & \PR{\bm{X}_1 \circled{r} \bm{G}}_{ik} + \PR{\bm{X}_2 \circled{r} \bm{G}}_{ik} \\ = & \PR{\PC{\bm{X}_1 \circled{r} \bm{G}} + \PC{\bm{X}_2 \circled{r} \bm{G}}}_{ik}, \end{align*} $\forall i \in \chav{1, \ldots, n}, \forall k \in \chav{1, \ldots, p}$ $\implies (\bm{X}_1 + \bm{X}_2) \circled{r} \bm{G} = \PC{\bm{X}_1 \circled{r} \bm{G}} + \PC{\bm{X}_2 \circled{r} \bm{G}}$. \end{proof} For $\bm{X}_{N\times p}$ matrix with entries $X_{ijk}$ and a constant $c$, it is true that $(c\bm{X}) \circled{r} \bm{G} = c(\bm{X} \circled{r} \bm{G})$. \begin{proof} Consider the general term \begin{align*} \PR{(c\bm{X}) \circled{r} \bm{G}}_{ik} = & \sum_{j = 1}^{n_i}\PC{cX_{ijk}} \\ = & c\sum_{j = 1}^{n_i}X_{ijk} \\ = & c\PR{\bm{X} \circled{r} \bm{G}}_{ik} \\ = & \PR{c\PC{\bm{X} \circled{r} \bm{G}}}_{ik}, \end{align*} $\forall i \in \chav{1, \ldots, n}, \forall k \in \chav{1, \ldots, p}$ $\implies (c\bm{X}) \circled{r} \bm{G} = c(\bm{X} \circled{r} \bm{G})$. \end{proof} For $\bm{X}_{N\times p}$ matrix with entries $X_{ijk}$, $\bm{r}_{n\times 1}$ a column vector, $R = [r_{G_1}, \ldots, r_{G_N}]^T$ a $N\times 1$ vector with repeated entries for each index of $\bm{G}$ (constant by indices), it is true that $\bm{X^TR} = (\bm{X} \circled{r} \bm{G})^T\bm{r}$. \begin{proof} Consider the general term \begin{align*} \PR{\bm{X}^T\bm{R}}_{k} = & \sum_{l = 1}^{N}\PC{X_{lk}R_l} \\ = & \sum_{i = 1}^{n}\sum_{j = 1}^{n_i}\PC{X_{ijk}r_i} \\ = & \sum_{i = 1}^{n}r_i\sum_{j = 1}^{n_i}X_{ijk} \\ = & \sum_{i = 1}^{n}r_i\PR{\bm{X} \circled{r} \bm{G}}_{ik} \\ = & \PR{\bm{X} \circled{r} \bm{G}}_{1k}r_1 + \ldots + \PR{\bm{X} \circled{r} \bm{G}}_{nk}r_n \\ = & \PR{\PC{\bm{X} \circled{r} \bm{G}}^T}_{.k}\bm{r} \\ = & \PR{\PC{\bm{X} \circled{r} \bm{G}}^T\bm{r}}_k, \end{align*} $\forall k \in \chav{1, \ldots, p}$ $\implies \bm{X^TR} = (\bm{X} \circled{r} \bm{G})^T\bm{r}$. \end{proof} For $\bm{X}_{N\times p}$ matrix with entries $X_{ijk}$ and $\bm{Q}_{M\times p}$ a matrix with entries $Q_{mk}$, it is true that $(\bm{QX^T}) \circled{r} \bm{G}^T = \bm{Q}(\bm{X} \circled{r} \bm{G})^T$. \begin{proof} Consider the general term $\PR{\bm{Q}\bm{X}^T}_{ml} = \sum_{k = 1}^{p}Q_{mk}X_{lk}$, and \begin{align*} \PR{(\bm{Q}\bm{X}^T) \circled{r} \bm{G}^T}_{mi} = & \sum_{j = 1}^{n_i}\sum_{k = 1}^{p} Q_{mk} X_{ijk} \\ = & \sum_{k = 1}^{p} Q_{mk}\sum_{j = 1}^{n_i} X_{ijk} \\ = & \sum_{k = 1}^{p} Q_{mk}\PR{\PC{\bm{X} \circled{r} \bm{G}}}_{ik} \\ = & Q_{m1}\PR{\PC{\bm{X} \circled{r} \bm{G}}}_{i1} + \ldots + Q_{mp}\PR{\PC{\bm{X} \circled{r} \bm{G}}}_{ip} \\ = & \bm{Q}_{m.}\PR{\PC{\bm{X} \circled{r} \bm{G}}^T}_{.i} \\ = & \PR{\bm{Q}\PC{\bm{X} \circled{r} \bm{G}}^T}_{mi}, \end{align*} $\forall m \in \chav{1, \ldots, M}, \forall k \in \chav{1, \ldots, p}$ $\implies (\bm{QX^T}) \circled{r} \bm{G}^T = \bm{Q}(\bm{X} \circled{r} \bm{G})^T$. \end{proof} For $\bm{X}_{N\times p}$ matrix with entries $X_{ijk}$ and $\bm{P}_{p\times p}$ a squared matrix, it is true that $(\bm{XPX^T}) \circled{r} \bm{G} = (\bm{X} \circled{r} G)\bm{P}\bm{X}^T$. \begin{proof} \begin{align*} \PC{\bm{X}\bm{P}\bm{X}^T} \circled{r} \bm{G} = & \PC{\bm{X}\bm{K}} \circled{r} \bm{G} \\ = & \PC{\PC{\bm{K}^T\bm{X}^T} \circled{r} \bm{G}^T}^T \\ \stackrel{\text{1.4}}{=} & \PC{\bm{K}^T\PC{\bm{X} \circled{r} \bm{G}}^T}^T \\ = & \PC{\bm{X} \circled{r} \bm{G}}\bm{K} \\ = & \PC{\bm{X} \circled{r} \bm{G}}\bm{P}\bm{X}^T. \end{align*} \end{proof} For $\bm{X}_{N\times p}$ matrix with entries $X_{ijk}$ and $\bm{P}_{p\times p}$ a squared matrix, it is true that $((\bm{XPX^T}) \circled{r} \bm{G}) \circled{r} \bm{G}^T = (\bm{X} \circled{r} \bm{G})\bm{P}(\bm{X} \circled{r} \bm{G})^T$. \begin{proof} \begin{align*} \PC{\PC{\bm{X}\bm{P}\bm{X}^T} \circled{r} \bm{G}} \circled{r} \bm{G}^T \stackrel{\text{1.5}}{=} & \PC{\PC{\bm{X} \circled{r} \bm{G}}\bm{P}\bm{X}^T} \circled{r} \bm{G}^T \\ = & \PC{\bm{K}\bm{X}^T} \circled{r} \bm{G}^T \\ \stackrel{\text{1.4}}{=} & \bm{K}\PC{\bm{X} \circled{r} \bm{G}}^T \\ = & \PC{\bm{X}\circled{r}\bm{G}}\bm{P}\PC{\bm{X} \circled{r} \bm{G}}^T. \end{align*} \end{proof} For $\bm{X}_{N\times p}$ matrix with entries $X_{ijk}$, $\bm{r}_{n\times 1}$ a column vector, $R = [r_{G_1}, \ldots, r_{G_N}]^T$ a $N\times 1$ vector with repeated entries for each index of $\bm{G}$ (constant by indices) and $\bm{P}_{p\times p}$ a squared matrix, it is true that $(\bm{XPX^TR}) \circled{r} \bm{G} = (\bm{X} \circled{r} \bm{G})\bm{P}(\bm{X} \circled{r} \bm{G})^T\bm{r}$. \begin{proof} \begin{align*} \PC{\bm{X}\bm{P}\bm{X}^T\bm{R}} \circled{r} \bm{G} = & \PC{\bm{X}\bm{K}} \circled{r} \bm{G} \\ = & \PC{\PC{\bm{K}^T\bm{X}^T} \circled{r} \bm{G}^T}^T \\ \stackrel{\text{1.4}}{=} & \PC{\bm{K}^T\PC{\bm{X} \circled{r} \bm{G}}^T}^T \\ = & \PC{\bm{X} \circled{r} \bm{G}}\bm{K} \\ = & \PC{\bm{X} \circled{r} \bm{G}}\bm{P}\bm{X}^T\bm{R} \\ \stackrel{\text{1.3}}{=} & \PC{\bm{X} \circled{r} \bm{G}}\bm{P}\PC{\bm{X} \circled{r} \bm{G}}^T\bm{r}. \end{align*} \end{proof} \bibliographystyle{plainnat}
{'timestamp': '2020-08-18T02:17:46', 'yymm': '2008', 'arxiv_id': '2008.06911', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06911'}
arxiv
\section{Introduction} \parindent=2em The performance of the computer-aid diagnosis approach plays an important role in clinical care treatment \cite{cahan2017learning}. In which, chest x-ray is considered the most innovative technology for health services because of the possibility of application of several breakthrough technologies in artificial intelligence \cite{jaeger2013automatic}. AI can do this task quickly, and cheaply that can significantly improve diagnostics and ultimately treat the disease through chest radiographs. However, in many situations, poor quality images with complicated foreign objects are usually directly unexpected results. In which, foreign objects are a major hindrance to remove these factors which affect the performance of interpretation of chest radiographs. For instance, foreign elements are shown in figure \ref{fig:chexphoto-dataset}. \begin{figure}[htbp] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.6\linewidth, height=0.7\linewidth]{images/train_natural_iphone_patient08952_study6_view1_frontal.jpg} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.6\linewidth, height=0.7\linewidth]{images/train_natural_iphone_patient09842_study1_view1_frontal.jpg} \end{subfigure} \caption{CheXphoto images were captured from smartphone} \label{fig:chexphoto-dataset} \end{figure} Xue \cite{xue2015foreign} has the first novel technology for identification common foreign objects in chest radiographs that are linked four steps including normalization, image enhancement, segmentation, and button object. They performed circular hough transform (CHT) and Viola Jones algorithm. For CHT, this model has achieved 83\% precision and 85\% recall, by contrast of Viola Jones algorithm with 86\% precision and 94\% recall. Similarly, Zohora \cite{zohora2017foreign} has also applied multi-step including normalization and adjustment for pre-processing chest x-ray images. Next, they used edge detection to circle segmentation candidates and performed CHT to detect foreign object element. The results have achieved significantly including 96\% precision, 90\% recall, and 90\% F1 score. In 2018, they have shown a new approach to collect foreign elements-like unsupervised clustering with more than 90\% accuracy \cite{zohora2018circle}. Another method used a k-NN classifier algorithm was applied by Hogeweg \cite{hogeweg2013foreign} to remove different types of foreign objects such as brassier clips, jewelry, pacemakers, etc. However, these current models are no longer carried out in x-ray photography capturing cell phones which is one of the most challenging due to under various settings. In addition, only button objects were implemented in previous studies. In this paper, we deployed on CheXphoto datasets \cite{phillips2020chexphoto} that were created with multi-complicated foreign objects. In which, 10,507 photo x-ray images of 3,000 unique patients for training set that get a better insight into developing the detection model with high accuracy on smartphones. The first contribution of our proposed study is the novelty of the method. To the best of our knowledge, this is the first time a multi-step Deep Learning-based study has been carried out in order to handle foreign objects in chest radiographs captured by smartphone cameras. In addition, we achieved an acceptable accuracy of 90\%, while other metrics including IoU, Dice scores reached up to 81 and 90\% respectively. Another contribution of this study is that our study proposed a list of annotation criteria as long as the cross-validation label reviewing process to allow the consistency in annotating and reviewing the label. Finally, this study can serve as assistance in improving the performance of models in lung disease classification problems. The paper is structured as follows: Firstly, we briefly introduced previous studies for handling foreign objects and then we proposed methodology in five steps including data preparation, pre-processing, foreign object detection, segmentation and inpainting. Secondly, the experimental result section provided the achievement of our pipeline. Consequently, the conclusion was drawn in the discussion and future work section. \section{Experiment Design} In this study, we proposed a novel approach to remove foreign objects from initial chest radiographs guided by object detection and segmentation results. Figure \ref{fig:pipeline} and \ref{fig:actual-pipeline} describes 4 main stages included in the approach. In the following section, we will describe each step in detail including the pre-processing techniques, foreign object detection, detail segmentation and inpainting method. \begin{figure}[htbp] \centering \includegraphics[width=\linewidth]{images/pipeline.png} \caption{The proposed pipeline for our solution} \label{fig:pipeline} \end{figure} \begin{figure}[h] \centering \includegraphics[width=\linewidth]{images/pipeline_image.png} \caption{The actual processes given a raw input image.} \label{fig:actual-pipeline} \end{figure} \subsection{Data preparation} Our experiment was carried out on a subset of the cheXphoto dataset, including four types of lung diseases: pneumothorax, effusion, pneumonia, atelectasis without uncertain labels for all (Table \ref{tab:data-stat}). These chest x-ray images were collected from the cheXphoto dataset with natural and synthetic transformation, removed lateral style. Afterward, we continually filtered out non-foreign object images. The remaining images with complicated foreign objects were applied to the training model. To prove the contribution of the inpainting technique in improving the performance of classification models, we adopted the second experiment and constructed another dataset (Table \ref{tab:test-train}). Samples from this dataset were selected from the original chexPhoto dataset. To enable independence from the inpainting dataset and avoid any possible bias or imbalance, samples were selected in the way such that, there is no overlap between the inpainting dataset and the classification dataset, moreover, the ratio between both classes in the dataset remains balanced. \begin{table}[htbp] \centering \begin{tabular}{|l|r|r|r|r|r|} \hline & \multicolumn{1}{l|}{Pneumonia} & \multicolumn{1}{l|}{Atelectasis} & \multicolumn{1}{l|}{Pneumothorax} & \multicolumn{1}{l|}{Pleural Effusion} & \multicolumn{1}{l|}{No finding} \\ \hline Train set & 32 & 359 & 251 & 950 & 132\\ \hline Validation set & 14 & 94 & 49 & 202 & 33 \\ \hline Test set & 8 & 99 & 74 & 189 & 38 \\ \hline \end{tabular} \caption{Number of chest x-ray images for training, test and validation} \label{tab:data-stat} \end{table} \begin{table}[htbp] \centering \begin{tabular}{|l|r|r|r|} \hline & Normal & Abnormal \\ \hline Train set & 196 & 200\\ \hline Test set & 66 & 56\\ \hline \end{tabular} \caption{Number of chest x-ray images for training, test set used for the classification task} \label{tab:test-train} \end{table} \textbf{Annotations method} By default, the CheXphoto dataset does not include any annotations for object detection or segmentation. Thus, we have to determine the standards of the annotation criteria and the reviewing process for both object detection and segmentation tasks. To ensure the consistency and accuracy in annotations, we thereby follow a cross-validation reviewing progress, where each image has to be reviewed by at least two people. Each image is scanned to identify if it follows all of the below criteria mentioned in table \ref{tab:standard-annotation}. If any criteria are disobeyed, the image’s annotations are cleared completely, and the image is put back to the queue of annotation and reviewed again. \begin{table}[htbp] \begin{tabular}{|l|l|} \hline Criteria & Requirements \\ \hline Shape of objects & \vtop{\hbox{\strut Sickle or round or earbud-like shaped objects}\hbox{\strut \begin{tabular}{p{2cm}p{2cm}p{2cm}} \begin{minipage}{0.33\textwidth} \includegraphics[width=0.25\linewidth, height=0.3\linewidth]{images/sickle.jpg} \end{minipage} & \begin{minipage}{0.33\textwidth} \includegraphics[width=0.25\linewidth, height=0.3\linewidth]{images/round.jpg} \end{minipage} & \begin{minipage}{0.33\textwidth} \includegraphics[width=0.25\linewidth, height=0.3\linewidth]{images/earbud.jpg} \end{minipage} \end{tabular} }} \\ \hline Location & Within and located in the centre of the bounding boxes \\ \hline Region & An object is annotated as long as the object is in or is partly in the lung region \\ \hline Number of vertices in a bounding box & At least 6-8 vertices are required for each bounding box \\ \hline Number of objects & The number of objects annotated by each reviewers have to be the same \\ \hline \end{tabular} \caption{Standards of the annotation criterias} \label{tab:standard-annotation} \end{table} \subsection{Pre-processing} Initially, the chest x-ray images are extracted from the original images. To ensure the consistency in pixel values among different images, we thereby normalize all images to the range of [0-255] in pixel values. The normalized samples are then resized to a predefined size of WxH. \subsection{Foreign object detection} In order to separate the regions of interest (ROIs), for instance, the undesired and foreign object, from the pre-processed images, we trained a YOLOv4-based model \cite{bochkovskiy2020yolov4} to detect the rectangles surrounding the targets. Thus, this step enables us to cut out the focused region only, instead of having to work on the whole global and large images. The foreign object detection model is constructed based on the widely-known Yolov4 architecture, which has an initial learning rate of 0.00261, batch size of 4 over 100 epochs. The loss function used is the GIoU loss. After this step, every single foreign object is separated into an image, which is then fed to the segmentation model. \subsection{Foreign object segmentation} For the segmentation task, we adopt a UNET-like structure \cite{ronneberger2015u} for the segmentation model. Instead of using the vanilla encoder, we made use of the popular EfficientNet-B0 model as the chosen encoder \cite{tan2019efficientnet}. We used the custom BCE-Dice loss as the cost function and Dice score and Intersection over Union ratio as learning metrics. The model is trained for 100 epochs, with a learning rate of 0.01 and a batch size of 8. Upon the completion of this step, the binary masks for foreign objects are generated, in which positive pixels are marked equal to the maximum intensity values (255) otherwise, negative pixels are marked as minimum intensity values (0). \subsection{Foreign object inpainting} The inpainting technique enables the removal of unwanted objects and the reconstruction of the hidden part in the target images. In this study, we used the Fast Marching algorithm to tackle the challenges of having noisy, undesired foreign objects in the chest x-rays. The algorithm inpainted a pixel by assigning it with a normalized weighted sum of all its surrounding neighbor pixels. We determined the size of the circular neighborhood surrounding every considered pixel by the radius size of T. After this step, the foreign objects should be completely cleared from the ROI images. It is worth mentioning that the in-painted ROIs are then merged back to the original images. \subsection{Evaluation metrics} To evaluate the overall performance and the efficiency of the approach, we proposed several metrics for deeper analysis. We proposed the mean difference in object counting (MDOC) (Eq. \ref{eq:MDOC}) to quantify the object detection ability of the model. Subsequently, the average Dice score (avgDice) (Eq. \ref{eq:avgDice}) between predicted objects and ground truth objects is also employed to assess how overlapped, similar or accurate the predicted objects are, in comparison to the ground-truths, in pixel-level. Conventional metrics such as accuracy, precision, recall and F1-score are also accounted for better assessment. \begin{eqfloat} \begin{equation} MDOC = \frac{1}{\sum_i^N C_i} \times \sum_i^N (C_i - \hat{C}_i) \end{equation} \caption{Formula of the mean difference in object counting metric} \label{eq:MDOC} \end{eqfloat} $C_i$ denotes the total number of foreign objects existing in sample $i^{th}$, $\hat{C}_i$ denotes the total number of predicted foreign objects existing in sample $i^{th}$ \begin{eqfloat} \begin{equation} avgDice = \sum_i^N\sum_j^M Dice(B_{ij}, \hat{B}_{ij}) \end{equation} \caption{Formula of the average Dice score metric} \label{eq:avgDice} \end{eqfloat} Where N, M denotes the number of samples and objects available in the dataset, and each sample respectively. $B_j$ and $B_j$ represents the ground-truth and the predicted binary masks of the object $j^{th}$ in sample $i^{th}$ \section{Result} \subsection{Object detection} The results obtained with state-of-the-art object detectors. Our model detector got the below results with the image size set 512x512 and confidence threshold 30\%, IOU threshold 60, batch size when evolution using 16 on the test-set we extracted from ChexPhoto dataset. Our model has defined that the object foreign on the boundary of lung region is true positive and by contrast that of false positive. The percentage of precision, recall, and F1 was 76\%, 70\%, and 73\%, respectively. Meanwhile, around 61\% for [email protected]. Table 3 showed several examples of output metrics in object detection. \begin{table}[htbp] \centering \begin{tabular}{|c|c|c|c|c|} \hline Ground Truth & Precision & Recall & F1-score & [email protected] \\ \hline 1524 & 76 & 70 & 73 & 61 \\ \hline \end{tabular} \caption{Result of foreign object detection} \label{tab:OD-result} \end{table} \begin{figure}[ht] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/true_positive.jpeg} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/true_positive2.jpeg} \end{subfigure} \caption{True positives of foreigin object detector} \label{fig:true-positive} \end{figure} \begin{figure}[htbp] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/false.jpeg} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/false2.jpeg} \end{subfigure} \caption{False positive of foreign object detector} \label{fig:false-positive} \end{figure} \subsection{Segmentation} Table \ref{tab:segment-result} reveals the obtained result utilizing the aforementioned segmentation strategy. The threshold to distinguish between positive pixels and negative pixels is 0.5 by default. Figure \ref{fig:result_no_score} illustrates several examples obtained, where raw inputs and predictions are plotted against the annotated ground-truths. As a result in table 4, predicted bounding boxes and obtained the level of overlap were considered through Dice and IoU [email protected] that have achieved high accuracy with 0.8889, and 0.8045, respectively. The output is closely matched with foreign objects in figure 4. Moreover, pixel-level [email protected] had a similar tendency of around 93.12\%. \begin{figure} \centering \includegraphics[width=0.5\linewidth]{images/result_no_score.png} \caption{Examples of raw-inputs, ground-truths and binary mask generated from segmentation models} \label{fig:result_no_score} \end{figure} \begin{table}[htbp] \centering \begin{tabular}{|c|c|c|} \hline Dice score @0.5 & IoU score @0.5 & Pixel-level accuracy @0.5 \\ \hline 0.8889 & 0.8045 & 0.9312 \\ \hline \end{tabular} \caption{Results of the segmentation task} \label{tab:segment-result} \end{table} \subsection{Inpainting results} We examined the performance of the proposed approach by determining the number and the percentage of the objects removed. After processing, the images were reviewed again to check if all foreign objects were inpainted and cleaned completely. If yes, we increased the count, otherwise we continue with the next images. Thus, in the end, we reported in table 6 the number of completely foreign object- inpainted images as long as their corresponding percentage. To the best of our knowledge, currently, there is an acknowledged lack of quantitative metrics for image inpainting quality evaluation \cite{Dang2013visual}. Conventional metrics are often subjective or only specifically adapted to a particular issue. Thus, we thereby evaluated the usefulness and performance of the proposed approach by assessing the contribution of chest radiograph inpainting to the performance of CNN-based lung abnormality detection models. For every model architecture, we trained the model with 2 versions of the same dataset: the original version and the inpainted version. Other settings and hyperparameters were left unchanged. The models are built based on conventional and state of the art architectures, such as VGG16, Resnet50 and EfficientNet-B2. Performance on the test set of every architecture is then recorded in table 7 for comparison and illustrate the effectiveness of the proposed method in improving the models learning ability. \begin{table}[htbp] \centering \begin{tabular}{|c|c|c|c|} \hline Measurements & Total images available & Number of completely inpainted images & \% of inpainted images \\ \hline Values & 501 & 428 & 85 \\ \hline \end{tabular} \caption{Evaluation of the performance of the object inpainting approach} \label{tab:evaluation-result} \end{table} \begin{table}[htbp] \centering \begin{tabular}{|l|l|l|l|l|l|l|l|l|} \hline \multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}\\Architectures\end{tabular}} & \multicolumn{4}{l|}{Original Dataset} & \multicolumn{4}{l|}{Image Inpainting Dataset} \\ \cline{2-9} & Accuracy & Precision & Recall & F1 & Accuracy & Precsion & Recall & F1 \\ \hline VGG16 & 0.432 & 0.432 & 0.432 & 0.432 & 0.465 & 0.480 & 0.480 & 0.465 \\ \hline Resnet50 & 0.642 & 0.681 & 0.662 & 0.633 & 0.680 & 0.690 & 0.690 & 0.680 \\ \hline Efficientnet-b2 & 0.561 & 0.580 & 0.575 & 0.559 & 0.570 & 0.580 & 0.580 & 0.580 \\ \hline \end{tabular} \caption{Comparison of original and inpainted data in terms of model performance} \end{table} \begin{figure}[htbp] \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/train_synthetic_digital_patient37789_study2_view1_frontal.jpg} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/train_natural_nokia_patient54039_study2_view1_frontal.jpg} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/train_synthetic_digital_patient19062_study9_view1_frontal.jpg} \end{subfigure} \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=.8\linewidth, height=0.7\linewidth]{images/train_natural_nokia_patient43298_study7_view1_frontal.jpg} \end{subfigure} \caption{Inpainting} \label{fig:Inpainting} \end{figure} \section{Discussion and Future work} \subsection{Discussion} To conclude, we mainly focused on removing foreign objects in the center of the lung region of chest radiographs. As a result of object detection, our model has detected different types of foreign objects in chest x-ray images captured by smartphone instead of screening or file images. However, because of the evaluation metrics focused on the lung region, false positives were defined as outside the lung region boundary that led to diminishing accuracy. In addition, the big size objects haven’t been supported. Towards segmentation, our model had a high score in predicted bounding boxes. These outcomes strongly supported removing foreign objects in inpainting section. As mentioned by \cite{Dang2013visual}, the current image inpainting lacks good quantitative assessment metrics. Thereby, instead of directly evaluating the metrics for the image inpainting task, we assess its contribution to the improvement of the lung abnormality detection models. Reported results in table 7 show that, when applying these techniques with different architectures, we witnessed a significant improvement among conventional classification metrics such as accuracy, F1, Recall and Precision. In details, for the lightest architecture, VGG16, we obtained a 3.3\% improvement in the accuracy score, while for Resnet50-based architecture and Efficient Net-b2-based architecture, that number is 3.8\% and 0.9\% respectively. It is worth noting that, in all cases, using the inpainting technique led to the improvement of F1-scores, precision and recall. In other words, we observe that no trade off between precision and recall happened. It also indicated that the Type I and Type II error are reduced consecutively. The experimental achievements will probably apply for the automatic detection of complicated images. \subsection{Limitation} Although the paper has achieved high performance by removing the foreign object and proposed methodology, we always acknowledge the limitation of our research. The first limitation is that, since this study is the first one in designing a particular solution to handle the foreign objects in the CheXphoto dataset, it is clear that at the time we were writing, there is no other existing study for us to compare. Secondly, it is worth noting that the object detection and segmentation annotations were conducted under our defined regulations and standards. Thus, these standards may be applicable to the current dataset only. To address this problem, we need to build a gold standard to encompass foreign objects in general, for example, direction, diagonal length, box area, etc. Third, our approach requires several models working subsequently. Thus, it is not a lightweight solution that can be either applied in Edge devices, or in mobile applications. \subsection{Future work} In future work, this model can probably be used in terms of model detection for multi-label lung disease to the cheXphoto dataset. Moreover, we continually plan to mitigate foreign objects outside the lung region as well as other objects. \section{Acknowledgments} We would like to give a thank to our friends who collected dataset and labeled segmentation. Ms. Nhung H. Tran (University of Medicine and Pharmacy), Ms.Huong T. T. Nguyen (Hanoi National University of Education). \bibliographystyle{unsrt}
{'timestamp': '2020-08-18T02:14:10', 'yymm': '2008', 'arxiv_id': '2008.06828', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06828'}
arxiv
\section{Introduction} Spatio-temporal video grounding is an emerging task in the cross-modal understanding field. Given a sentence depicting an object, this task aims to retrieve the spatio-temporal tube of the queried object, i.e. a sequence of bounding boxes. Most existing spatio-temporal grounding methods~\cite{chen2019weakly,shi2019not} are restricted to well-aligned segment-sentence pairs, where the segment has been trimmed from the raw video and is temporally aligned to the sentence. Recently, researchers~\cite{zhang2020does} begin to explore spatio-temporal video grounding~(STVG) on unaligned data and multi-form sentences. Concretely, as shown in Figure~\ref{fig:exp}, either the declarative sentence or interrogative sentence describes a short-term action of the target object "child" and matches with the spatio-temporal tube within a small segment. To localize the target existence in a fleeting clip, we need to distinguish the subtle status of the object according to the textual information. Specifically, the sentence often illustrates diverse relationships between the queried object with other objects, thus the key of this task is to capture these crucial relations in video contents to identify the spatio-temporal tube. Particularly, the interrogative sentences depict unknown objects and lack the explicit information of the object, e.g., the direct characteristics "a child in yellow" in Figure~\ref{fig:exp}. Grounding these sentences can only depend on the object relationships such as the action relation "kicking a ball" and spatial relation "in front of the goal". \begin{figure}[t] \centering \includegraphics[width=0.45\textwidth]{example3} \caption{An example of spatio-temporal video grounding on unaligned data and multi-form sentences.}\label{fig:exp} \end{figure} Although existing grounding methods~\cite{yamaguchi2017spatio,chen2019weakly} have achieved excellent performance on aligned segment-video pairs, they are ineffectively applied to unaligned data and multi-form sentences. On the one hand, they heavily rely on the tube pre-generation to extract a series of candidate tubes and then select the most relevant one according to the sentence. But without the temporal alignment, it is difficult to pre-generate reasonable candidate tubes. On the other hand, these approaches always ignore the relation construction between objects and model each tube individually. Recently, Zhang et al.~\cite{zhang2020does} explore spatio-temporal grounding on unaligned data. They incorporate the textual clues into region features and employ spatio-temporal graph reasoning to retrieve the spatio-temporal tube. Despite this method tries to capture object relations by cross-modal region interactions, it does not exclude inessential regions from massive region proposals and may lead to severe obstruction for effective relation modeling. Concretely, there are a large number of objects in videos but most of them are irrelevant to the textual descriptions. ~\cite{zhang2020does} fails to filter out the unnecessary ones and remain in the coarse relation modeling for all regions. Hence, we need to pay more attention to the crucial objects mentioned in the sentence and build sufficient cross-modal relation reasoning between them for precise video grounding. In this paper, we propose a novel Object-Aware Multi-Branch Relation Network~(OMRN) for object-aware fine-grained relation reasoning. We first extract region features from the video and learn object representations corresponding to the nouns in the sentence. We then employ multiple branches to develop object-aware region modeling and discover the notable regions containing informative objects, where the main branch corresponds to the queried object and each auxiliary branch focuses on an object mentioned in the sentence. Concretely, we apply the object-aware modulation to strengthen object-relevant region features and weaken unnecessary ones in each branch. Next, we can conduct object-region cross-modal matching in each branch. After it, we propose the multi-branch relation reasoning to capture critical object relationships between the main branch and auxiliary branches, where the irrelevant regions are filtered out by preceding matching scores. Further, considering each branch should only focus on its corresponding object, we devise a diversity loss to make different branches pay attention to different regions, that is, have diverse distributions of matching scores. Eventually, we apply a spatio-temporal localizer to determine the temporal boundaries and retrieve the target tube. The main contributions of this paper are as follows: \begin{itemize} \item We propose a novel object-aware multi-branch relation network for spatio-temporal video grounding, which can discover object-aware fine-grained relations and retrieve the accurate tubes of the queried objects. \item We devise multiple branches with a diversity loss to develop object-aware region modeling, where each branch focuses on a crucial object mentioned in the sentence and the diversity loss makes different branches focus on their corresponding objects. \item We employ the multi-branch relation reasoning to capture critical object relationships between the main branch and auxiliary branches. \item The extensive experiments show the effectiveness of our object-aware multi-branch framework. \end{itemize} \section{Related Work} In this section, we briefly review some related work on visual grounding and video grounding. Visual grounding is to localize the object in an image according to the referring expression. Early approaches~\cite{hu2016natural,nagaraja2016modeling} often model the language information by RNN, extract region features through CNN and then learn the object-language alignment. Recent methods~\cite{yu2018mattnet,hu2017modeling} parse the expression into multiple parts and compute cross-modal alignment scores for each part. Furthermore, \cite{deng2018visual,zhuang2018parallel} employ the co-attention mechanism to develop cross-modal interactions for fine-grained matching. And~\cite{yang2019dynamic,yang2019cross} capture the relations between regions to boost the grounding accuracy. Video grounding can be categorized into temporal grounding and spatio-temporal grounding. Given a sentence, temporal grounding localizes a temporal clip in the video. Early methods~\cite{hendricks2017localizing,gao2017tall} apply a proposal-and-selection framework that first samples massive candidate clips and then select the most relevant one semantically matching with the sentence. Recently, \cite{chen2019localizing,zhang2019cross,lin2020moment} develop frame-by-word interactions between visual and textual contents and discover the dynamical clues by attention mechanism. \cite{zhang2019man} explicitly model moment-wise relations as a structured graph and employ an iterative graph adjustment. \cite{yuan2019semantic} propose a semantic conditioned dynamic modulation for better correlating video contents over time and \cite{zhang2019learning} adopt a 2D temporal map to cover diverse moments with different lengths. In the weakly-supervised setting, \cite{mithun2019weakly} leverage the attention scores to align moments with sentences, and \cite{lin2019weakly} propose a semantic completion network to estimate each clip by language reconstruction. Besides natural language queries, Zhang et al.~\cite{zhang2019localizing} try to detect the unseen video clip according to image queries. Spatio-temporal video grounding is a natural extension of temporal grounding, which retrieves a spatio-temporal tube from a video corresponding to the sentence. Most existing approaches are designed for well-aligned segment-sentence data. \cite{yamaguchi2017spatio} only ground the person tube in multiple videos and \cite{zhou2018weakly,chen2019weakly} further retrieve the spatio-temporal tubes of diverse objects from trimmed videos by weakly-supervised MIL methods. Different from single-object grounding, \cite{Huang_2018_CVPR,shi2019not} localize each noun or pronoun of sentences in frames. Recently, \cite{zhang2020does} explore spatio-temporal grounding on unaligned data by spatio-temporal cross-modal graph modeling. But it still fails to capture the critical objects and remains in the coarse relation reasoning. In this paper, we explore object-aware fine-grained relation modeling and further improve the grounding accuracy. \begin{figure*}[t] \centering \includegraphics[width=0.9\textwidth]{./framework3} \caption{The Overall Architecture of Object-Aware Multi-Branch Relation Network. }\label{fig:framework} \end{figure*} \section{The Proposed Method} As shown in Figure~\ref{fig:framework}, we propose the object-aware multi-branch relation network (OMRN) for this STVG task, where we develop object-aware multi-branch region modeling to discover the notable regions containing informative objects and devise multi-branch relation reasoning to capture critical object relationships. \subsection{Region and Object Extraction} Given a video ${\bf v}$, we extract region features $\{ \{{\bf r}^{n}_k\}_{k=1}^K \}_{n=1}^N$ by a pre-trained Faster R-CNN, where the video has $N$ frames and each frame contains $K$ regions. The feature ${\bf r}^{n}_k$ corresponds to the $k$-th region in frame $n$. And each region is also associated with a bounding box ${\bf b}^n_k = (x^n_k, y^n_k,w^n_k,h^n_k)$, where $(x^n_k, y^n_k)$ are the center coordinates and $(w^n_k,h^n_k)$ are the box width and height. Considering video grounding requires to capture the object dynamics but region features extracted from still frames lack motion information, we then adopt a temporal region aggregation method to incorporate dynamic clues from forward $L$ frames and backward $L$ frames into each region. Concretely, if two regions in adjacent frames have similar semantic features and spatial locations, we expect them to contain the same object. Thus, the linking score between region ${\bf r}^{n_1}_{i}$ and ${\bf r}^{n_2}_{j}$ by \begin{eqnarray} & s({\bf r}_i^{n_1}, {\bf r}_j^{n_2}) = {\rm cos}({\bf r}_i^{n_1}, {\bf r}_j^{n_2}) + \frac{\alpha}{|n_2-n_1|} \cdot {\rm IoU}({\bf b}_i^{n_1}, {\bf b}_j^{n_2}), \nonumber \end{eqnarray} where the ${\rm cos}(\cdot)$ means the cosine similarity of two features and ${\rm IoU}(\cdot)$ is the IoU score of their bounding boxes. The $|n_2-n_1|$ is the temporal distance of two regions and applied to limit the IoU score. And $\alpha$ is a balanced coefficient. For each region, we select the region with the maximal linking score from each adjacent frame and obtain $2L$ relevant features. Next, we apply a mean pooling on the $2L+1$ features to absorb region dynamics, followed by a linear layer for feature transformation. For simplicity, we still denote the pooled region features with temporal dynamics by $\{ \{{\bf r}^{n}_k\}_{k=1}^K \}_{n=1}^N$. For language modeling, we input word embeddings of the sentence into a Bi-GRU to learn the word-level semantic features $\{{\bf s}_m\}_{m=1}^M$ with $M$ words. After it, we learn object features with context information for each object mentioned in the sentence. Specifically, we first identify all nouns in the sentence using the library of NLTK. Assuming there are $T$ nouns in the sentence, each noun points to an object in the video and the $t$-th noun corresponds to the word-level feature ${\bf s}_t$. In Figure~\ref{fig:framework}, the sentence contains three objects "child", "ball" and "goal", and we aim to retrieve the spatio-temporal tube of the main object "child" (i.e. the queried object). For interrogative sentences, we regard the interrogative words (e.g. "who" and "what") as the main objects. Next, we apply a context attention to aggregate the language context for each object by \begin{eqnarray} &\beta_{t,m} = {\bf w}^{\top}{\rm tanh}({\bf W}_1^s {\bf s}_{t} + {\bf W}_2^s{\bf s}_{m} + {\bf b}^s), \nonumber\\ &{\bf \widetilde o}_t = \sum \limits_{m=1}^{M} {\rm softmax}({\beta}_{t,m})\cdot {\bf s}_{m}, \ {\bf o}_t = [{\bf s}_t;{\bf \widetilde o}_t], \nonumber \end{eqnarray} where ${\bf W}_1^s$, ${\bf W}_2^s$ are projection matrices, ${\bf b}^s$ is the bias and ${\bf w}^{\top}$ is the row vector. The ${\beta}_{t, m}$ is the attention weight of object $t$ for the $m$-th word. Finally, we obtain the object features $\{{\bf o}_t\}_{t=1}^T$, where ${\bf o}_1$ is the feature of the main object and $\{{\bf o}_t\}_{t=2}^T$ are auxiliary object features. \subsection{Object-Aware Multi-Branch Relation Reasoning} We next devise object-aware multi-branch relation reasoning with a diversity loss to capture object-aware fine-grained relations. Concretely, we first take multiple branches to learn object-aware region features and then apply multi-branch relation reasoning to capture critical object relationships from multiple branches, where the main branch corresponds to the main object and auxiliary branches correspond to auxiliary objects. And the diversity loss makes different branches focus on their corresponding objects. \subsubsection{Object-Aware Multi-Branch Region Modeling} For branch $t$ with object ${\bf o}_t$, we first apply the object-aware modulation to strengthen object-relevant region features and weaken unnecessary ones. Concretely, we produce the object-aware modulation vectors by \begin{eqnarray} & {\bm \gamma}_t = {\rm tanh}({\bf W}^{\gamma} {\bf o}_{t}+ {\bf b}^{\gamma}), \ {\bm \delta}_t = {\rm tanh}({\bf W}^{\delta} {\bf o}_{t}+ {\bf b}^{\delta}), \nonumber \end{eqnarray} where ${\bm \gamma}_t$ and ${\bm \delta}_t$ are the modulation gate and bias based on object $t$. We then modulate all region features by \begin{eqnarray} & {\bf r}^n_{tk} = {\bm \gamma}_t \odot {\bf r}^n_k + {\bm \delta}_t, \nonumber \end{eqnarray} where $\odot$ is the element-wise multiplication and ${\bf r}^n_{tk}$ means the object-aware region feature in branch $t$. The modulation vectors are expected to emphasize region features containing the object $t$ and weaken unrelated ones. In branch $t$, we then conduct cross-modal matching between region features ${\bf r}^n_{tk}$ and the object feature ${\bf o}_{t}$ by \begin{eqnarray} &{d}^n_{tk} = {\bf w}^{\top} {\rm tanh}({\bf W}^{c} [{\bf r}^n_{tk}; {\bf o}_{t}; {\bf r}^n_{tk} \odot {\bf o}_{t}; {\bf r}^n_{tk} -{\bf o}_{t}]+ {\bf b}^{c}), \nonumber \end{eqnarray} where ${d}^n_{tk} $ is the matching score of region $k$ in frame $n$ on branch $t$. Next, we apply the softmax function on ${d}^n_{tk}$ to obtain the matching score distribution over regions, given by ${\hat d}^n_{tk} = \frac{{\rm exp}({d}^n_{tk})}{\sum_{k=1}^{K} {\rm exp}({d}^n_{tk})}$. It is used to multi-branch relation reasoning for critical object relation discovery and is also applied to construct the diversity loss between multiple branches. \subsubsection{Multi-Branch Relation Reasoning} Next, we develop the multi-branch relation reasoning in each frame to capture critical object relationships by integrating auxiliary branches into the main branch. Concretely, the branch $t$ focuses on its corresponding object $t$ and has learnt the object-aware region feature ${\bf r}^n_{tk}$ with the matching score ${\hat d}^n_{tk}$. To build the relation between the main object (i.e. object $1$) and auxiliary object $t$ in each frame, we absorb crucial clues of notable regions from the branch $t$ into the main branch. We estimate the attention weight between the $k$-th region ${\bf r}^n_{1k}$ in the main branch (i.e. branch $1$) and the $l$-th region ${\bf r}^n_{tl}$ in the auxiliary branch $t$ by \begin{eqnarray} & \epsilon_{1k,tl}^n = {\bf w}^{\top}{\rm tanh}({\bf W}_1^m {\bf r}^n_{1k} + {\bf W}_2^m {\bf r}^n_{tl} + {\bf W}_3^m{\bf b}^n_{1k,tl} + {\bf b}^m), \nonumber \end{eqnarray} where ${\bf b}^n_{1k,tl}$= $[x^n_{1k,tl};y^n_{1k,tl};w^n_{1k,tl};h^n_{1k,tl}]$ is the relative geometry vector between region ${\bf r}^n_{1k}$ and ${\bf r}^n_{tl}$, given by \begin{eqnarray} & x^n_{1k,tl} = (x^n_{1k} - x^n_{tl})/w^n_{tl}, \ y^n_{1k,tl} = (y^n_{1k} - y^n_{tl})/h^n_{tl}, \nonumber\\ & w^n_{1k,tl} = {\rm log}(w^n_{1k} / w^n_{tl}), \ h^n_{1k,tl} = {\rm log}(h^n_{1k} / h^n_{tl}). \nonumber \end{eqnarray} Thus, the attention weight $\epsilon_{1k,tl}^n$ is built on object-aware features ${\bf r}^n_{1k}$ and ${\bf r}^n_{tl}$ with the spatial location information. After it, we aggregate the regions relevant to object $t$ from the auxiliary branch $t$ by \begin{eqnarray} & {\hat \epsilon}_{1k,tl}^n = \frac{{\rm exp}(\epsilon_{1k,tl}^n)}{\sum_{l=1}^{K} {\rm exp}(\epsilon_{1k,tl}^n)}, \ {\bf r}^n_{1k, t} = \sum \limits_{l=1}^{K} {\hat d}^n_{1k} \cdot {\hat d}^n_{tl} \cdot {\hat \epsilon}_{1k,tl}^n \cdot {\bf r}^n_{tl}, \nonumber \end{eqnarray} where ${\bf r}^n_{1k, t}$ is the aggregation feature from branch $t$ for the region $k$ in the main branch. We first apply the softmax on the attention weights $\epsilon_{1k,tl}^n$ and then aggregate region features with the matching scores ${\hat d}^n_{1k}$ and ${\hat d}^n_{tl}$ as weighting terms. Thus, the relation reasoning between the main object and auxiliary object $t$ will focus on notable regions with higher matching scores ${\hat d}^n_{tl}$ and filter out inessential ones. Simultaneously, by the prior confidence ${\hat d}^n_{1k}$ of the main object, we can enhance the relation modeling for these regions with higher ${\hat d}^n_{1k}$ in the main branch. After multi-branch relation reasoning from all auxiliary branches, we learn the multi-branch aggregation features $\{ {\bf r}^n_{1k, t} \}_{t=2}^T$ for each region $k$ of frame $n$ in the main branch. We then obtain the final object-aware multi-branch features $\{ \{ {\bf \widetilde r}^n_{k} \}_{k=1}^K \}_{n=1}^N$ by \begin{eqnarray} & {\bf \widetilde r}^n_{k} = {\rm ReLU}({\bf r}^n_{1k} + \sum \limits_{t=2}^{T} {\bf r}^n_{1k, t}). \nonumber \end{eqnarray} \subsubsection{Diversity Loss Between Branches} Considering each branch should only focus on its corresponding object, we devise a diversity loss to make different branches have diverse score distributions over regions. Specifically, we denote the score distribution in the frame $n$ on branch $t$ as ${\bf \hat d}^n_{t}=[{\hat d}^n_{t1},\dots, {\hat d}^n_{tK}]^{\top}$ and calculate the diversity loss by the distribution similarity between multiple branches as follows: \begin{eqnarray} & {\mathcal L}_{d} = \frac{1}{Z}\sum_{n \in {\mathcal S}_{gt}}\sum_{i=1}^{T-1}\sum_{j=i+1}^{T} ({\bf \hat d}^n_{i})^{\top} ({\bf \hat d}^n_{j}), \nonumber \end{eqnarray} where ${\mathcal S}_{gt}$ is the set of frames in the ground truth segment and $Z = \frac{1}{2}|{\mathcal S}_{gt}|T(T-1)$ is the normalization factor. This diversity loss encourages each branch to pay more attention to the region matching with the corresponding object. \begin{table*}[t] \centering \begin{tabular}{c|cccc|cccc} \hline \multirow{2}{*}{Method}& \multicolumn{4}{c|}{Declarative Sentence Grounding} & \multicolumn{4}{c}{Interrogative Sentence Grounding} \\ & m\_tIoU & m\_vIoU& [email protected] &[email protected] &m\_tIoU & m\_vIoU& [email protected] &[email protected] \\ \hline GroundeR + TALL&\multirow{3}{*}{34.63\%}&9.78\%&11.04\%&4.09\%&\multirow{3}{*}{33.73\%}&9.32\%&11.39\%&3.24\% \\ STPR + TALL&&10.40\%&12.38\%&4.27\%&&9.98\%&11.74\%&4.36\% \\ WSSTG + TALL&&11.36\%&14.63\%&5.91\%&&10.65\%&13.90\%&5.32\%\\ \hline GroundeR + L-Net&\multirow{3}{*}{40.86\%}&11.89\%&15.32\%&5.45\%&\multirow{3}{*}{39.79\%}&11.05\%&14.28\%&5.11\% \\ STPR + L-Net&&12.93\%&16.27\%&5.68\%&&11.94\%&14.73\%&5.27\%\\ WSSTG + L-Net&&14.45\%&18.00\%&7.89\%&&13.36\%&17.39\%&7.06\%\\ \hline STGRN&48.47\%&19.75\%&25.77\%&14.60\%&46.98\%&18.32\%&21.10\%&12.83\%\\ \hline OMRN (Ours)&{\bf 50.73\%}&{\bf 23.11\%}&{\bf 32.61\%}&{\bf 16.42\%}&{\bf 49.19\%}&{\bf 20.63\%}&{\bf 28.35\%}&{\bf 14.11\%}\\ \hline \end{tabular} \caption{Performance Evaluation Results on the VidSTG Dataset.}\label{table:mainexp} \end{table*} \subsection{Spatio-Temporal Localization} In this section, we apply a spatio-temporal localizer to predict the spatio-temporal tube of the queried object based on final region features $\{ \{ {\bf \widetilde r}^n_{k} \}_{k=1}^K \}_{n=1}^N$, including the temporal moment localization and spatial region localization. For spatial localization, we estimate the region confidence scores according to the main object feature ${\bf o}_1$ by \begin{eqnarray} & {p}^{n}_k = \sigma( ({\bf W}^r {\bf \widetilde r}^n_{k})^{\top} ({\bf W}^o {\bf o}_1)), \nonumber \end{eqnarray} where $\sigma$ is the sigmoid function and ${p}^{n}_k$ is the confidence score of region $k$ in frame $n$. Next, we apply the spatial loss to guide the spatial localization where we only consider frames in the set ${\mathcal S}_{gt}$, i.e. in the ground truth segment. We first compute the IoU score ${\rm IoU}^{n}_k$ of each region with the corresponding ground truth region and then calculate the spatial loss by \begin{equation} \begin{aligned} {\mathcal SL}^n_{k} &= (1 - {\rm IoU}_{k}^n) \cdot {\rm log}(1 - {p}_{k}^n) + {\rm IoU}_{k}^n \cdot {\rm log}({p}_{k}^n), \\ \nonumber {\mathcal L}_{s} &= -\frac{1}{|{\mathcal S}_{gt}|K}\sum_{n \in {\mathcal S}_{gt}}\sum_{k=1}^{K} {\mathcal SL}^n_{k}. \end{aligned} \end{equation} For temporal localization, we sample a set of candidate segments and estimate their confidence scores with the boundary adjustment. Concretely, we first adopt a spatial attention to aggregate the final region features by \begin{eqnarray} &\zeta^n_{k} = {\bf w}^{\top}{\rm tanh}({\bf W}^{f}_{1} {\bf \widetilde r}_{k}^{n}+ {\bf W}^{f}_{2}{\bf o}_{1}+{\bf b}^{f}), \nonumber \\ &{\bf f}^{n} = \sum_{k=1}^{K} {\rm softmax}({\zeta^n_{k}}) \cdot {\bf \widetilde r}_{k}^{n}, \nonumber \end{eqnarray} where ${\bf f}^n$ is the object-aware feature of frame $n$. We then input $\{{\bf f}^n\}_{n=1}^N$ into a Bi-GRU to learn context features $\{{\bf \widetilde f}^n\}_{n=1}^N$. Next, we regard each frame as a sample center and define $H$ candidate segments with widths $\{{w}^h\}_{h=1}^H$ at each center. After it, we generate the confidence scores and their boundary offsets by \begin{eqnarray} & {\bf c}^{n} = \sigma({\bf W}^c {\bf \widetilde f}^n + {\bf b}^c), \ {\bf l}^{n} = {\bf W}^l {\bf \widetilde f}^n+ {\bf b}^l, \nonumber \end{eqnarray} where ${\bf c}^{n} \in \mathbb{R}^{H}$ represent confidence scores of $H$ candidates at step $n$ and ${\bf l}^{n} \in \mathbb{R}^{2H}$ are their offsets. Similar to the spatial loss, we apply the temporal alignment loss for segment selection, which is based on the temporal IoU score ${\rm tIoU}_{h}^n$ of each candidate segment with the ground truth segment, given by \begin{equation} \begin{aligned} {\mathcal TL}^n_{h} &= (1 - {\rm tIoU}_{h}^n) \cdot {\rm log} (1 - {c}_{h}^n) + {\rm tIoU}_{h}^n \cdot {\rm log}({c}_{h}^n), \\ \nonumber {\mathcal L}_{t} &= -\frac{1}{NH}\sum_{n=1}^{N}\sum_{h=1}^{H} {\mathcal TL}^n_{h}. \end{aligned} \end{equation} Next, we select the segment with the highest ${c}_{h}^n$ and adjust its temporal boundaries by the offset $(l_s,l_e)$ from ${\bf l}^{n}_{h}$. Here we develop another regression loss to train the offsets. With the original boundaries $({s}, {e})$ of the selected segment and ground truth $({\hat s}, {\hat e})$, we first compute the ground truth offsets ${\hat l}_s = s - {\hat s}$ and ${\hat l}_e = e - {\hat e}$ and compute the regression loss by \begin{eqnarray} & {\mathcal L}_{r} = {\rm R}({l}_s - {\hat l}_s) + {\rm R}({l}_e - {\hat l}_e), \nonumber \end{eqnarray} where ${\rm R}$ is the smooth L1 function. Eventually, we apply the multi-task loss to train our OMRN method in an end-to-end manner, given by \begin{eqnarray} & {\mathcal L}_{OMRN} = {\lambda}_1 {\mathcal L}_{s} + {\lambda}_2 {\mathcal L}_{t} + {\lambda}_3 {\mathcal L}_{r} + {\lambda}_4 {\mathcal L}_{d}, \nonumber \end{eqnarray} where ${\lambda}_1$, ${\lambda}_2$, ${\lambda}_3$ and ${\lambda}_4$ control the balance of four losses. During inference, we first detect the segment with the highest temporal confidence score, fine-tune its boundaries by its offsets and then select the regions with the highest spatial scores within the selected segment to generate the target tube. \section{Experiments} \subsection{Experimental Settings} \subsubsection{Dataset} We conduct experiments on a large-scale spatio-temporal video grounding dataset VidSTG~\cite{zhang2020does}, which is constructed from the video object relation dataset VidOR~\cite{shang2019annotating} by annotating the natural language descriptions. As we know, VidSTG is the only grounding dataset on unaligned video-sentence data and multi-form sentences. Specifically, VidSTG contains 5,563, 618 and 743 videos in the training, validation and testing sets, totaling 6,924 videos. There are 99,943 sentence annotations for 80 types of queried objects, including 44,808 and 55,135 for declarative and interrogative sentences, respectively. Moreover, the duration of the videos is 28.01s and temporal tube length is 9.68s on average. And declarative and interrogative sentences have about 11.12 and 8.98 words, respectively. \subsubsection{Implementation Details} During data preprocessing, we extract 1,024-d region features by a pre-trained Faster R-CNN~\cite{ren2015faster}. We sample 5 frames per second and extract $K=20$ regions for each frame. For language, we apply a pre-trained Glove embedding to obtain 300-d word features and use the NLTK to recognize the nouns in sentences. As for modeling setting, we set $\alpha$ to 0.6, $L$ to 5 and set $\lambda_1$, $\lambda_2$, $\lambda_3$ and $\lambda_4$ to 1.0, 1.0, 0.001 and 1.0, respectively. We define $H=9$ candidate segments at each step with temporal widths $[3,9,17,33,65,97,129,165,197]$. We set the dimensions of all projection matrices and biases to 256 and set the hidden state of each direction in BiGRU to 128. We employ an Adam optimizer with the initial learning rate 0.0005. \subsubsection{Evaluation Criteria} We apply the criterion m\_tIoU to evaluate the temporal grounding performance and use m\_vIoU and vIoU@R to estimate the spatio-temporal accuracy as \cite{zhang2020does}. Concretely, the m\_tIoU is the average temporal IoU of selected segments with the ground truth. We define vIoU as the spatio-temporal IoU between the predicted and ground truth tubes, given by $ {\rm vIoU} = \frac{1}{|{\mathcal S}_{p} \cup {\mathcal S}_{gt}|} \sum_{n \in {\mathcal S}_{p} \cap {\mathcal S}_{gt}} {\rm IoU}(r^n, {\hat r}^n)$. The ${\mathcal S}_{p}$ is the frame set in the predicted segment and ${\mathcal S}_{gt}$ is the frame set in the ground truth. The $r^n$, ${\hat r}^n$ are the predicted and ground truth regions in frame $n$. The m\_vIoU is the mean vIoU of all test samples and vIoU@R is the rate of testing samples with vIoU $>$ R. \subsection{Performance Comparison} As an emerging task, only the STGRN method~\cite{zhang2020does} is designed for STVG on unaligned data. Besides it, we combine the temporal grounding methods TALL~\cite{gao2017tall} and L-Net~\cite{chen2019localizing} with spatio-temporal grounding approaches on aligned data as the baselines. Specifically, TALL employs a proposal-and-selection framework for the temporal localization and L-Net develops frame-by-word interactions for holistic segment selection. Given the predicted segment, GroundeR~\cite{rohrbach2016grounding} is a visual grounding method to retrieve the target region in each frame. And the STPR~\cite{yamaguchi2017spatio} and WSSTG~\cite{chen2019weakly} approaches apply tube pre-generation in the segment and then rank these tubes by cross-modal estimation. Concretely, the original STPR is applied to multi-video person grounding, we extend it to single-video grounding for diverse objects. The WSSTG originally use a weakly-supervised ranking loss but we replace it with a supervised triplet loss~\cite{yang2019cross}. Thus, there are 6 combinations such as WSSTG+TALL and STPR+L-Net. The overall experiment results are shown in Table~\ref{table:mainexp} and we can find some interesting points: \begin{itemize} \item On the whole, the grounding performance of all models for interrogative sentences is lower than for declarative sentences, validating the unknown objects without explicit characteristics are more difficult to ground. \item For temporal grounding, region-level methods STGRN and OMRN outperform the frame-level methods TALL and L-Net, which demonstrates the fine-grained region modeling is beneficial to determine the accurate temporal boundaries of target tubes. \item For spatio-temporal grounding, the GroundR+$\{\cdot\}$ approaches ignore the temporal dynamics of objects and achieve the worst performance, suggesting it is crucial to capture the object dynamics among frames for high-quality spatio-temporal video grounding. \item In all criteria, our OMRN achieves the remarkable performance improvements compared with baselines. This fact shows our method can effectively focus on the notable regions by object-aware multi-branch region modeling with the diversity loss and capture critical object relations by multi-branch reasoning. \end{itemize} Furthermore, given the temporal ground truth segment during inference, we compare the spatial grounding ability of our OMRN method with baselines. The results are shown in Table~\ref{table:temgt} and we do not separate declarative and interrogative sentences here. We can see that our OMRN still achieves the apparent performance improvement on all criteria, especially for [email protected]. This demonstrates our OMRN approach is still effective when applied to aligned segment-sentence data. \begin{table}[t] \centering \scalebox{0.95}{ \begin{tabular}{c|ccc} \hline Methods & m\_vIoU &[email protected] &[email protected]\\ \hline GroundeR + Tem. GT& 27.31\%&40.53\%&20.86\%\\ STPR + Tem. GT&28.20\%&42.08\%&21.75\%\\ WSSTG + Tem. GT&31.51\%&46.99\%&27.65\%\\ STGRN + Tem. GT& 36.75\%&50.78\%& 32.93\%\\ \hline OMRN + Tem. GT& {\bf 39.57\%}&{\bf 58.19\%}&{\bf 37.91\%}\\ \hline \end{tabular} } \caption{Evaluation Results with the Temporal Ground Truth.}\label{table:temgt} \end{table} \begin{table}[t] \centering \scalebox{0.95}{ \begin{tabular}{c|cccc} \hline Methods & m\_tIoU& m\_vIoU &[email protected] &[email protected]\\ \hline w/o. OM&47.78\%&19.85\%&28.55\%&12.99\%\\ w/o. DL&48.32\%&20.08\%&28.80\%&13.42\%\\ w/o. CM&47.23\%&19.06\%&27.08\%&12.25\%\\ \hline w/o. TA&48.92\%&20.50\%&29.76\%&13.61\%\\ w/o. CA&48.85\%&20.73\%&29.87\%&14.02\%\\ \hline full&{\bf 49.88\%}&{\bf 21.73\%}&{\bf 30.26\%}&{\bf 15.14\%}\\ \hline \end{tabular} } \caption{Ablation Results on the VidSTG Dataset.}\label{table:ablation} \end{table} \subsection{Ablation Study} We next verify the contribution of each part of our method by ablation study. We remove one key component at a time to generate an ablation model. The object-aware multi-branch modeling is vital in our method, so we first remove the object-aware modulation from each branch as \textbf{w/o. OM}. We then discard the diversity loss from the multi-task loss, denoted by \textbf{w/o. DL}. Further, we remove the cross-modal matching from all branches and discard the weighting terms ${\hat d}^n_{1k}$ and ${\hat d}^n_{tl}$ in multi-branch relation reasoning, denoted by \textbf{w/o. CM}. Note that in this ablation model, the diversity loss is also ineffective due to the lack the matching score distributions. Next, we develop the ablation study on the basic region and object modeling. We discard the temporal region aggregation from region modeling as \textbf{w/o. TA} and remove the context attention during object extraction as \textbf{w/o. CA}. The ablation results are shown in Table~\ref{table:ablation}. We can find all ablation models have the performance degradation compared with the full model, showing each above component is helpful to improve the grounding accuracy. And the ablation models \textbf{w/o. OM}, \textbf{w/o. DL} and \textbf{w/o. CM} have the lower accuracy than \textbf{w/o. TA} and \textbf{w/o. CA}, which suggests the object-aware multi-branch relation reasoning plays a crucial role in high-quality spatio-temporal grounding. Moreover, the model \textbf{w/o. CM} achieves the worst performance, validating the cross-modal matching with the diversity regularization is very important to incorporate language-relevant region features from auxiliary branches into the main branch. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{./atten} \caption{A typical example of the grounding result.}\label{fig:atten} \end{figure} \subsection{Qualitative Analysis} To qualitatively validate the effectiveness of our OMRN method, we display a typical example in Figure~\ref{fig:atten}. The sentence describes a short-term state of the "dog" and requires to capture object-aware fine-grained relations. By intuitive comparison, our OMRN can retrieve the more accurate temporal boundaries and spatio-temporal tube of the "dog" than the best baseline STGRN. Furthermore, we display the object-region matching score distribution in the example, where we visualize the matching scores between three objects (i.e. "dog", "rope" and "man") and the regions of the 4-th frame. Although there are a woman and another dog in the frame, our method can still eliminate the interference and focus on the notable region containing the corresponding object, e.g., the object "dog" assigns a higher score to the 2-th region rather than the 6-th region. \section{Conclusion} In this paper, we propose a novel object-aware multi-branch relation network for STVG. The method can effectively focus on the vital regions by object-aware multi-branch region modeling and capture sufficient object relations by multi-branch reasoning for high-quality spatio-temporal grounding. \section*{Acknowledgments} This work was supported by the National Key R\&D Program of China under Grant No. 2018AAA0100603, Zhejiang Natural Science Foundation LR19F020006 and the National Natural Science Foundation of China under Grant No.61836002, No.U1611461 and No.61751209. This research is partially supported by the Language and Speech Innovation Lab of HUAWEI Cloud. \clearpage \bibliographystyle{named}
{'timestamp': '2020-08-25T02:09:36', 'yymm': '2008', 'arxiv_id': '2008.06941', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06941'}
arxiv
\section{Introduction} Recommender Systems have been described as “an intuitive line of defense against consumer over-choice” \cite{10.1145/3285029}. With the rapid growth in the number of products available on e-commerce websites, this problem of "over-choice" is becoming more and more significant, especially in the case of clothing related products. In fact, fashion recommendation has attracted considerable attention in recent literature. Studies tackling this problem have shown improved performance by incorporating visual information into their recommendation procedure. Hence it is safe to conclude that the visual appearance of a product plays a significant role while making purchase decisions. Image-based recommendation systems can be broadly classified into two groups - (i) Systems which incorporate images into a product rating/rank prediction function. These systems build upon well known Latent Factor models like Singular Value Decomposition (SVD) or Bayesian Personalized Ranking (BPR). \cite{10.1145/3331184.3331254, 10.5555/3015812.3015834, HeLinWanMcA16, 10.1145/2959100.2959152, 10.1145/3077136.3080797} (ii) Systems which learn latent representations (a.k.a embeddings) using image features and subsequently use embedding distance for making recommendations. These systems rely on extracting fine-grained embeddings which can capture user preference and/or product similarity \cite{10.1145/3240508.3240541, McATarShiHen15, 10.1145/3219819.3219890, DBLP:journals/corr/ShankarNAKC17, 10.1145/2964284.2967182}. Beyond images, information coming from product metadata \cite{10.1145/2959100.2959160}, user-product information networks \cite{8355676}, review-text \cite{10.1145/3240508.3240541, 10.1145/3291060} etc. has also been leveraged for learning effective representations. Making recommendations in the cold-start setting is a key area where addition of visual information has shown significant performance improvement \cite{10.5555/3015812.3015834}. However, we observe that there is considerable variability in the definition of cold-start setting across literature. Some studies describe cold-start products as items that have fewer instances of positive feedback in the training set \cite{10.5555/3015812.3015834, HeLinWanMcA16, 8355676, 10.1145/3077136.3080797, 10.1145/3397271.3401252}, whereas \cite{10.1145/2959100.2959160} describes its cold-start scenario when certain product-pairs have zero co-occurrences while training. Recommending completely new products (i.e. products which are unseen during the training step) is a tougher problem which is studied less frequently \cite{10.1145/564376.564421, 10.1145/2645710.2645751, 5693971}. Systems falling under category (i) (as described above) rely on user and product latent factors coming from interaction records, hence, they are incapable of handling new products unless product latent factors are estimated by other methods. Systems falling under category (ii) show better promise of handling this problem. Methods like \cite{DBLP:journals/corr/ShankarNAKC17, McATarShiHen15}, which make recommendations based on product-product similarity are capable of extracting latent representations for a new product. However, here user preference is ignored while feature extraction hence making personalized recommendations is not possible. Methods which attempt to capture preferences for individual users are better suited for handling this problem. To this end, we propose a novel framework which jointly learns (i) user and product embeddings in a common latent space and (ii) a mapping function which transforms product image features to the same latent space. In specific, we augment the Skip-Gram model \cite{Mikolov:2013:DRW:2999792.2999959} with a decoder architecture where the decoder uses the product Skip-Gram embeddings to reconstruct their corresponding image features. Here Skip-Gram maximizes the probability of co-occurrence of users and products in a Heterogeneous Information Network (HIN) while the decoder minimizes the image feature reconstruction loss. This decoder serves two purposes- (i) it incorporates visual information into the skip gram embeddings and (ii) it is later used for learning a mapping function which transforms product image features to the Skip-Gram embedding space. The learning objective of this architecture is dependent on the genre of input (users or products) observed while training. The Skip-Gram model is optimized in case of both users and products whereas the decoder is updated only for products in a multitask fashion. We term this model as VASG (Visually Aware Skip-Gram). The mapping from the product image feature space to VASG embedding space is subsequently learned and can be used for finding effective embeddings for cold-start products. VASG embeddings reflect user preference while simultaneously capturing a product's purchase history and visual appearance. Since users and products are represented in the same latent space, personalized recommendations can be made directly by searching for products in the user's vicinity. Our contributions can be summarized as - \begin{itemize} \item We propose a novel multitasking Skip-Gram architecture, VASG, which is trained on two different objectives depending on the genre of the input (users or products). This architecture enables us to learn a mapping which transforms product image features to the learned embedding space. \item Extensive experiments are performed on real world datasets and VASG embeddings are compared to state-of-the-art recommendation systems. The performance for unseen cold start products is also studied. \item We analyze the learned embeddings in detail to shed some light on the information captured by them. \end{itemize} \begin{figure*}[h] \centering \includegraphics[width=\linewidth]{model2.png} \caption{The VASG framework. (a) User-Product interactions are represented in a HIN. (b) Sequences are generated by performing random walks on the HIN. The Skip-Gram context window is used to describe the neighbourhood of a node. (c) The Skip-Gram model is trained on the generated sequences. (d) The decoder $\mathcal{M}^{-1}(.)$ attempts to reconstruct product image features from the Skip-Gram embeddings. (e) An autoencoder is trained to estimate the mapping $\mathcal{M}(.)$} \end{figure*} \section{Related Work} Our work relies on several advancements in image feature extraction methods, representation learning techniques in graphs and multitask learning. With advancements in deep learning, VBPR \cite{10.5555/3015812.3015834} established that the addition of visual signals can be useful for making recommendations. VBPR adds image features extracted from a pre-trained convolutional neural network to the BPR framework. Similarly, \cite{10.1145/3077136.3080797} extracts more fine grained image features using attention modules and incorporates them in collaborative filtering. Images have also been proven to be useful for Point-of-Interest recommendations in \cite{wang2017your} and for tag recommendations in \cite{rawat2016contagnet}. More recently, there has been a surge of methods which combine information coming from different modalities and metadata with images \cite{10.1145/3291060, HeLinWanMcA16, 10.1145/3240508.3240541, 10.1145/2959100.2959152, 10.1145/3331184.3331254}. Attention mechanisms which utilize textual reviews have been used for finding specific parts of an image where users are most interested in \cite{10.1145/3331184.3331254}. Reviews and image features have also been used for learning user preference which is then integrated into a rating-based matrix factorization model \cite{10.1145/3291060}. Pre-defined product categories and hierarchy trees have been leveraged for learning hierarchical product embeddings \cite{HeLinWanMcA16}. Recommendation Systems which rely on product image similarity; for example methods which address the Street-to-shop recommendation problem \cite{6248071}; have received a tremendous boost with improvements in metric learning methods \cite{8575408, 10.1145/2964284.2967182, DBLP:journals/corr/ShankarNAKC17} . These methods use triplet loss to learn embeddings from product images which are robust to change in background, pose, lighting conditions etc. and hence can be used for making cross-domain recommendations. However, learning both user and product representations in a joint latent space is less frequently explored in existing literature. \cite{10.1145/3336191.3371770} embeds users and topics to the same low dimensional space to capture of their mutual dependency while \cite{10.1145/3240508.3240541} attempts to bring users, products and product search queries to the same latent space using both textual and visual modalities. Heterogeneous Information Networks (HINs) can naturally model complex user and product interactions. Traditionally, meta-path based similarity and link predictions have been used for making recommendations in networks. With the development of graph representation learning methods \cite{perozzi2014deepwalk, grover2016node2vec, dong2017metapath2vec}, network embedding based recommendation systems have shown improved performance. The study \cite{8355676} learns user and product representations from a HIN and incorporates them into the {\it SVDFeature} \cite{Chen:2012:STF:2503308.2503357} framework. This idea of learning network representations has also been extended by using multitask learning for jointly optimizing the tasks of recommendation and link prediction in a HIN \cite{9051843}. Multitask learning is a training regime where multiple objectives are optimized simultaneously. It has proven to provide performance boosts in works like \cite{Gidaris_2019_ICCV, 8771379}. A few studies which are relevant to our proposed approach should be discussed here. Learning attribute-to-feature mappings has been proposed in \cite{5693971}. Here k-nearest neighbours, least squares approximation is used for approximating latent factors for new users or products. A large scale recommender system which uses images along with the HIN structure is proposed in \cite{10.1145/3219819.3219890}. Here highly efficient Graph-Convolutional Neural Networks are used on random walks generated from the HIN and recommendations are then made using similarity between the learned embeddings. Contrastive Predictive Coding \cite{oord2018representation} (CPC) is a generic representation learning regime which uses a similar training procedure as the proposed framework. CPC uses encoders to map raw data to latent representations and subsequently trains auto-regressive models using a contrastive loss. VASG differs from CPC in terms of usage of a decoding architecture instead of an encoder; usage of Skip-Gram instead of an auto-regressive model; and training using auxiliary supervision instead of self-supervision. To the best of our knowledge, the model architecture proposed in this paper has not been studied before. In addition, we also make a novel attempt to bring unseen cold start products to the same latent space as existing users and products using product image features. \section{VASG Framework} Consider a set of users $\mathcal{U}$ and a set of products $\mathcal{P}$ where each user $u\in\mathcal{U}$ has interacted with a subset of products $\mathcal{P}\textsubscript{\it u} \subset \mathcal{P}$. Each product $p\in\mathcal{P}$ is associated with a visual feature $f\textsubscript{p}\in\mathbb{R\textsuperscript{I}}$ which is extracted from its image using a Deep Convolutional Neural Network. Only a subset of products $\mathcal{P}\textsubscript{warm} \subset \mathcal{P}$ is observed during training and is termed as the {\it warm start} set. The set of products which is never observed during training is termed as {\it completely cold} set $~\mathcal{P}\textsubscript{cold} \subset \mathcal{P}$ . It is to be noted that $\mathcal{P}\textsubscript{cold} \cap \mathcal{P}\textsubscript{warm} = \phi$.\\ Our objective is to learn (i) a {\it D} dimensional latent representation $\mathcal{X}\in\mathbb{R}\textsuperscript{\it D}$ for each $u\in\mathcal{U}$ and $p\in\mathcal{P}\textsubscript{warm}$; and (ii) a mapping function $\mathcal{M}(f\textsubscript{p}):\mathbb{R}\textsuperscript{\it I}\rightarrow\mathbb{R}\textsuperscript{\it D}$. This function is used for finding embeddings of products that have no purchase history. The learned embeddings are expected to represent characteristic features of users and products which can be exploited for making representations. The VASG framework achieves the above mentioned objectives in two steps- \begin{itemize} \item The first step involves training a Skip-Gram model on sequences of users and products. Here, the Skip-Gram architecture is modified by adding an auxiliary objective of learning an inverse mapping function $\mathcal{M}\textsuperscript{-1}(\mathcal{X}\textsubscript{p}): \mathbb{R}\textsuperscript{\it D}\rightarrow\mathbb{R}\textsuperscript{\it I}$. The {\it D} dimensional embeddings corresponding to users $u\in\mathcal{U}$ and products $p\in\mathcal{P}\textsubscript{warm}$ are learned during this step. \item The second step involves learning the mapping function $\mathcal{M}(f\textsubscript{p}):\mathbb{R}\textsuperscript{\it I}\rightarrow\mathbb{R}\textsuperscript{\it D}$. This is achieved by training a deep encoder-decoder architecture using the inverse mapping $\mathcal{M}\textsuperscript{-1}(.)$ learned in the previous step. \end{itemize} We describe the network structure used for representing user-product interactions before describing the model architecture. \subsection{Heterogeneous Information Network} Skip-Gram \cite{DBLP:journals/corr/abs-1301-3781} is an unsupervised representation learning model for words in a text corpus. The representation corresponding to each word is learned by maximizing the probability of correctly predicting the context surrounding the given word. The proposed framework builds upon the Skip-Gram architecture, hence, it requires sequences of user and products. Taking inspiration from \cite{8355676}, we generate these sequences by performing random walks on a bipartite Heterogeneous Information Network (HIN) of users and products. Formally, our HIN is a graph $G = (V,E)$ where $V = \mathcal{U}\cup\mathcal{P}\textsubscript{warm}$ is the set of nodes. $E = \{(u,p) \vert p\in\mathcal{P}\textsubscript{u}\cap\mathcal{P}\textsubscript{warm}~;~u\in\mathcal{U}\}$ is the set of edges connecting the nodes where each edge connects a user to the products purchased by him. Sequences are generated in the following manner - Starting from a node $\mathrm{v}\in V$, $n$ number of random walks, each of length $wl$ are performed on the HIN. Every subsequent node in a walk is chosen randomly from the direct neighbours of the current node. For example, consider the sample HIN shown in Figure 1(a). A sequence starting from node {\it u\textsubscript{1}} could be {\it u\textsubscript{1} p\textsubscript{2} u\textsubscript{2} p\textsubscript{2} u\textsubscript{3} ...} repeated for $wl$ nodes. Here, $n$ and $wl$ are hyper-parameters which determine the size of the corpus generated for training. It is to be noted that the bipartite structure of the HIN ensures that users and products appear in an alternating fashion in each random walk. The neighbouring context of a node, $\mathcal{N}(\mathrm{v})$ is determined by sliding a fixed size context window over the generated sequences. We discuss the effect of the context window size on the learned representations in Section 6. \begin{table}[] \caption{Dataset statistics (after preprocessing)} \begin{tabular}{@{}llll@{}} \toprule \textbf{Dataset} & \textbf{\#products} & \textbf{\#users} & \textbf{\#ratings} \\ \midrule Women & 116,971 & 14,110 & 307,863 \\ Men & 62,376 & 19,618 & 187,181 \\ Shoes & 71,219 & 22,066 & 211,818 \\ Jewelry & 62,958 & 13,975 & 161,439 \\ \bottomrule \end{tabular} \end{table} \subsection{Visually Aware Skip-Gram} Consider an HIN node $\mathrm{v}\in V$ and its neighbouring context $\mathcal{N}(\mathrm{v})$. We can learn the the representations corresponding to each node in the HIN by optimizing the Skip-Gram objective - \begin{equation} \underset{\theta}{arg\,max} \displaystyle\sum_{\mathrm{v}\in V} \displaystyle\sum_{c \in N(\mathrm{v})} log (p(c|v;\theta)) \end{equation} Here $p(c|v;\theta)$ is the commonly used softmax probability, given by: $p(c|v, \theta) = \frac{e^{\mathcal{X}\textsubscript{c}\mathcal{X}\textsubscript{v}}}{\sum_{n \in V} e^{\mathcal{X}\textsubscript{\it n}\mathcal{X}\textsubscript{v}}}$ where $\mathcal{X}\textsubscript{v}\in\mathbb{R}\textsuperscript{D}$ is the $D$ dimensional latent representation corresponding to node $\mathrm{v}$. Mikolov et al. \cite{Mikolov:2013:DRW:2999792.2999959} introduces negative sampling for efficiently estimating the softmax probabilities however, generating effective negative samples can be an expensive process \cite{10.1145/3289600.3290979}. We expect the negative samples to highlight the contrast in a product's visual appearance and a user's purchase preference simultaneously. In our experiments, we are able to obtain meaningful results without negative sampling, hence we approximate the softmax probability as: $\sigma(\mathcal{X}\textsubscript{c}~.~\mathcal{X}\textsubscript{v})$ where $\sigma$ is the $sigmoid$ function, given by: $\sigma(x) = \frac{1}{1+e^{-x}}$. We add the auxiliary objective of learning $\mathcal{M}\textsuperscript{-1}(\mathcal{X}\textsubscript{p}): \mathbb{R}\textsuperscript{\it D}\rightarrow\mathbb{R}\textsuperscript{\it I}$ to the Skip-Gram objective whenever $\mathrm{v}\in\mathcal{P}\textsubscript{warm}$. The function $\mathcal{M}\textsuperscript{-1}(.)$ attempts to reconstruct the DeepCNN image feature $f\textsubscript{p}$ of a product from its latent representation $\mathcal{X}\textsubscript{p}$. This inverse mapping function is approximated by training a decoder architecture with the objective of minimizing the mean squared error of image feature reconstruction - \begin{equation} \underset{\mathcal{M}^{-1}}{arg\,min} \displaystyle\sum_{\mathrm{v}\in \mathcal{P}\textsubscript{warm}} \vert\vert f\textsubscript{v} - f^{'}_{\textsubscript{p}}\vert\vert^{2}_{2} \end{equation} Where $f^{'}_{\textsubscript{p}} = \mathcal{M}\textsuperscript{-1}(\mathcal{X}\textsubscript{p})$. It is to be noted that the auxiliary task is optimized only when $\mathrm{v}\in\mathcal{P}\textsubscript{warm}$. This implies that users have a single loss function while products have two different loss functions which are optimized simultaneously in a multi-task learning fashion. When a node $\mathrm{v}$ is observed in the training corpus, the loss can be written as - \begin{equation} \mathcal{L}(\mathrm{v})= \begin{cases} -log(\sigma(\mathcal{X}\textsubscript{c}\mathcal{X}\textsubscript{v})) &\text{ $\mathrm{v}\in \mathcal{U}$}\\ w\textsubscript{1}(-log(\sigma(\mathcal{X}\textsubscript{c}\mathcal{X}\textsubscript{v}))) + w\textsubscript{2}\vert\vert f\textsubscript{v} - f^{'}_{\textsubscript{p}}\vert\vert^{2}_{2} & \text{$\mathrm{v}\in \mathcal{P}\textsubscript{warm}$} \end{cases} \end{equation} Here $ w\textsubscript{1} $ and $ w\textsubscript{2} $ are trainable weights used for combining the Skip-Gram and image reconstruction losses. We follow the approach introduced in \cite{DBLP:journals/corr/KendallGC17} for learning these weights. Once the embeddings and the inverse mapping $\mathcal{M}^{-1}(.)$ have been learned, the function $\mathcal{M}(.)$ is approximated by training a deep autoencoder for reconstructing the product image features for each product $p\in\mathcal{P}\textsubscript{warm}$. The autoencoder has $\mathcal{M}^{-1}(.)$ as the decoder while the encoder attempts to approximate $\mathcal{M}(.)$. Weight updates are not allowed in the decoder, therefore $\mathcal{M}^{-1}(.)$ remains unchanged during the training process. An overview of the proposed architecture is presented in Figure 1. \\{\bfseries Implementation Details:} We implemented our model in Pytorch. The decoder architecture $\mathcal{M}^{-1}(.)$ consists of 5 fully connected layers with [256, 512, 1024, 2048, $I$] neurons respectively ($I = 4096$). Each layer has {\it reLu} activation and dropout regularization with dropout probability set to 0.5. The encoder $\mathcal{M}(.)$ follows the same architecture. Adam optimizer with learning rate 1e-3 is used for parameter updates. To fully utilize GPU acceleration, we use a batch wise implementation and ensure each batch homogeneously comprises either users or products as we iterate over the Skip-Gram corpus. Training on our largest dataset requires around 30 minutes on a Nvidia Quadro P5000 GPU. We provide our implementation here\footnote{\href{https://github.com/parth2170/triplet-recsys}{\bfseries Link to repository}. Will be released at the time of publication.} \setlength{\textfloatsep}{0.3cm} \section{Experiments} We perform experiments on real-world datasets to evaluate the VASG embeddings. Our experiments attempt to answer the following research questions - {\bf (i)} Can the embeddings generate personalized recommendations for each user? {\bf (ii)} Can the embeddings identify product to product relationships? {\bf (iii)} What are the properties displayed by the learned embedding space? {\bf (vi)} How do different components and hyper-parameters of the proposed framework affect its performance? \subsection{Datasets} Four subcategories under the "Clothing, Shoes \& Jewelry" dataset from {\it Amazon Product Reviews} \cite{McATarShiHen15} are used for our experiments. The selected subcategories are - {\it Men, Women, Shoes} and {\it Jewelry}. The dataset is pre-processed to remove users that do not have sufficient purchase history. Users with $\vert\mathcal{P}\textsubscript{u}\vert<5$ are discarded from the datasets . Users' rating history and product image features are used in our framework. Product metadata is also available, however it not utilized for learning embeddings. Only image URLs are used for retrieving images for the purpose of visualization. Product image features were extracted using a pre-trained Caffe reference model \cite{10.1145/2647868.2654889}, with 5 convolutional layers followed by 3 dense layers. The feature vector is obtained by taking the output of the second dense layer (FC7) of this network and has length $I = 4096$. The details of the datasets are specified in Table 1. The training and test sets are created by following the leave one out protocol described by \cite{10.5555/3015812.3015834}. For each user $u$, one random product rated by the user is used for testing, while the remaining products are used for training. Two subsets of the test set are created for testing in {\it warm start} and {\it completely cold start} setting: $\mathcal{T}\textsubscript{warm} = \{(u, p) \mid u \in \mathcal{U}~;~p\in \mathcal{P}\textsubscript{warm}\}$ and $\mathcal{T}\textsubscript{cold} = \{(u, p) \mid u \in \mathcal{U}~;~ p\in \mathcal{P}\textsubscript{cold}\}$. Here $\mathcal{T}\textsubscript{warm}$ and $\mathcal{T}\textsubscript{cold}$ are approximately equal in size. \begin{table}[t] \caption{AUC values on the test sets. The best scores are boldfaced. Refer Section 4.2} \begin{tabular}{@{}llllll@{}} \toprule \textbf{Dataset} & \textbf{Setting} & \textbf{RAND} & \textbf{WBOI} & \textbf{VBPR} & \textbf{VASG} \\ \midrule Women & \textit{Warm Products} & 0.4998 & 0.6134 & 0.7982 & \textbf{0.8964} \\ & \textit{Cold Products} & 0.5001 & 0.5912 & & \textbf{0.7596} \\ Men & \textit{Warm Products} & 0.4897 & 0.6468 & 0.7753 & \textbf{0.8758} \\ & \textit{Cold Products} & 0.4954 & 0.6094 & & \textbf{0.7061} \\ Shoes & \textit{Warm Products} & 0.5023 & 0.6318 & 0.8116 & \textbf{0.8972} \\ & \textit{Cold Products} & 0.4995 & 0.5846 & & \textbf{0.7261} \\ Jewelry & \textit{Warm Products} & 0.4987 & 0.6087 & 0.7629 & \textbf{0.8801} \\ & \textit{Cold Products} & 0.5003 & 0.5704 & & \textbf{0.7134} \\ \bottomrule \end{tabular} \end{table} \subsection{Making Personalized Recommendations} VASG embeddings can be used for generating recommendations by searching for relevant products in the vicinity of corresponding users in the learned latent space. We evaluate this ability to generate personalized recommendations in a Bayesian Personalized Ranking (BPR) scenario. BPR based methods \cite{10.5555/3015812.3015834,DBLP:journals/corr/abs-1205-2618} learn a rating prediction function by optimizing pairwise rankings of products w.r.t. to users. Predicted rankings are then evaluated using the well known AUC (Area Under ROC Curve) metric: \begin{equation} AUC = \frac{1}{\vert\mathcal{T}\textsubscript{test}\vert}\sum_{{}u\in\mathcal{T}\textsubscript{test}}\frac{1}{\vert\mathcal{P}-\mathcal{P}\textsubscript{u}\vert} \sum_{{}p\textsubscript{j}\in \mathcal{P}-\mathcal{P}\textsubscript{u}}\textbf{1}((u, p\textsubscript{test}) > (u,p\textsubscript{j})) \end{equation} where $\mathcal{T}\textsubscript{test}$ corresponds to $\mathcal{T}\textsubscript{warm}$ or $\mathcal{T}\textsubscript{cold}$ and $u,p\textsubscript{test}\in\mathcal{T}\textsubscript{test}$. Here, $\textbf{1}(.)$ is an indicator function which evaluates if $p\textsubscript{test}$ has been ranked higher than $p\textsubscript{j}$ for user $u$. BPR based methods rank products using the learned rating prediction function. We evaluate VASG embeddings for ranking products using the {\it cosine similarity} between corresponding user and product embeddings. \subsubsection{{\bfseries Baselines}} We compare the proposed embeddings against the raw image features and against a state-of-the-art visually aware BPR method: \begin{itemize} \item {\bfseries RAND} ({\it Random}) - Product rankings are decided randomly for all users. \item {\bfseries WBOI} ({\it Weighted Bag Of Images}) - User embeddings are directly computed using the image features corresponding to the products purchased by him. The rating weighted mean of image features is used as the user embedding and ranks are computed using cosine similarity as described above. \item {\bfseries VBPR} ({\it Visual Bayesian Product Ranking}) - Introduced by \cite{10.5555/3015812.3015834}, VBPR incorporates visual factors to the BPR framework by using product image DeepCNN features in its rating prediction function. \end{itemize} \subsubsection{{\bfseries Results}} The entire pipeline for VASG with $D = 100$ is run 5 times and the averaged results are reported in Table 2. The results for VBPR are calculated using 20 latent factors and 100 visual factors. Results are reported on the set $\mathcal{T}\textsubscript{warm}$ ({\it Warm Products}) and for on $\mathcal{T}\textsubscript{cold}$ ({\it Cold Products}) separately. VASG embeddings for cold start products are found using the mapping $\mathcal{M}(.)$. Since latent factors for cold start products are not available in VBPR, computing its results on the set $\mathcal{T}\textsubscript{cold}$ is infeasible. VASG embeddings show an average improvement of 3.84\% over VBPR in the warm start setting. The AUC scores drop in the cold start setting, however they are significantly better than the WBOI baseline. This drop in performance can be explained by imperfections in the approximation of the mapping function $\mathcal{M}(.)$. \subsection{Identifying Product Relationships} We expect the embeddings corresponding to co-purchased products to be similar. The evaluation strategy used by McAuley et al. (IBR) \cite{McATarShiHen15} is followed for identifying product relationships using VASG embeddings. IBR uses product DeepCNN image features to learn a parametric distance function by maximizing the probability of correctly identifying co-purchased product pairs. Formally, two products $p\textsubscript{i}$ and $p\textsubscript{j}$ share a relation $R\textsubscript{ij}$ if they have been purchased by the same user. This relation is termed as an {\it "also bought"} relation in IBR. We attempt to correctly identify co-purchased product pairs using the cosine similarity between the VASG embeddings. The test set is restructured in the following manner for reporting the results - A set of positive relation pairs $\mathcal{R} = \{(p\textsubscript{i}, p\textsubscript{j}) \mid \exists~R\textsubscript{ij}\}$ and a set of negative relation pairs $\mathcal{Q} = \{(p\textsubscript{i}, p\textsubscript{j}) \mid \nexists~R\textsubscript{ij}\}$ is constructed such that $\vert\mathcal{R}\vert = \vert\mathcal{Q}\vert~;~p\textsubscript{i}\in\mathcal{P}$. A positive relation is identified when $cosine~similarity(\mathcal{X}\textsubscript{i}, \mathcal{X}\textsubscript{j}) > t$, where $\mathcal{X}\textsubscript{i}$ is the VASG embedding corresponding to $p\textsubscript{i}$ and $t$ is a manually assigned threshold. The accuracy of identifying co-purchased product pairs is reported on the combined set $\mathcal{R}\cup \mathcal{Q}$. \begin{table}[t] \caption{Accuracy of predicting product relations. Refer Section 4.3} \begin{tabular}{@{}llllll@{}} \toprule \textbf{Dataset} & \textbf{INN} & \textbf{IBR} & \textbf{VASG} & \begin{tabular}[c]{@{}l@{}}VASG \\ vs INN\end{tabular} & \begin{tabular}[c]{@{}l@{}}VASG \\ vs IBR\end{tabular} \\ \midrule Women & 67.82\% & 87.43\% & 79.59\% & 17\% & -10\% \\ Men & 66.23\% & 87.13\% & 80.12\% & 21\% & -9\% \\ Shoes & 69.34\% & 89.67\% & 81.56\% & 18\% & -10\% \\ Jewelry & 65.42\% & 83.25\% & 79.36\% & 21\% & -5\% \\ \bottomrule \end{tabular} \end{table} \begin{figure*}[] \centering \includegraphics[width=\linewidth]{tsne.png} \caption{2D visualizations of VASG embeddings(a) PCA projections of 100 dimensional embeddings for each dataset. Here 200 randomly selected products are plotted (b) t-SNE projections of 100 dimensional embeddings for each dataset. Here products purchased by 4 randomly selected users are plotted. Products corresponding to the same user have the same frame colour} \end{figure*} \subsubsection{{\bfseries Baselines}} Since $\vert\mathcal{R}\vert = \vert\mathcal{Q}\vert$, random classification is 50\% accurate. In addition, the performance of VASG embeddings is compared to the following methods: \begin{itemize} \item {\bfseries INN} ({\it Image Nearest Neighbours}) - Cosine similarity between the DeepCNN image features $f\textsubscript{i}, f\textsubscript{j}$ are used for identifying relationships in the same manner as described above. \item {\bfseries IBR} ({\it Image Based Recommendations}) - As described above, this method is trained on all co-purchased product pairs occurring in the training set. \end{itemize} \subsubsection{{\bfseries Results}} The entire pipeline for VASG with $D = 100$ is run 5 times and the averaged results are reported in Table 3. For IBR, the rank of the Mahalanobis transform is set to 100 for fair comparison. Here, VASG embeddings show an average improvement of 19\% over INN, however they do not outperform IBR which shows significantly better results across all datasets. However it should be noted that IBR is trained for specifically identifying all product-product relations \cite{McATarShiHen15} whereas VASG embeddings are not. Our method learns embeddings by capturing co-occurrence of users and products in a small network neighbourhood which is more suited for making personalised recommendations which is shown by the results in Section 4.2 \section{Analysis of Embeddings} {\bfseries Embedding Visualization.} We visualize the learned embeddings in lower dimensions to understand the information captured. We plot 2D projections of a random set of products from each dataset in Figure 2(a). Here dimensions are reduced using Principal Component Analysis (PCA). A variance in the visual appearance of the products can be seen when we travel along the axes in these plots. For example in the {\it Men} dataset, the x-axis is populated with watches while the y-axis contains clothing related items like t-shirts. A similar trend can be observed for the {\it Women} and {\it Shoes} dataset, however, the plot for the {\it Jewelry} dataset looks noisy. Next, we visualize groups of products which have been purchased by specific users in Figure 2(b). Here we select 4 random users and plot all the products purchased by them. Dimensions are reduced using t-SNE with the perplexity parameter set to 30. Products corresponding to a specific user are marked by the colour of the frame around them. In case of co-purchased products, the frame colour is chosen randomly. It can be seen that products purchased by the same user have been clustered together. These plots show that the leaned embeddings can simultaneously capture the visual properties and the purchase history of a product. \\ \begin{figure}[t] \includegraphics[width=\linewidth]{linear_relations.png} \caption{Examples of recommendations generated by exploiting linear relationships in the embeddings} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} {\bfseries Linear relationships.} Skip-Gram word embeddings are known to follow a linear algebraic structure where embeddings display associative properties (shown by the famous example vector(”King”) - vector(”Man”) + vector(”Woman”)$\approx$vector(”Queen”) \cite{DBLP:journals/corr/abs-1301-3781}). We attempt to exploit a similar structure in the VASG embeddings for recommending products. Consider a pair: $\{(u1,p1), p1 \in \mathcal{P}\textsubscript{u1}\}$ and a user $u2;u2\neq u1$, keeping $(u1,p1)$ and $u2$ fixed, if we can a find a product $ p \in \mathcal{P}$ such that $$ cosine~similarity(\mathcal{X}\textsubscript{p1}-\mathcal{X}\textsubscript{u1}+\mathcal{X}\textsubscript{u2},\mathcal{X}\textsubscript{p}) \approx 1 $$ Then we say that $p$ is a user specific recommendation generated for the user $u2$ having a query product $p1$. To test this methodology, we sample 10,000 pairs of $u1,u2$ and find the nearest neighbour of the point $\mathcal{X}\textsubscript{p1}+\mathcal{X}\textsubscript{u2}-\mathcal{X}\textsubscript{u1}$, using cosine distance, from the set $\mathcal{P}$ and treat them as recommendations generated by VASG. We obtained a precision@5 of 89.7\% in the Men dataset. Figure 3. shows some of the recommendations generated by this methodology. Approximately speaking, here a product $p$ is recommended for user $u2$ when the similarity between $p,p1$ and between $p,u2$ is high and when similarity between $u1,p$ is low.\\ {\bfseries Embedding similarity distribution.} This analysis is inspired by \cite{10.1145/3219819.3219890}. Effectiveness of the learned embeddings can be judged by the distribution of distances between random pairs of embeddings. A wide distribution indicates that the embedding space has enough “resolution” to capture relevance of different product pairs. Figure 4 plots the distribution of cosine similarities between pairs of products from the {\it Men } dataset. The distribution coming from the VASG embeddings is compared against the distribution computed from product image features. VASG embeddings show a wider distribution hence proving their superiority over using raw image features. The kurtosis of this distribution for VASG embeddings is 0.87, compared to 3.67 for image features. \begin{figure}[t] \includegraphics[width=\linewidth]{pdf.png} \caption{Probability density of pairwise cosine similarity obtained from VASG embeddings and Product (image) Features.} \Description{A woman and a girl in white dresses sit in an open car.} \end{figure} \section{Sensitivity Analysis} {\bfseries Influence of Embedding size.} We study the variation of AUC scores with the embedding dimension size $D$. Figure 4 shows AUC scores for warm-start products when evaluating the performance of making personalized recommendations. The performance improves with increase in dimension size, however the rate of improvement seems to slow down after $D = 70$.\\ {\bfseries Influence of noise addition.} Autoencoders are known to suffer from over fitting. To overcome this problem, we add a small amount of Gaussian noise to the product image features while learning the mapping $\mathcal{M}(.)$. We find that noise addition helps in improving the performance of cold-start products for making personalized recommendations by an average margin of 1.8\% in AUC score.\\ {\bfseries Influence of Skip-Gram window Size.} The window size determines the neighbourhood size of a HIN node. For example a window size of 5 restricts the neighborhood to second degree neighbours. A smaller context window exposes the embeddings to local HIN structures which is suited for making personalized recommendations. We experiment with window size [3,5,7,9] and find that a window size of 7 gives the best results. Smaller window sizes lead to a faster convergence, but the embeddings over-fit in a small neighbourhood whereas larger window sizes make the training corpus unnecessarily large.\\ {\bfseries Influence of the auxiliary decoder.} We study how VASG's performance is affected by removing the auxiliary decoder. This reduces the proposed architecture to the general Skip-Gram model. We evaluate the performance of making personalized recommendations in the set $\mathcal{T}\textsubscript{warm}$. The performance drops by an average of 2.4\% on the {\it Women, Men} and {\it Shoes} dataset while the performance remains almost consistent for the {\it Jewelry} dataset. This indicates that addition of visual features improves the convential Skip-Gram embeddings. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{chart.png} \caption{Variation of AUC scores with embedding dimensions} \end{figure} \section{Conclusion} In this paper, we proposed a novel embedding learning architecture, VASG, which incorporates visual features into the Skip-Gram model. This model has two different loss functions depending on whether a user or a product is observed during training. VASG embeddings can be used for making personalized recommendations using nearest neighbour searches in the learned latent space. In addition, this framework enables us to find embeddings for cold start products which have never been observed during training. The embeddings are trained on real world datasets and extensive analysis brings forward several interesting properties captured by them. There are multiple potential directions in which this work can be extended. Use of effective negative samples while training can enable us to learn a more refined latent space. Adversarial training can be used to reconstruct product images using Generative Adversarial Networks conditioned on the Skip-Gram embeddings. Additional auxiliary tasks which bring information from other modalities can be added to central Skip-Gram architecture. VASG embeddings can be also be incorporated into frameworks like SVDFeature for predicting ratings. \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-08-18T02:17:28', 'yymm': '2008', 'arxiv_id': '2008.06908', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.06908'}
arxiv
\section{Introduction} Recent progress in NLP has been dominated by large pretrained transformer neural networks~\cite{vaswani2017attention}, such as BERT~\cite{devlin-etal-2019-bert}, and GPT-2~\cite{gpt2}. However, these models have a memory footprint that is quadratic in input sequence length. Although architectural innovations such as those of \citet{reformer} and \citet{pg19} mitigate this and the issue of a predetermined maximum context size, large pretrained models applying these techniques are not available at this time. Even if large pretrained models of this kind are released in the future, they will likely not cover the wide range of domains that BERT-family models have been published for. For example, there have been BERT-based models trained for other languages such as French~\cite{flaubert,camembert}, Italian~\cite{alberto}, and many other languages (see~\citet{bertlangoverview} for an overview) as well as specific domains such as scientific papers~\cite{scibert}, biomedical papers~\cite{biobert}, and health records~\cite{medbert}. Individuals working with these models may not have the resources to train new models from scratch using the latest tricks, as the computation requirements for pretraining are extremely high. As such, identifying ways that already existing models can be improved could be widely impactful. Another drawback of this family of models is that they have an a priori fixed maximum context size (typically 512 or 1024 tokens for the currently available pretrained models). A typical application of pretrained language models is producing contextual embeddings for a document. If the document is simply chunked into disjoint segments of 512 tokens, tokens at the boundary of a window will have less contextual information than tokens in the center of a window. This can be mitigated by striding the evaluation of the model, and only keeping the embedding for a token which has the largest context---but this adds quite a bit of wasted computation. In this paper, we propose a method for augmenting and fine-tuning pretrained transformer language models to use context without directly attending to it. Our method simultaneously allows for increasing the context size a transformer processes, while allowing a controllable trade-off between computation and perplexity. We accomplish this by adding a small recurrence module that computes a fixed size representation from the transformer hidden states in a window of text. Then, the representation for that window is used during processing of the next window. Shrinking the window size is then a way to reduce the memory footprint of the model, with less loss of performance than would occur with a standard transformer. Our experiments add recurrence GPT-2 language models, and fine-tune them on the PG-19~\cite{pg19} and WikiText-103 corpora~\cite{wikitext103}, and require only the same amount of memory used for standard fine-tuning of a pretrained language model. We demonstrate improvements in perplexity compared to a baseline model using the same amount of computation. Qualitative analysis shows that our recurrent module propagates certain information from previous windows of text, which can facilitate handling of long-distance dependencies with fixed-size input windows. \section{Related Work} Recently, many methods have been proposed which lower the memory footprint or computation time of transformer language models, or allow them to be used on larger contexts. The Transformer-XL~\cite{dai-etal-2019-transformer} allows a position within an attention window to attend to tokens from the previous windows by introducing relative position embeddings. While that mechanism like ours, allows information to flow between windows of text, existing BERT and GPT-2 models do not use relative position embeddings, so training from scratch would be necessary to take advantage of this architecture. Other methods modify the attention function to reduce the quadratic memory footprint down to a manageable amount. \citet{child2019generating} modify the transformer architecture to replace the standard attention with a sparse one. \citet{qiu2019blockwise} enforce a block-sparse structure on the attention matrix. \citet{reformer} also introduce sparsity, but instead do so by using locality sensitive hashing to select positions over which a full attention is computed, reducing the memory cost from quadratic to $O(T\log{T})$ for an input of size $T$. \citet{pg19} introduce a memory compression technique that allows much longer contexts to be attended to in memory. \citet{longformer} replace the standard attention with a combination of dilated sliding windows, and global attention from selected tokens that. \citet{sukhbaatar-etal-2019-adaptive} learn a masking function such that not all tokens attend to every previous position. \citet{Tay2020SynthesizerRS} learn synthetic attention weights, removing the need for token-token interactions. \citet{Wu2019PayLA} replace the full self-attention with a dynamic convolution depending only on the current timestep, yielding a linear dependence on length instead of a quadratic dependence. While the above methods all allow for a reduction in required computational resources, they also all require one to train a model from scratch. Our method's goal is to allow more efficient and powerful use of the wide array of existing pre-trained models that cover many domains. \citet{Cao2020DeFormerDP} propose the DeFormer, which also modifies the execution of a pretrained transformer. However, unlike our method, they decompose a single window into multiple windows by removing the attention interactions between these windows. This is largely orthogonal to our method, as one could both decompose windows of text, and additionally use our method to allow information to be passed between neighboring windows. Similarly, distilled versions of pretrained models such as DistilBERT~\cite{distilbert} provide more computational efficiency, but could be combined with our method to apply them to longer contexts, or reduce the quadratic cost of self-attention. \section{Method}\label{method} \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/recurrent_transformer.pdf} \caption{\small Augmenting a pretrained transformer with a small recurrence module, allowing reduction of attention computation as well as simpler processing of longer contexts.}\label{fig:model} \end{figure} The main idea of our method is to take a transformer that was pretrained in a fixed context size setting and add recurrence at the level of $T$-token windows of text. For example, instead of executing the model on one 1000 token window of text, we could instead execute our model with 10 windows of 100 tokens. The first window is processed by the transformer model as normal, but for subsequent windows we add a supplementary embedding, which is generated using the hidden states from the preceding window (see Figure~\ref{fig:model}). The recurrence module is extremely small compared to the size of transformer language model, so the additional computation required is negligible. \subsection{Adding recurrence to pretrained transformers} Starting by defining terms, we will consider a pretrained transformer with $L$ layers, a hidden state size of $k$, and a maximum context size of $T$ tokens. Let $\bm{h}_i^{(\ell)} \in \mathbb{R}^{k}$ be the output of the $\ell$-th layer of the pretrained model, at position $t$. To produce a fixed-size representation of tokens $t_1, t_2, \dots, t_T$, the embeddings produced by the pretrained transformer are mean-pooled as follows: \begin{equation}\label{eq:pool} \bm{z}_1 = \sum\limits_{i=1}^T \sum\limits_{\ell=1}^L w_\ell \bm{h}_i^{(\ell)} \end{equation} where $w_\ell$ are weights softmax-normalized from learned parameters $\alpha_\ell$: \begin{equation*} w_\ell = \frac{\mathrm{e}^{\alpha_\ell}}{\sum\limits_{j=1}^L \mathrm{e}^{\alpha_j}} \end{equation*} \begin{figure}\label{fig:token_insertion} \centering \includegraphics[width=\columnwidth]{figures/side_info.pdf} \caption{\small $\bm{h}_{\text{prev}}$ is added as an additional key and value to one self-attention layer. Arrows show which positions can pass information to which other positions.}\label{fig:token_insert} \end{figure} The fixed-size representation, $\bm{z}_1$, is passed through a feedforward network to produce an embedding $\bm{h}_{\text{prev},1}$ which represents the tokens processed so far, $t_{1:T}$. Next, instead of evaluating the pretrained transformer without modification on positions $T+1$ through $2T$, $\bm{h}_{\text{prev},1}$ is inserted at a single layer (denoted $\ell_{\text{ins}}$) of the pretrained model, as an additional embedding that may be used in the computation of attention, as shown in Figure~\ref{fig:token_insert}. To keep the number of embeddings per layer fixed, this embedding is only used as a key and a value, but not a query, in the self-attention layer. That is, for a window size of 300 tokens, there are 301 inputs to layer $\ell_{\text{ins}}$, but still only 300 outputs. The embeddings for positions $T+1$ to $2T$ are then pooled in the same way as Equation~\ref{eq:pool} to produce $\bm{z_2}$ and passed through the feedforward network, outputting $\bm{h}_{\text{prev},2}$. $\bm{h}_{\text{prev},2}$ is used to modify the execution of the pretrained language model on tokens $2T +1$ through $3T$, and so on. Because the model is now being applied recurrently, it is trained end-to-end with backpropagation through time. One could consider more complex recurrence modules, different methods for pooling the previous window's embeddings, or for inserting $\bm{h}_{\text{prev}}$ into the computation for the next window. We experimented with modifications such as max pooling instead of mean pooling, inserting multiple embeddings into the next window, inserting an embedding at all layers of the transformer for the next window, and using fixed key attention as the pooling function. However the performance after each of these changes was not significantly better than the model presented above, so we do not include those modifications here. \subsection{Gradient checkpointing in networks with bottlenecks} While our method can reduce the quadratic cost of attention by splitting the input into windows, we can also easily apply it to much longer contexts by use of gradient checkpointing~\cite{chen_checkpointing}. Gradient checkpointing is a method for lowering the peak memory requirement of training large neural networks. This is accomplished by storing only a subset of activations during the forward pass, and recomputing forward from those cached states during the backwards pass. For example, in a 100 layer feedforward network with uniformly wide layers, one could store the output of only every 10th layer. Then, during the backward pass, in order to compute the gradients for the 95th layer, one would re-compute layers 91 through 99 using the stored 90th layer activations. The overall memory cost is reduced to $\sqrt{L}$ at the cost of a single additional forward pass. In a network with variable width, the memory reduction can be even larger. When gradient checkpointing is applied to transformers, the outputs of each layer are usually stored ($k\times L \times T$ values), so that at most one set of self-attention activations is stored in memory at once. In the case of our recurrent models, we have an even narrower bottleneck: the $\bm{z}_i$'s and $\bm{h}_{\text{prev},i}$'s. Storing only these values means that the maximum number of activations present in memory while training on sequences $N$ tokens in length is $M + 2k\lceil{\frac{N}{T}}\rceil$, where $M$ is the number of activations stored when training the transformer on an individual window of length $T$. Because $k$ is extremely small compared to $M$, our model can be applied to very long contexts on any GPU on which the pretrained model could be fine-tuned. \section{Revisiting the evaluation of transformer language models}\label{transformer_eval} Before describing the empirical evaluation of our method, we discuss how transformer language models are evaluated in related work. The standard way of measuring perplexity uses extra computation in order to make as much context available for each token prediction. This yields low perplexities, but does not reflect how practitioners use transformer language models in applications. In this section, we describe the situation in detail and propose practical solutions that achieve relatively low perplexities while being closer to how transformers are used in practice. \subsection{Potential misalignment between LM evaluation and application} Transformers are often described as having quadratic time complexity in comparison to RNNs which have linear time complexity. However, this can be somewhat misleading when it comes to evaluation of perplexity on a test set. Given a test set of length $N$, an RNN requires $O(N)$ time to evaluate---but reaching the best perplexity for a transformer requires $O(NT^2)$, where $T$ is its maximum context size. (The preceding time complexities exclude hidden state size, number of layers, and batch size.) This much higher time complexity is due to the fact that a transformer may be run with its full context size once for each token in the test set, so that the maximum context is available for each prediction. Re-execution of the whole model for each token is required for models with absolute position embeddings, since hidden state reuse is only possible up to the maximum context size of the network. Note that it is possible to achieve smaller wall-clock time by splitting evaluation of a test set over multiple GPUs, but this is not applicable to the generation setting where outputs depend on prior ones. \begin{figure*} \centering \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.8\linewidth]{figures/disjoint.pdf} \caption{\small Disjoint execution. Predictions have context ranging between 1 and 3 tokens.}\label{fig:disjoint} \end{subfigure} \hfill \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.8\linewidth]{figures/overlap.pdf} \caption{\small Maximum overlap. All predictions except the first two have maximal context. }\label{fig:max_overlap} \end{subfigure} \hfill \begin{subfigure}{0.3\textwidth} \centering \includegraphics[width=0.8\linewidth]{figures/mid_overlap.pdf} \caption{\small Intermediate degree of overlap. Except the first prediction, all predictions attend to at least 2 tokens of context.}\label{fig:partial_overlap} \end{subfigure} \caption{\small Varying degree of overlap while evaluating a transformer with a window size of 3. The green (top) circles are outputs, and the blue (bottom) circles are inputs.\label{fig:overlap}} \end{figure*} To illustrate why re-computation is necessary, consider executing GPT-2 (which has 1024 position embeddings) on a test set. Each of the first 1024 tokens of a test set will have been passed into the network using a distinct position embedding. Having exhausted the position embeddings, one option is to start again with the 1025th token being treated as position 1---we will refer to this as \emph{disjoint execution}, illustrated in Figure~\ref{fig:disjoint}. The issue with disjoint execution is that it requires predicting the tokens at the beginning of a window from a very small amount of context. The alternative, which is used for standard test set evaluation, is \emph{overlapped execution}, as shown in Figure~\ref{fig:max_overlap}. The position embeddings are advanced by one position for each prediction, meaning that $T-1$ tokens are repeated between consecutive evaluations of the transformer, requiring much more computation. The benefit of this method is that it allows a model with $T$ position embeddings to have $T$ tokens of context for each prediction, as opposed to a variable amount between 1 and $T$. Stepping a transformer decoder forward one token at a time measures the best that such a model could perform, but it reflects a generative story that does not align with how the models may be used in practice. A perplexity that only measures the ability of GPT-2 to generate the 1024th token given a context of 1023 tokens is not necessarily indicative of the model's performance when generating from a smaller context. For example, the popular website Talk To Transformer\footnote{https://talktotransformer.com/} generates samples from GPT-2, but only provides 150 tokens of output. The evaluation of GPT-2 by stepping forward one token at a time provides little information about the quality of such generations. An example where the discrepancy is length instead of brevity is the GPT backed text adventure game AI Dungeon.\footnote{https://aidungeon.io/. Note that AIDungeon now uses the OpenAI GPT-3 API, but a similar project without OpenAI API access would still have to use GPT-2.} In this setting, the number of tokens can easily reach and exceed the full context size GPT-2 was trained on. Using overlapped execution as described above, generating each token would be 1024 times slower than with disjoint execution, so perplexity calculated by overlapped execution does not match this use case either. While lower perplexity seems to correspond to better generation with shorter contexts in practice (perhaps due to parameter sharing between all sequence positions), there is no reason that this need be the case in principle. To demonstrate an extreme case of the concern being discussed, let $F$ be a transformer model with vocabulary $V$, which uses the previous 1023 tokens as context, and consider the following generative story for generating token $t_i$: \begin{equation*} t_i \sim \begin{cases} \text{Uniform}(V) & \text{if $i \le 1023$}\\ F(t_{(i-1023):(i-1)}) & \text{otherwise} \end{cases} \end{equation*} Clearly the above generative model would not be of any practical use for generation or otherwise. However, because perplexity is calculated per token, increasing the size of the test set will lead to a measured perplexity that approaches that of a standard evaluation of the model $F$. This example is not representative of the models that are trained in practice, as even generations much shorter than the maximum context size from a GPT-2 model are quite impressive. However, it does demonstrate that the criteria that we use to compare models, or to select the best model during early stopping, place very high weight on the ability of the model to produce text given a full context, and a potentially vanishingly small amount on its ability to generate text using shorter contexts. \subsection{Varying overlap for evaluation}\label{overlap} As we are interested in increasing computational efficiency at evaluation time for pretrained models, we investigate their performance using overlapped execution, but with a reduced degree of overlap between windows. Varying the overlap lets us investigate the connection between degree of overlap and perplexity. The overlap used in evaluation will be defined to be the number of tokens from each input window that are repeated in the next window (see Figure~\ref{fig:overlap}). For example, consider a window size $T = 10$, and an overlap of 3. The windows that the transformer will be executed are then $t_{1:10}$, $t_{8:17}$, $t_{15:24}$, \textellipsis, $t_{1 + 7n:10 + 7n}$where $n$ indexes the window. These input windows are used to predict the spans of tokens $t_{2:11}$, $t_{12:18}$, $t_{19:25}$, \textellipsis, $t_{5 + 7n:11+ 7n}$. Figure~\ref{fig:partial_overlap} illustrates an intermediate overlap setting with $T=3$, and an overlap of 1. The perplexity minimizing evaluation setting for a transformer is then the extreme with an overlap $T-1$, and an overlap of 0 corresponds to disjoint execution. While a standard transformer can be evaluated with any degree of overlap, our augmentation method produces the embedding $\bm{h}_{\text{prev}}$, which is used during training to help predict the first token of a window of text. If we change the overlap at test time, the alignment of the text represented by $\bm{h}_{\text{prev}}$ and the current window of text will be different than the model was trained for, and so performance will degrade. To address this, we use the same overlap that will be used at test time during training for the recurrent models. \section{Experiments} In this section we provide experiments comparing our proposed technique to the default usage of transformer language models. We describe experiments on the WikiText-103 corpus and a subset of the PG-19 corpus, using the GPT-2-small language model as the pretrained transformer component of our models. WikiText-103 is a standard corpus for word level language modeling composed of approximately 29,000 documents from English Wikipedia, totaling about 103 million words. We use the WikiText-103 ``raw'' corpus, which does not have rare words replaced by ``UNK'' tokens. While we train using the BPE tokenization used by GPT-2, we normalize the final loss by the number of words rather than the number of BPE tokens for clarity. Although WikiText-103 does test long term dependencies, many of the documents are still shorter than the context size of the models we test. Therefore, we also use PG-19, which consists of books from the Project Gutenberg corpus. The average length of a WikiText-103 document is 3.6K words, while PG-19 documents (i.e.\ books) average 69K words, which far exceeds the context size of the models we test. However, the full PG-19 dataset is over 20 times larger than WikiText-103, so we use only a subset of it for training due to computational constraints. Specifically, we use only the first (alphabetically by filename) 1250 books of the PG-19 corpus, and use only the first 15000 tokens of each of the books in the validation set for early stopping. We make no modifications to the test set. In all our experiments we use the HuggingFace implementation of the pretrained GPT-2 small model (12 layers, 768-dimensional hidden state). For both the recurrent and baseline models, the GPT-2 model was fine-tuned, not left frozen. We selected learning rates for both our models and the baseline separately, by evaluating on WikiText-103 for the same set of candidate learning rates. We used the same learning rates for the PG-19 experiments without further hyperparameter search. We fine-tune all models for 2 epochs, measuring the validation loss every 2 million tokens. All models were trained with Adam~\cite{adam}, warming the learning rate up linearly from 0 to its final value over 100 steps. The feedforward network used to produce $\bm{h}_{\text{prev}, i}$ from window $i-1$ consisted of 3 hidden layers with dimension 200. We fixed $\ell_{\text{ins}}$ to be 2. Recall from Section~\ref{transformer_eval} that we are interested in evaluating the models in a setting similar to how they would be used in practice. To that end, we report separate perplexities for different degrees of overlap between adjacent windows of text, as described in Section~\ref{overlap}. For our models, we train with the same overlap that we test with, as unlike the baseline models, they cannot be trained with no overlap between adjacent windows and then tested with an overlap. This is because the embedding of the previous window of text is expected to represent all tokens up until the first token of the current window, but with an overlap of 30 for example, that embedding would be representing all tokens up until the 30th token of the current window. \subsection{Results} We first show that with the same amount of fine-tuning, our method achieves lower perplexity than a baseline GPT-2 model when evaluated using the same window size and degree of overlap between adjacent windows of text. It is important to emphasize that the perplexities we report are based on pretrained models, and so should not be compared to models trained from scratch on these datasets. The GPT-2 models were trained on text from a web crawl from which all Wikipedia documents are removed, but this still leaves open the possibility of quotes from Wikipedia having been encountered, or text from PG-19. \begin{table*} \small \centering \begin{tabular}{p{3cm}cp{2cm}p{3cm}c} Model & Overlap & Validation Perplexity & Test Perplexity & FLOPs/token\\ \midrule \multirow{5}{3cm}{GPT-2 (small), 300 token window} & 0 & 29.00 & 30.47 & $1.75\times 10^{8}$\\ & 5 & 27.99 & 29.36 & $1.78\times 10^{8}$\\ & 10 & 27.58 & 28.88 & $1.81\times 10^{8}$\\ & 30 & 26.72 & 27.96 & $1.94\times 10^{8}$\\ & 50 & 26.17 & 27.31 & $2.10\times 10^{8}$\\ \midrule \multirow{5}{3cm}{Recurrent, 20 windows of 300 tokens (Ours)} & 0 & 27.70 & 29.01 & $1.75\times 10^{8}$\\ & 5 & 26.88 & 28.12 & $1.78\times 10^{8}$\\ & 10 & 26.51 & 27.77 & $1.81\times 10^{8}$\\ & 30 & 25.90 & 27.12 & $1.94\times 10^{8}$\\ & 50 & 25.53 & 26.73 & $2.10\times 10^{8}$\\ \end{tabular} \caption{Results on WikiText-103}\label{tab:wikitext} \normalsize \end{table*} Table~\ref{tab:wikitext} shows the perplexity of our models and the non-recurrent GPT-2 models on the WikiText-103 dataset. The models compared here all use windows of 300 tokens, with varying degrees of overlap. The baseline models can only access information from the previous window of text through the overlapping tokens, while the recurrent models have a fixed size representation of the longer context. Our addition of recurrence increases the performance of the GPT-2 models in this setting, but by a relatively small amount. Increasing the overlap between each window of text decreases the perplexities of the baseline model as expected, but also decreases the perplexity of the recurrent models.\footnote{We did not attempt to train recurrent models with extremely high overlaps, as that would greatly increase the required training time} This indicates that there is room to increase the capacity of the recurrence mechanism, as if it passed all relevant information about the previous window forward, the overlapping tokens would be redundant. On the other hand, some useful information beyond what is contained in the local context is being propagated, as otherwise the baseline model should catch up in perplexity at higher overlaps. To investigate this further, we also experiment with the PG-19 dataset. The results for the PG-19 experiments are shown in Table~\ref{tab:pg19}. While we find only small increases in performances on the WikiText-103 dataset, we see larger improvements on PG-19, confirming our prediction that the gains would be larger on a dataset that has a larger context available for each prediction on average. We find that adding our recurrence module leads to a model that gives as good a perplexity with no overlap between adjacent windows as an unmodified model does when evaluated with an overlap of 30 out of 300 tokens in each window. Training the recurrent model with a 5 token overlap gives perplexity lower than the baseline perplexity with an overlap of 50 or even 75. In terms of FLOPs, adding our recurrence module and overlapping adjacent windows of tokens by 50 is less than half as costly as using a non-recurrent model with an overlap of 200. \begin{table*}[t] \small \centering \begin{tabular}{p{3cm}cp{2cm}p{3cm}c} Model & Overlap & Validation Perplexity & Test Perplexity & FLOPs/token\\ \midrule \multirow{9}{3cm}{GPT-2 (small), 300 token window} & 0 & 172.25 & 147.71 & $1.75\times\mathrm{10}^8$\\ & 5 & 165.93 & 142.30 & $1.78\times 10^8$\\ & 10 & 162.66 & 139.49 & $1.81\times 10^8$\\ & 30 & 156.21 & 134.30 & $1.94\times 10^8$\\ & 50 & 152.64 & 131.25 & $2.10\times 10^8$\\ & 75 & 149.54 & 128.46 & $2.33\times 10^8$\\ & 100 & 147.05 & 126.51 & $2.62\times 10^8$\\ & 150 & 143.62 & 123.53 & $3.50\times 10^8$\\ & 200 & 141.14 & 121.40 & $5.25\times 10^8$\\ \midrule \multirow{5}{3cm}{Recurrent, 20 windows of 300 tokens (Ours)} & 0 & 155.27 & 133.02 & $1.75\times 10^8$\\ & 5 & 150.00 & 128.78 & $1.78\times 10^8$\\ & 10 & 147.53 & 127.05 & $1.81\times 10^8$\\ & 30 & 142.35 & 122.22 & $1.94\times 10^8$\\ & 50 & 140.10 & 119.93 & $2.10\times 10^8$\\ \end{tabular} \caption{Results on PG-19}\label{tab:pg19} \normalsize \end{table*} \subsection{Effect of window size} As one of our motivations is to retain performance while decreasing compute requirements, we experiment with varying the window size used by our model and an unmodified GPT-2 model. At smaller window sizes the recurrent model has access to much more information than an unmodified GPT-2 model, which can only attend to the current window of tokens. Because of this, we expect our augmentation to cause the performance to fall off less rapidly with decreasing window size. The results, shown in Figure~\ref{fig:window_size}, confirm this prediction, as the performance gap widens with smaller window sizes. Figure~\ref{fig:flops} contains the same points (and additional baseline curves for various overlaps), but in terms of FLOPs rather than window size. In this comparison, all of the results of the recurrent models lie on the Pareto frontier, meaning that to improve perplexity or computational cost, one must worsen the other. The non-monotonicity of the overlap 30 and 50 curves is due to the fact that at smaller window sizes, an overlap represents a higher fraction of the computation being used for positions that predictions were already produced for. Also note that while the baseline with overlap 50 curve has the lowest absolute perplexity in Figure~\ref{fig:flops}, the recurrent models trained with overlaps shown in Table~\ref{tab:pg19} still perform better. \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/pg19_chunk_size.png} \caption{\small Effect of window size on performance on PG-19 validation set}\label{fig:window_size} \end{figure} \begin{figure} \centering \includegraphics[width=\columnwidth]{figures/pg19_flops.png} \caption{\small Relationship between FLOPs and perplexity for recurrent and non-recurrent models. Each curve ranges over window sizes from 200 to 600.}\label{fig:flops} \end{figure} \subsection{What information is being propagated between windows?} \begin{table*}[t] \small \setlength{\tabcolsep}{4pt} \begin{tabular}{p{0.48\textwidth}p{0.37\textwidth}p{0.09\textwidth}} Context & Continuation & Topic\\ \midrule \textellipsis{} It drains a territory of 300,000 square miles, and, traced back to the rise of its principal source, is 2,000 miles long. At two points, Needles and Yuma on the California boundary, it is crossed by a railroad. Elsewhere its course lies far from Caucasian settlements and far from the routes of common travel, in the heart of a vast region fenced on the one hand by arid plains or deep forests and on the other by formidable mountains & . The first of the two great rivers, the Mississippi, was the first to be navigated by the Americans, and the first to be navigated by the Indians. The other was the first to be navigated by the Americans, and the first to be navigated by the Indians. The first of the two great streams, the Mississippi, was navigable by the Indians, and the first by the English\textellipsis{} & Rivers \\ \midrule \textellipsis{} ``Mr. Hammerby will have to wait for his money.'' ``Will he?'' ``I don't see what else he can do. But, aside from that, three dollars and a half won't keep us a month. I'll have to & get the money, and he'll be glad to see you again.'' ``I'm glad to see you again, Tom. I'm glad to see you again. I'm glad to see you again. I'm glad to see you again. I'm glad to see you again & Money\\ \midrule \textellipsis{} Long's his sister, Thankful, lived, we couldn't say nothing, of course. If she wanted to slave and work so's her brother could live in idleness and sloth, why, that was her business. There ain't any law against a body's making a fool of herself, more's the pity. But she's been dead a year, and he's done nothing since but live on those that'll trust him, and ask help from the town. He ain't sick--except sick of work. [\textellipsis{}] to-mor & rer and his wife, and the whole family. He was a good man, and he was a good man. He was a good man, and he was a good man. He was a good man, and he was a good man. He was a good man, and he was a good man. He & Family, Description of a man\\ \midrule \textellipsis{} and any form of thought or any institution tending to suppress education or destroy intelligence strikes at the very essence of the government, and constitutes a treason which no law can meet, and for which no punishment is adequate. Education, then, as universally diffused as the elements of God, is the life-blood of our body politic. The intelligence of the people is the one great fact of our civilization and our prosperity,--it & is the only way to preserve the peace of the world. The only way to preserve the peace of the world is to preserve the liberty of the people. The first step to be taken is to abolish the power of the government. The first step to be taken is to abolish the power of the people. The first step to \textellipsis{} & Government\\ \midrule \end{tabular} \caption{\small Continuations of PG-19 validation set passages using recurrent model ($T=300$, disjoint) which display approximate continuation of topic. Contexts are shortened for space, 300 tokens of context were used for each.}\label{tab:samples} \normalsize \end{table*} \begin{table*} \small \setlength{\tabcolsep}{4pt} \begin{tabular}{p{0.57\linewidth}p{0.39\linewidth}} Context & Continuation\\ \midrule \textellipsis{} Elaine, however, did not gratify their hopes; she referred to the ball with the detachment she would have shown in describing a drawing-room show of cottage industries. It was not difficult to discern in her description of the affair the confession that she had been slightly bored. From Courtenay, later in the day, the aunts received a much livelier impression of& the house, and the two women were standing in the doorway. ``I am afraid I have not been very well,'' she said, as she looked at the two men. ``I have been very much worried about you, and I have been very much worried about you. I have been very much worried about you, and I have been very much worried about you. I have been very much pleased with you, and I have been very much\\ \midrule \textellipsis{} ``Oh, he's not at all a bookworm,'' said Suzette quickly, ``though he's tremendously well-read. He's quite the man of action.'' ``Does he hunt?'' asked Elaine. ``No, he doesn't get much time or opportunity for riding.'' ``What a pity,'' commented Elaine; ``I don't think I could marry a man who wasn & '' ``I don't know,'' said the Sergeant, ``but I have heard that you are a very good friend.'' ``I am not,'' said the girl, ``I am not.'' ``I am not,'' said the Sergeant, ``I am not.'' ``I am not,'' said the girl, ``I am not.\\ \midrule \textellipsis{} Gregg was still the soft-stepping scoundrel who invited the toe of honesty, and Mornway, as he entered, was conscious of a sharp revulsion of feeling. But it was impossible to evade the interview, and he sat silent while the man stated his case. Mrs. Mornway had represented the stenographer as being in desperate straits, and ready to accept any job that could be found, but though his appearance might have seemed to corroborate her account, he evidently took a less hopeless view of his case, and the Governor found with surprise that he had fixed his eye on a clerkship & that he had been in the habit of doing, and that he had been in the habit of doing. ``I'm not going to be a fool,'' he said, ``and I'm not going to be a fool,\textellipsis{}\\ \midrule \textellipsis{} Many transactions too, from a desire to avoid worrying me, were carried through without my knowledge, although formerly, as a matter of course, they would have been submitted to me. Strangers, when they called, asked to see Johnson or Marsh. I directed the messenger that they were to be shown into my room if I was disengaged. This was a failure, for, when they came, I was obliged to ask for help, which was not given very generously. Sometimes I sent for the papers, but it took a long time to read them, and my visitors became impatient. During one of these interviews, I remember that I was sorely perplexed, but I had managed to & get the money, and I was glad to get it. The next day I went to the Court of the Emperor, and found him standing in the courtyard of the Palace, with a large number of soldiers. He was dressed in a very dirty uniform, and wore a very dirty hat. He was dressed in a very dirty uniform, and wore a very dirty hat. He was dressed in a very dirty hat, and wore a very dirty hat\\ \midrule \textellipsis{} I know at which crossings to look out--I know what I'm going to see in the shop-windows. It saves a lot of wear and tear to know what's coming. For a good many years I never did know, from one minute to another, and now I like to think that everything's cut-and-dried, and nothing unexpected can jump out at me like a tramp from a ditch.'' He paused calmly to knock the ashes from his cigar, and Garnett said with a smile: ``Doesn't such a plan of life cut off nearly all the possibilities?'' The old gentleman made a contemptuous motion. ``Possibilities of what? Of being multifariously miserable? There are lots of ways of being & ''I'm afraid I'm not going to be able to do that,'' he said. ``I'm going to have to go to the station. I'm going to have to go to the station. I want to see the station. I want to see the station. I want to see the station. I want to see the station. I want to see the station. I want to see the station. I want to see the station. I want to see\\ \midrule \end{tabular} \caption{\small Continuations of PG-19 validation set passages using recurrent model ($T=300$, disjoint) which display continuation of correct pronouns or references to characters from context. Contexts are left-truncated, 300 tokens of context were given for each continuation.}\label{tab:pronouns} \normalsize \end{table*} In this section we show sample continuations (using greedy argmax decoding) from contexts in the PG-19 validation set, which illustrate types of information that the recurrent module passes (or fails to pass) forward. Table~\ref{tab:samples} shows that high level topical information is often propagated forward to some extent.\footnote{The collapse into repetition seen in many of the examples is a common effect when using argmax decoding with language models. To get qualitatively better text, other decoding methods should be used, but our goal here is to identify information being propagated through the learned recurrence mechanism.} For example, the first sample continues a description of rivers using only information passed through the recurrent module. Table~\ref{tab:pronouns} shows that the recurrent module can pass some information about what characters are in the context (mostly in the form of using the correct pronouns). The first sample, for instance, generates ``the two women'' after two women were described in the context (as well as ``the aunts''). On the other hand, the examples also contain several discontinuities between the context and the continuation in terms of local syntax or facts, such as in the last example in Table~\ref{tab:pronouns}, where the closing quote mark which was predicted from the previous window is interpreted as an opening one. These are the types of issues that evaluation with an overlap between adjacent windows may easily address---a fact that likely accounts in part for the gap between the recurrent model with disjoint and overlapped execution shown in Table~\ref{tab:pg19}. The examples also show new characters being invented rather than using those in the context. The recurrent module acts as a bottleneck, and seems to have too little capacity to convey this type of information. A higher capacity bottleneck could perhaps capture such information, but at the cost of additional compute and memory. \section{Conclusion and Future work} We showed that augmenting a pretrained language model with a recurrence module during fine-tuning can allow increased performance given a fixed computational budget. Our method can be similarly applied to improve the computational efficiency of pretrained models that already exist for many languages and domains, as well as for future models that will be developed. It can also allow their application to longer contexts than they were trained for, increasing their flexibility. There are two main extensions to this work that merit exploration. The first is increasing the capacity of the recurrence mechanism in such a way that it can pass more fine-grained information forward between windows. \citet{dai-etal-2019-transformer} have a very high capacity recurrent connection in the form of directly attending to the previous window, but this is not applicable to existing pretrained models that use absolute position embeddings. The goal would be to identify a mechanism that can pass information more effectively while still being learnable from a small fine-tuning dataset and without significantly increasing the computational cost. The other direction is to use our recurrent method with the BERT family of models for tasks other than language modeling. Many of the tasks used to evaluate BERT-like models, such as those of the GLUE benchmark~\cite{glue}, use very short texts. On the other hand, the RACE~\cite{race} reading comprehension dataset has been used as well, and does contain some examples that exceed the 512 token context of BERT\@. Applying our method to a transformer pretrained with masked language modeling could allow application to longer contexts, or increased computational efficiency on smaller contexts. \section*{Acknowledgments} This material is based upon work supported by the National Science Foundation under Award Nos.~1941178 and 1941160.
{'timestamp': '2020-08-18T02:21:15', 'yymm': '2008', 'arxiv_id': '2008.07027', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07027'}
arxiv
\section{Introduction}\label{sec1} Observational data sources are expanding to include large registries and electronic health records, providing new opportunities to obtain comparative effectiveness evidence among broader target patient populations. Although traditional methods for observational studies focus on estimating the average treatment effect in a fixed target population, the rise of personalized healthcare and the increasing complexity of observational data have generated a more patient-centric view for drawing causal inferences about treatment effect. As a result, treatments need to be tailored to the covariate distribution of the target population, which necessitates the evaluation of \emph{treatment effect heterogeneity} (TEH). If TEH presents, there exists a partition of the population into subgroups across which the treatment effect differs. Because the assessment of TEH requires addressing challenges due to complex and oftentimes high-dimensional individual characteristics, using flexible modeling techniques such as machine learning methods within the counterfactual framework is a promising approach and has received increasing attention in the statistical literature. For example, Foster et al. \cite{foster2011subgroup} studied the virtual twins approach that first uses random forests to estimate the individual treatment effect (ITE). They obtained the difference between the predicted counterfactual outcomes under different treatment condition for each unit, and then regressed the predicted ITEs on covariates to identify subgroups with a treatment effect that is considerably different than the average treatment effect. Wager and Athey \cite{wager2018estimation} developed the causal forests for ITE estimation. Lu et al. \cite{lu2018estimating} compared several random forests methods, including Breiman forests, causal forests and synthetic forests, \cite{ishwaran2014synthetic} for predicting ITE and found that the synthetic RF had the best performance. Hill \cite{hill2011bayesian} adapted the Bayesian Additive Regression Trees (BART) for causal inference and described methods for visualizing the modes of the predicted ITEs to gain insights into the underlying number of subgroups. Anoke et al. \cite{anoke2019approaches} \emph{a priori} set the number of subgroups and group observations based on percentiles of the empirical distribution of either the ITEs or propensity scores and estimated a treatment effect within each subgroup. They compared several machine learning methods including BART, gradient boosted models and the facilitating score method, for the estimation of TEH and found BART performed the best in their simulation studies. While these previous studies focus either on continuous or binary outcomes, time-to-event outcomes are of primary interest in many biomedical studies. \cite{hu2018modeling, ennis2018brachytherapy} Besides the average survival treatment effect, it is also important to understand whether there is survival TEH in order to make informed personalized treatment decisions. \cite{chen2018challenges} The detection of survival TEH, however, may be complicated by the right censoring (e.g. due to loss-to-follow-up) as well as challenges in precisely relating survival curves to individual covariates. Extending BART to survival outcomes, Henderson et al. \cite{henderson2020individualized} developed a nonparametric accelerated failure time (AFT) model to flexibly capture the relationship between covariates and the failure times for the estimation of ITE. Tian et al.\cite{tian2014simple} approached the TEH problem by modeling interactions between a treatment and a large number of covariates. Both methods were designed for analyzing data from randomized clinical trials, with little empirical evidence within the context of observational studies. Shen et al. \cite{shen2018estimating} used random forests with weighted bootstrap to estimate the optimal personalized treatment strategy; however, identification of TEH was not the focus of their paper. Cui et al.\cite{cui2020estimating} extended the causal forests of Wager and Athey \cite{wager2018estimation} for ITE estimation to accommodate right censoring, and used bootstrap for inference. Tabib and Larocque \cite{tabib2020non} also proposed a new random forests splitting rule to partition the survival data with the goal of maximizing the heterogeneity of the ITE estimates at the left and right nodes from a split. Neither of the last two methods has made software publicly available. Despite burgeoning literature in causal machine learning methods for survival data, their comparative performance for estimating the survival TEH remains under-explored. The practical implementation of machine learning methods for detecting possible survival TEH also merits additional study. To address these gaps and facilitate better use of machine learning for estimating survival TEH, we carry out a series of simulations to investigate the operating characteristics of nine state-of-the-art machine learning techniques, including \begin{enumerate} \itemsep-0.3em \item[(1)] nonparametric BART model within the AFT framework (AFT-BART-NP);\cite{henderson2020individualized} \item [(2)] a variant of AFT-BART-NP where the estimated propensity score is included as a covariate (AFT-BART-NP-PS); \item[(3)] semiparametric BART model within the AFT framework (AFT-BART-SP); \cite{henderson2020individualized} \item[(4)] random survival forests (RSF);\cite{ishwaran2008random} \item[(5)] Cox regression based on deep neural network (DeepSurv); \cite{katzman2018deepsurv} \item[(6)] deep learning with doubly robust censoring unbiased loss function (DR-DL); \cite{steingrimsson2020deep} \item[(7)] deep learning with Buckley-James censoring unbiased loss function (DL-BJ); \cite{buckley1979linear,steingrimsson2020deep} \item[(8)] targeted survival heterogeneous effect estimation (TSHEE); \cite{zhu2020targeted} \item[(9)] generalized additive proportional hazards model (GAPH) \cite{hastie1990generalized}. \end{enumerate} These techniques are representative of the recent machine learning advancement specifically designed for estimating individual-specific survival functions with right-censored failure time data; details of each method are reviewed in Section \ref{sec:methods}. In particular, recent work of Dorie et al. \cite{dorie2019automated} and Hahn et al. \cite{hahn2020bayesian} suggests that inclusion of an estimated propensity score in the BART model can improve the estimation of causal effects with non-censored outcomes. To investigate whether the utility of this strategy is transferable to censored survival outcomes, we considered a version of the nonparmetric AFT BART model, AFT-BART-NP-PS, where the estimated propensity score was included as a covariate in model formulation. We contributed sets of simulations representing a variety of causal inference settings, and evaluated the empirical performance of these machine learning methods, with emphasis on new insights that can be gained, relative to the average survival treatment effects. We also compared these machine learning methods with two commonly used parametric and semi-parametric regression methods, the AFT and Cox proportional hazards model, and elucidated the ramifications of potentially restrictive parametric model assumptions. Finally, to improve our understanding of the survival effect under two radiotherapy approaches for treating high-risk localized prostate cancer, we applied these machine learning methods to an observational dataset drawn from the national cancer registry database (NCDB). We focused on 7330 prostate cancer patients \cite{ennis2018brachytherapy} who received either external beam radiotherapy (EBRT) combined with androgen deprivation (AD), EBRT+AD, or EBRT plus brachytherapy with or without AD, EBRT+brachy$\pm$AD, with at least 7920 cGy EBRT dose, and explored the possible survival TEH in relation to individual covariate information. The remainder of the paper is organized as follows. Section \ref{sec:methods} introduces causal assumptions and estimand of interest; it further provides a concise overview of each machine learning method considered. In Section \ref{sec:simulations}, we describe the data generating processes and parameter constellations in our simulation study. Section \ref{sec:results} summarizes the comparative findings from simulation studies. In Section \ref{sec:example}, we provide a case study where we estimated the heterogeneous survival treatment effects of two radiotherapy approaches for high-risk localized prostate cancer patients. Section \ref{sec:discussion} concludes with a discussion. \section{Statistical Methods} \label{sec:methods} \subsection{Notation and causal estimand}\label{sec:setup} Consider an observational study with two treatment conditions and $n$ observations, $i=1,\ldots,n$. Let $Z_i$ be a binary treatment variable with $Z_i=1$ for treatment and $Z_i=0$ for control, and $X_i$ be a vector of confounders measured before treatment assignment. We proceeded in the counterfactual framework, and defined the causal effect for individual $i$ as a comparison of $T_i (1)$ and $T_i (0)$, representing the counterfactual survival times that would be observed under treatment and control, respectively. We similarly define $C_i(1)$ and $C_i(0)$ as the counterfactual censoring times under each treatment condition. We further write $T_i$ as the observed survival time and $C_i$ the observed censoring time. The observed outcome consists of $Y_i=\min(T_i, C_i)$ and censoring indicator $\Delta_i=I (T_i<C_i)$. Throughout, we maintained the standard assumptions for drawing causal inference with observational survival data: \cite{chen2001causal} \begin{enumerate} \itemsep-0.3em \item[(A1)] Consistency: The observed failure time and censoring time $T_i=Z_i T_i (1)+(1-Z_i) T_i (0)$ and $C_i = Z_i C_i(1) + (1-Z_i) C_i(0)$; \item[(A2)] Weak unconfoundedness: $T_i (z) \amalg Z_i | X_i \text{ for } Z_i= z,z\in\{0,1\}$; \item[(A3)] Positivity: the propensity score for treatment assignment $e(X_i)=P(Z_i=1|X_i)$ is bounded away from 0 and 1; \item[(A4)] Covariate-dependent censoring: $T_i (z) \amalg C_i(z) | \{X_i,Z_i\}$, for $Z_i= z,z\in \{0,1\}$. \end{enumerate} Assumption (A1) maps the counterfactual outcomes and treatment assignment to the observed outcomes. It allows us to write $Y_i=Z_iY_i(1)+(1-Z_i)Y_i(0)$, where $Y_i(z)=\min\{T_i(z),C_i(z)\}$. Likewise, $\Delta_i=Z_i\Delta_i(1)+(1-Z_i)\Delta_i(0)$, where $\Delta_i(z)=I\{T_i(z)<C_i(z)\}$. Assumption (A2) is referred to as the ``no unmeasured confounders'' assumption. Because this assumption is generally not testable without additional data, sensitivity analysis may be required to help interpret the causal effect estimates.\cite{hogan2014bayesian} Assumption (A3) is also referred to as the overlap assumption,\cite{li2018balancing} which requires that the treatment assignment is not deterministic within each strata formed by the covariates. This assumption can be directly assessed by visualizing the distribution of estimated propensity scores. Finally, Assumption (A4) states that the counterfactual survival time is independent of the counterfactual censoring time given the pre-treatment covariates and treatment. This condition directly implies $T_i \amalg C_i | \{X_i,Z_i\}$, and is akin to the ``independent censoring'' assumption in the traditional survival analysis literature. For survival outcomes, the population-level survival treatment effect can be characterized by the survival quantile effect, \cite{mao2018propensity} \begin{equation} \label{eq:survq} \omega^q=\theta^{q}(1)-\theta^{q}(0)=\sup\left \{ t: P(T(1)\leq t) \leq q \right \} - \sup\left \{ t: P(T(0)\leq t) \leq q \right \} \end{equation} where $q$ is a pre-specified number between 0 and 1. The estimand \eqref{eq:survq} compares the $q$th quantile of the marginal counterfactual survival distribution under the treated and the control condition. Implicit in our notation, we assume that the treatment strategy includes a hypothetical intervention that removes censoring until the end of follow-up. It has been suggested that the survival quantile effect should be used when the proportional hazards assumption does not hold. \cite{uno2014moving,uno2015alternatives} In this paper, we focus on $q=1/2$ and $\omega^{q=1/2}$ corresponds to the causal contrast in median survival times, which is a natural summary statistics of the entire causal survival curve and of clinical relevance. \cite{mao2018propensity,hu2019causal} Extending the population-level treatment effect \eqref{eq:survq}, we define the \emph{individual survival treatment effect} (ISTE) as \begin{equation}\label{eq:ISTE} \omega^{q=1/2}(x)=\theta^{q=1/2}(1,x) - \theta^{q=1/2}(0,x), \end{equation} where $\theta^{q=1/2}(z,x) = \sup\left \{ t: P\left( T(z)\leq t | X=x\right) \leq 1/2\right \} $. In other words, $\theta^{q=1/2}(z,x)$ represents the median survival time of the conditional counterfactual survival function $P(T(z)>t|X=x)$ and $\omega^{q=1/2}(x)$ is alternatively called the \emph{conditional survival treatment effect}. Because only the outcome, $(Y_i, \Delta_i)$, corresponding to the actual treatment assignment is observed, the ISTE as a function of the unknown counterfactuals is not directly identifiable without additional assumptions. However, under assumptions A1-A3, we have \begin{align}\label{eq:identify} P\left( T(z)>t|X=x \right)= P\left( T(z)>t|Z=z,X=x \right) =P\left( T>t|Z=z,X=x\right), \end{align} where $P\left( T>t|Z=1,X=x\right)$ becomes the group-specific survival functions conditional on $X=x$ and is estimable from observed data. Specifically, the identification condition \eqref{eq:identify} allows us to estimate $\omega^{q=1/2}(x)$ by fitting two survival outcome regression models, $\mathcal{M}_0$ and $\mathcal{M}_1$, to two sets of the observed data $\{X_i,Y_i, \Delta_i \mid Z_i=0\}$ and $\{X_i,Y_i, \Delta_i \mid Z_i=1\}$. We then predict, for each data point, two individual-specific counterfactual survival curves conditional on individual covariate profile $X_i$, $\hat{P}\left( T_i(z)>t|X_i \right)=\hat{S}_{\mathcal{M}_z}(t,X_i)$, from model $\mathcal{M}_z, z= 0,1$. The general form of the ISTE estimator is then given by \begin{equation}\label{eq:medsurv} \hat{\omega}^{q=1/2}(X_i) = \hat{\theta}_{\mathcal{M}_1}^{q=1/2}(X_i) - \hat{\theta}_{\mathcal{M}_0}^{q=1/2}(X_i), \end{equation} where $\hat{S}_{\mathcal{M}_1} \left( \hat{\theta}_{\mathcal{M}_1}^{q=1/2}(X_i), X_i\right) = \hat{S}_{\mathcal{M}_0} \left( \hat{\theta}_{\mathcal{M}_0}^{q=1/2}(X_i), X_i\right) = 1/2$. \subsection{Estimating individual-specific counterfactual survival curves}\label{sec:overview} Because the estimation of the causal estimand \eqref{eq:ISTE} critically depends on the estimation of individual-specific counterfactual survival functions (or conditional survival functions), $\hat{S}_{\mathcal{M}_z}(t,X)$ for $z=0,1$, below we briefly review the machine learning methods for estimating $\hat{S}_{\mathcal{M}_z}(t,X)$. For simplicity, we drop the subscript ${\mathcal{M}_z}$ in the survival function, and only note here that the flexible outcome model will be fitted for each treatment group in a symmetric fashion, and the causal interpretation will be based on \eqref{eq:identify}. \subsubsection{Accelerated failure time BART model} The AFT-BART model relates the failure time $T$ to the covariates through $\log T = f(X)+W$, where $f(X)$ is a sum-of-trees BART model\citep{chipman2010bart}, $f(X)=\sum_{j=1}^J g(X;\mathcal{T}_j,\mathcal{M}_j)$, and $W$ is the residual term. The sum-of-trees model is fundamentally an additive model with multivariate components, which can more naturally incorporate interaction effects than generalized additive models and more easily incorporate additive effects than a single tree model. \citep{chipman2010bart} If $W$ is assumed to follow a Gaussian distribution, the resultant model is semi-parametric, termed as AFT-BART-SP. Henderson et al.\cite{henderson2020individualized} model the distribution of $W$ as a location-mixture of Gaussian densities by using the centered Dirichlet process (CDP), leading to a Bayesian nonparametric specification, which we refer to as AFT-BART-NP. The individual trees $\mathcal{T}_j$ and bottom nodes $\mathcal{M}_j$ are tree model parameters. A regularization prior is placed on $\{\mathcal{T}_j,\mathcal{M}_j\}$ to allow each individual tree model to contribute only a small part to the overall fit and therefore avoids over-fitting. \cite{chipman2010bart} Furthermore, prior distributions are assumed for the distributional parameters of the residual term $W$, including the normal variance components, or the location and scale parameters for the CDP assumption. The posterior distributions of AFT model parameters are computed using Markov chain Monte Carlo (MCMC) -- Metropolis-within-Gibbs sampler for updating tree parameters and then Gibbs sampler for parameters related to the residual distribution. The unobserved survival times are imputed from a truncated normal distribution $N_{(\log Y_i,\infty)}\left( f(X_i),\sigma^2\right)$ in each Gibbs iteration, where $\sigma^2$ is the variance or common scale of the residual term. The individual-specific survival curve can then be calculated by summarizing the posterior predictive distribution of \begin{equation*} S^{\text{AFT-BART-SP}}(t,X_i) = 1-\Phi \left( \frac{\log t-f(X_i)}{\sigma} \right) \end{equation*} for AFT-BART-SP, where $\Phi(\cdot)$ is the cumulative standard normal distribution and $\sigma$ is the variance of the residual term. For AFT-BART-NP, the individual-specific survival curve is calculated by summarizing the posterior predictive distribution of \begin{equation*} S^{\text{AFT-BART-NP}}(t,X_i) = 1-\sum_{l=1}^L \pi_l \Phi \left( \frac{\log t-f(X_i)-\tau_l}{\sigma} \right), \end{equation*} where $\pi_l$ is the mixture proportion of cluster $l$ ($l=1,\ldots,L$), $\tau_l$ is the cluster-specific location parameter, $\sigma$ is the common scale parameter. Additional technical details are available in Herderson et al. \cite{henderson2020individualized} A recent review of BART methods can also be found in Tan and Roy. \cite{tan2019bayesian} A direct implication from the weak unconfoundedness assumption (A2) is that $T_i(z)\amalg Z_i|e(X_i)$ for $Z_i=0,1$, suggesting that controlling for the one-dimensional propensity score is sufficient to remove confounding in estimating the average causal effect.\cite{rosenbaum1983central} For the purpose of estimating ITE with non-censored outcomes, Dorie et al. \cite{dorie2019automated} and Hahn et al. \cite{hahn2020bayesian} considered including an estimated propensity score as an additional covariate in BART for improved robustness and estimation efficiency. Assuming $\hat{e}_i$ is an estimate of $e(X_i)$, we further consider a version of AFT-BART-NP that includes both $X_i$ and $\hat{e}_i$ in the model formulation. To mitigate concerns on model misspecification, we obtain the propensity score estimate, $\hat{e}_i$, non-parametrically from a Super Learner \cite{pirracchio2015improving} and treat it as a fixed covariate in the subsequent AFT-BART-NP model formulation. The individual-specific survival curve from AFT-BART-NP-PS is then obtained by summarizing the posterior predictive distribution of \begin{equation*} S^{\text{AFT-BART-NP-PS}}(t,X_i, \hat{e}_i) =1-\sum_{l=1}^{L^*} \pi_l \Phi \left( \frac{\log t-f(X_i, \hat{e}_i)-\tau_l}{\sigma} \right), \end{equation*} where $\pi_l$ is the mixture proportion of cluster $l$ ($l=1,\ldots,L^*$), $\tau_l$ is the cluster-specific location parameter, and $\sigma$ is the common scale parameter. \subsubsection{Random survival forests} The RSF approach extends Breiman random forests to right-censored survival data. \cite{ishwaran2008random} The key idea of the RSF algorithm is to grow a binary survival tree $\mathcal{H}$ and construct the ensemble cumulative hazard function (CHF). Each terminal node of the survival tree contains the observed survival times and the binary censoring information for individuals who fall in that terminal node $h\in\mathcal{H}$. Let $t_{1,h} < t_{2,h}<\ldots, t_{N(h),h}$ be the $N(h)$ distinct event times. The CHF estimate for node $h$ is the Nelson-Aalen estimator $\hat{\Lambda}_h = \sum_{\{l:t_{l,h}\leq t\}} {d_{l,h}}/{R_{l,h}}$, where $d_{l,h}$ and $R_{l,h}$ are the number of events and size of the risk set at time $t_{l,h}$. All individuals within node $h$ then have the same CHF estimate. To compute the CHF for an individual with covariates $X_i$, one can drop $X_i$ down the tree, and obtain the Nelson-Aalen estimator for $X_i$'s terminal node, $\Lambda(t|X_i)=\hat{\Lambda}_h(t)$ if $X_i \in h$. The out-of-bag (OOB) ensemble CHF for each individual, $\lambda^{\text{OOB}}(t|X_i)$, can be calculated by dropping OOB data down a survival tree built from in-bag data, recording $i$’s terminal node and its CHF and taking the average of all of the recorded CHFs. By a conversation-of-events principle, \cite{ishwaran2008random} the individual-specific survival curve can be computed as one minus the estimated ensemble OOB CHF summed over survival times (event time or censoring time) until $t$, conditional on $X_i$, namely \begin{equation*} S^{\text{RSF}}(t,X_i)=1-\sum_{\{j:T_j\leq t\}} \hat{\Lambda}^{\text{OOB}} (T_j|X_i). \end{equation*} \subsubsection{Targeted survival heterogeneous effect estimation} TSHEE was recently proposed based on the doubly robust estimation method, the targeted maximum likelihood estimation (TMLE), for survival causal inference. \cite{zhu2020targeted} At the first step, a stylized counting process representation of the survival data is created, then the Super Learner \cite{van2007super} is applied to estimate, for each individual at each survival time point, the conditional hazard rate $h(t|X_i)$. The initial individual survival function is then derived via the probability chain rule, $$S(t,X_i) = \prod_{j:t_j\leq t} q(t_j|X_i).$$ In the second step, the initial estimator is adjusted with conditional censoring probability $P(C>t|Z,X)$ and the propensity score $e(X)$ using the one-step TMLE. \cite{cai2020one} To carry out the one-step TMLE, one replaces the univariate conditional hazard function $q(t|X)$ -- a covariate in a logistic regression working (fluctuation) model for the failure event conditional hazard -- with a high dimensional vector $\overrightarrow{q}(\bullet|X) = \left( q(t_1|X), \ldots, q(t_{\max}|X)\right)$, where $\{t_1$, \ldots, $t_\text{max}\}$ corresponds to the set of ordered unique survival times. Fitting the high-dimensional logistic regression, the one-step TMLE updates in small steps locally along the working model to iteratively update the conditional survival function of failure event to form a targeted estimator $S^{\text{TSHEE}}(t,X_i)$. We refer to Zhu and Gallego \cite{zhu2020targeted} for full technical details on TSHEE. \subsubsection{Cox regression based on deep neural network} DeepSurv is a Cox regression tool based on deep neural network. \cite{katzman2018deepsurv} It uses a deep feed-forward neural network to predict the effects of individual covariates on their hazard rate parameterized by the weights of the network. The input to the network is each individual's baseline covariates $X_i$. The network propagates the inputs through a number of hidden layers with weights $\xi$. The weights parameter $\xi$ is optimized to minimize the average negative log partial likelihood subject to $\ell_2$ regularization, $$l^{\text{PL}}(\xi)\coloneqq -\frac{1}{N_E} \sum_{i:\Delta_i=1} \left[ {h}_\xi(X_i) -\log \sum_{j\in R(Y_i)} \exp\left \{ {h}_\xi(X_i)\right \} \right] +\kappa ||\xi||_2^2,$$ where $N_E$ is the number of observed events, $Y_i$'s are the unique observed survival times, $R(Y_i)$ is the risk set at time $Y_i$, ${h}_\xi(\cdot)$ is the log hazard function, and $\kappa$ is $L_2$ regularization parameter. The hidden layers comprise fully-connected layer of nodes, followed by a dropout layer. As a fully connected layer occupies most of the parameters, neurons develop co-dependency amongst each other during the training phase, which leads to over-fitting of training data. By dropping out individual nodes, i.e., neurons with certain probability during the training phase, a reduced network is retained to prevent over-fitting. The output of the network estimates the log hazard function $\hat{h}_\xi(X)$ within the Cox model framework. To compute the individual-specific survival curve, we first calculate the Nelson-Aalen estimate of the baseline CHF using $\hat{h}_\xi(X_i)$ outputted by DeepSurv, $$\hat{\Lambda}_0(t) = \sum_{i:Y_i\leq t} \dfrac{\Delta_i}{\sum_{j\in R(Y_i)} \exp\left \{ \hat{h}_\xi(X_i)\right \} }.$$ We then relate the survival function to the CHF and estimate the individual-specific survival curve by $$S^{\text{DeepSurv}} (t,X_i) = \exp \left[ -\hat{\Lambda}_0(t) \exp\left \{ \hat{h}_\xi(X_i)\right \} \right].$$ \subsubsection{Censoring unbiased deep learning survival model} A recent deep learning (DL) survival modeling technique builds upon the DL algorithms for uncensored data, but develops censoring unbiased loss functions to replace the unobserved full data loss, resulting in two DL algorithms for censored survival outcomes – one with doubly robust censoring unbiased loss (DR-CL) and one with Buckley-James censoring unbiased loss (BJ-DL). \cite{steingrimsson2020deep} The doubly robust loss function consists of two terms, one based on uncensored outcomes and one constructed to inversely weight observed outcome information with functionals of the event or censoring probability. The loss function is doubly robust in the sense that it is a consistent estimator for the expected loss if one of the models for failure time $T$ or censoring time $C$ is correctly specified but not necessary both. A related estimator BJ-DL requires only modeling the conditional survival function for $T$ for the term of censored outcomes in the loss function, which does not share the property of double robustness with the DR-CL estimator. A survival prediction model, $S(t,X)$, can be obtained by replacing the full data loss function with either the doubly robust or Buckley-James loss function and minimizing the Brier risk. \cite{steingrimsson2020deep} Specifically, $S^{\text{DR-DL}}(t,X_i)$ minimizes the doubly robust censoring unbiased loss $$\mathcal{L}^{\text{DR}}(t) = \frac{1}{n} \sum_{i=1}^n \frac{\delta_i(t)\left( I(Y_i\geq t)-S(t,X_i)\right)^2}{\hat{G}(Y_i|X_i)} + \frac{1}{n}\sum_{i=1}^n \left \{ \frac{(1-\delta_i(t)) \mathcal{K}_{L_2,t}(Y_i,X_i,S(t,X_i))}{\hat{G}(Y_i|X_i)} - \int_0^{Y_i} \frac{\mathcal{K}_{L_2,t}(Y_i,X_i,S(t,X_i))d\hat{\Lambda}_G(u|X_i)}{\hat{G}(u|X_i)}\right \} ,$$ and $S^{\text{BJ-DL}}(t,X_i)$ minimizes the Buckley-James censoring unbiased loss $$\mathcal{L}^{\text{BJ}}(t) = \frac{1}{n}\sum_{i=1}^n \delta_i(t)\left( I(Y_i\geq t)-S(t,X_i)\right)^2 +\left( 1-\delta_i(t)\right) \mathcal{K}_{L_2,t}\left( C_i,X_i,S(t,X_i)\right),$$ where $\delta_i (t)$ is the event indicator at time $t$ for individual $i$, $G(u|X)$ is the conditional survival function for $C$, $\mathcal{K}_{L_2,t}(u,X_i,S(t,X_i)) = E\left[ \left( I(Y_i \geq t)-S(t,X_i)\right)^2|T\geq u, X_i\right]$ is the Brier risk, and $\hat{\Lambda}_G(u|X_i)$ is the conditional cumulative hazard fuction for $C$. We refer the reader to Steingrimsson and Morrison \cite{steingrimsson2020deep} for additional technical details. \subsubsection {Generalized additive proportional hazards model} In the absence of censoring, a flexible approach for outcome modeling and prediction is the generalized additive model (GAM).\cite{hastie1990generalized} This approach has also been extended to accommodate survival data. Specifically, the generalized additive proportional hazards model (GAPH) model \citep{hastie1990generalized} represents the hazard ratio function of the Cox proportional hazards model via a sum of smooth functions of covariates, and can be used to estimate the group-specific survival functions conditional on $X=x$. In our notation, the GAPH model is written as $\lambda(t|X)=\lambda_0 (t) \exp\left\{\eta(X)\right\},$ where $\eta(X) = \sum_{j=1}^p f_j(X_j)$ is the sum of smooth functions of each confounder $X_j$. Estimation of model functions $\eta$ proceeds by maximizing the log partial likelihood coupled with the second-order smoothness penalties for each function. In other words, the objective function is $$l^{\text{PL}}(f_1,\ldots,f_p) + \sum_{j=1}^p\lambda_j \int \{f_j^{''}(x)\}^2dx,$$ where $l^{\text{PH}}$ generically denote the log partial likelihood, and $\lambda_j$ is the regularization parameter (as $\lambda_j\rightarrow\infty$, $f_j(x)$ degenerates to the identity function). Similar to the DeepSurv, we can obtain the Nelson-Aalen estimate of the baseline CHF $\hat{\Lambda}_0(t)$ and compute the individual-specific survival curve by $$S^{\text{GAPH}} (t,X_i) = \exp \left \{ -\hat{\Lambda}_0(t) \exp\left[ \hat{\eta}(X_i) \right] \right \} .$$ \subsubsection{Parametric accelerated failure time model} A standard parametric model for analyzing survival data is the accelerated failure time (AFT) model. The parametric AFT model \cite{kalbfleisch2011statistical} postulates an explicit functional relationship between the covariates and the failure time $T$, $\log T = \mu +X^T\beta + \sigma W$, where $ \beta$ is a vector of coefficients describing the effects of covariates $X$ on the log transformed survival time, $\mu$ and $\sigma$ are intercept and scale parameters, respectively, $W$ is the error term, for which a variety of distributions can be assumed. In our simulations, we assume a standard extreme value distribution and a normal distribution, for which the survival time has a Weibull distribution and a log-normal distribution, respectively. The parameters can be estimated by maximizing the likelihood function for censored data, and are denoted by $\hat{\mu}, \hat{\beta}, \hat{\sigma}$. The individual-specific survival curve can then be calculated as $$S^{\text{AFT-Lognormal}}(t,X_i) = 1-\Phi\left(\frac{\log t-\hat{\mu} -X_i^T\hat{\beta}}{\hat{\sigma}}\right),$$ and $$S^{\text{AFT-Weibull}}(t,X_i) = \exp \left \{ -\exp\left( \frac{\log t-\hat{\mu} -X_i^T\hat{\beta}}{\hat{\sigma}} \right) \right \} .$$ A good review of parametric AFT model and the associated computational algorithms can be found in Wei. \cite{wei1992accelerated} \subsubsection {Cox proportional hazards model} A Cox proportional hazards model\cite{cox1972regression} relates the hazard function and the covariates $X$ through $\lambda(t|X)=\lambda_0 (t) \exp(X^T\gamma) $, where $\gamma$ is a vector of parameters describing the multiplicative effects of pre-treatment covariates on the hazard function. The model assumes that the hazard ratio is constant across the time span (the so-called proportional hazards assumption). The parameter $\gamma$ can be estimated by maximizing the partial likelihood. Similar to the procedure described for DeepSurv, we can obtain the Nelson-Aalen estimate of the baseline CHF $\hat{\Lambda}_0(t)$ and compute the individual-specific survival curve by $$S^{\text{CoxPH}} (t,X_i) = \exp \left \{ -\hat{\Lambda}_0(t) \exp\left( X_i^T\hat{\gamma} \right) \right \} .$$ Even though the Cox model includes a nonparametric specification of the baseline hazard, the performance of this approach critically depends on the parametric specification of the linear component $X_i^T\gamma$. When the true survival outcome surface involves complicated functional forms of the covariates, both the parametric AFT model and the Cox model may be subject to bias due to inaccurate model assumptions. We use these two conventional modeling techniques as a benchmark to quantify the bias that may occur in estimating the ISTE due to model misspecification. \section{Simulation Studies}\label{sec:simulations} \subsection{Simulation design} \label{sec:design} We carried out a series of simulation studies to compare the above methods for estimating the individual counterfactual survival curves and hence the ISTE in the context of observational studies. Throughout we considered two levels of total sample size: $n=500$ and $n=5000$, representing small and large studies. We simulated $p=10$ independent covariates, where $X_1,\ldots,X_5$ were drawn from the standard $N(0,1)$, and $X_6,\ldots,X_{10}$ from $\text{Bernoulli}(0.5)$. The treatment assignment was generated from $Z|X \sim \text{Bernoulli}(e(X))$, where the true propensity score follows $$\text{logit} \left \{ e(X)\right \} =\alpha_0+\alpha_1 X_1+\alpha_2 X_2+\alpha_3 X_3+\alpha_4 X_5+\alpha_5 X_6+\alpha_6 X_7+\alpha_7 X_9+\alpha_8 X_{10},$$ and $(\alpha_1,\alpha_2,\alpha_3,\alpha_4,\alpha_5,\alpha_6,\alpha_7,\alpha_8 )=(-0.1\psi,-0.9\psi,-0.3\psi,-0.1\psi,-0.2\psi,-0.4\psi,0.5\psi)$. We chose $\psi\in\{1,2.5,5\}$ to represent strong, moderate and weak levels of confounding, leading to strong, moderate and weak covariate overlap. \cite{hu2020estimation,hu2021estimation} The distribution of the true propensity scores is shown in Figure \ref{fig:overlap}. In particular, the degree of overlap determines the effective sample size for estimating population ATE, \cite{li2019addressing} but may have important implications for estimating ISTE. The intercept in the true propensity score model $\alpha_0$ was chosen such that the proportion of treated remained approximately $0.5$. \begin{figure}[htbp] \centering \includegraphics[width = 0.95\textwidth]{p_hist_combined.png} \caption{Distributions of true propensity scores generated from three treatment assignment mechanisms with an overall treatment prevalence equal to $0.5$. The un-shaded bars indicate the treated group; the gray shaded bars indicate the control group. Panels A–C correspond to setting $\psi = 1$, $\psi = 2.5$, and $\psi=5$ respectively.} \label{fig:overlap} \end{figure} We simulated the true counterfactual survival times $T$ from the Weibull distribution, \begin{equation} P(T(z)>t|X=x)=S(t|X=x,Z=z)=\exp\left[-\left \{ d_z \exp\left(m_z(x)t\right) \right \} ^\eta\right] ~~~~\forall z\in\{0,1\}, \end{equation} where $d_z$ is the treatment-group-specific parameter, $\eta$ is the shape parameter and $m_z(x)$ represents a generic functional form of covariates on survival time; specifications of these parameters will be discussed below. We considered the Weibull distribution because it has both the AFT and Cox proportional hazards representations, and therefore allows us to simulate scenarios where either one of these assumptions is valid. Using the inverse transform sampling, we generated counterfactual survival times by, \begin{equation*} T(z) = \left \{ \frac{-\log U}{d_z \exp \left[ m_z(X)\right]} \right \} ^{{1}/{\eta}}, \;\;\;\; \forall ~z \in\{0,1\}, \end{equation*} where $U \sim \text{Unif}(0,1)$ was a random variable following a uniform distribution on the unit interval $[0,1]$, $d_z=1200$ for $z=0$, and $d_z=2000$ for $z=1$, and $\eta$ was the shape parameter used to induce non-proportional hazards. We considered three structures for $m_z(X)$, leading to four treatment effect heterogeneity settings (HS) with increasing complexities: \begin{enumerate}[(i)] \item $m_1(X)=-0.2+0.1/(1+e^{-X_1})-0.8 \sin(X_3 )-0.1X_5^2-0.3X_6-0.2X_7$, and $m_0 (X)=0.2-0.5X_1-0.8X_3-1.8X_5-0.9X_6-0.1X_7$, \item $m_1(X)=-0.2+0.1/(1+e^{-X_1})-0.8 \sin(X_3 )-0.1X_5^2-0.3X_6-0.2X_7$, and $m_0 (X)=-0.1+0.1X_1^2-0.2 \sin(X_3 )+0.2/(1+e^{-X_5 } )+0.2X_6-0.3X_7$, \item $m_1 (X)=0.5-0.1/(1+e^{-X_2} )+0.1 \sin(X_3 )-0.1X_4^2+0.2X_4-0.1X_5^2-0.3X_6$, and $m_0 (X)=-0.1+0.1X_1^2-0.2 \sin(X_3 )+0.2/(1+e^{-X_5 } )+0.2X_6-0.3X_7$, \item $m_1 (X)=0.5-0.1/(1+e^{-X_2} )+0.1 \sin(X_3)-0.1X_4^2+0.2X_4-0.1X_5^2-0.3X_6$, and $m_0 (X)=-0.2+ 0.5\sin(\pi X_1 X_3 )+0.2/(1+e^{-X_5 } )+0.2X_6-0.3X_7$. \end{enumerate} Across all four outcome generating processes, $X_1, X_3, X_5, X_6, X_7$ were confounders that were related to both the treatment assignment and the potential survival outcome. In scenario (i), there is a nonlinear covariate effect only in the treated group. In scenario (ii), the nonlinear covariate effects are present in both treatment groups. Scenario (iii) is similar to scenario (ii) except that a non-overlapping set of covariates are included in the treated and control groups; this additional complexity represents an additional source of TEH. To avoid concerns that these settings may favor tree-based models, in scenario (iv), we further increased the data complexity by introducing a correlation of 0.6 between $X_2$ and $X_4$ in $m_1(X)$ and by including a nonadditive term $\sin(\pi X_1X_3)$ in $m_0(X)$. Finally, when simulating the counterfactual survival times, the parameter $\eta$ was set to be 2 to satisfy the proportional hazards assumption. To induce non-proportional hazards, $\eta$ was set to be $\exp\{0.7-1.8X_3+0.8X_7\}$ for $Z=0$, and $\exp\{0.9-0.5X_1+0.5X_2\}$ for $Z=1$. For simplicity, we generated the censoring time $C$ independently from an exponential distribution with rate parameters 0.007 and 0.02, corresponding to two levels of censoring rate (CR), 20\% and 60\%. In Section \ref{sec:censoring}, we additionally investigated the robustness of findings when censoring depends on observed covariates. An exploratory sensitivity analysis of the estimated ISTE to departure from the weak unconfoundeness assumption (A2) for all methods considered was conducted in Section~\ref{sec:UMC}. The simulated counterfactual survival curves are presented in Web Figure 1. \subsection{Implementation} We used the \code{abart} function from the R package \code {bart} with the default settings to implement AFT-BART-SP, and used the R package \code{AFTrees} to implement AFT-BART-NP. We used 1100 draws with the first 100 discarded as burn-in. \code{DeepSurv} was implemented in \textsf{Theano} with the Python package \code{Lasagne}. To fit RSF, we used the \code{randomForestSRC} R package with 1000 trees, \code{mtry = p/3} and a nodesize of 3. For the TSHEE method, we used the R code available at \url{https://github.com/EliotZhu/Targeted-Survival}. To implement DR-DL and BJ-DL, we used R codes provided at \url{https://github.com/jonsteingrimsson/CensoringDL}. The GAPH model was implemented using the \code{gam} function with $\code{family=cox.ph}$ from the ${\normalfont\textsf{R }}{}$ package $\code{mgcv}$. Super Leaner was implemented using the ${\normalfont\textsf{R }}{}$ package $\code{SuperLearner}$ to estimate the propensity score $\hat{e}_i$ for the method AFT-BART-NP-PS. Models in the Super Learner ensemble library included $\code{BART}$, $\code{GAM}$ and $\code{XGBoost}$. To facilitate the application of these state-of-the-art machine learning methods to estimate ISTE, we provide example code to replicate our simulation studies in the GitHub page of the first author \url{https://github.com/liangyuanhu/ML-DL-TEH}. \subsection{Performance metrics} We first assessed the overall precision in the estimation of heterogeneous effects (PEHE) for each method considered using $$\text{PEHE}=\sqrt{\frac{1}{n} \sum_{i=1}^n \left \{ \hat{\omega}^{q=1/2}(X_i) - \omega^{q=1/2}(X_i) \right \} ^2 },$$ where $\omega^{q=1/2}(X_i)=\theta^{q=1/2}(1,X_i)-\theta^{q=1/2}(0,X_i)$ is the difference between two counterfactual median survival times calculated from each data point, and $\hat{\omega}^{q=1/2}(X_i)$ is the estimated ISTE for individual $i$. This metric was also considered in Hill \cite{hill2011bayesian} and Dorie et al. \cite{dorie2019automated}, and a smaller value of PEHE indicates better accuracy and is considered favorable. For computational considerations, we replicated each of our simulations independently $B=250$ times for $n=5000$ and $B=1000$ times for $n=500$. We summarized the mean and standard deviation (SD) of the PEHE across $B$ replications. To further evaluate the operating characteristics of each method in recovering treatment effect within subpopulations, we subclassified the individuals into $\mathcal{G}=\{G_1,\ldots,G_K\}$ based on $K$ quantiles of the true propensity score distribution, and calculated relative bias and root mean squared error (RMSE) for each method. This strategy was firstly considered in Lu et al. \cite{lu2018estimating} in their simulations with non-censored outcomes, and adapted in our evaluation. We choose $K=50$ to represent a large enough number of subclasses with adequate resolution. By investigating the performance of each method in distinct covariate regions with different proportions of treatment assignment and overlap, we can assess the robustness of each method to data sparsity. More concretely, given an ISTE estimator $\hat{\omega}^{q=1/2}(X)$, we define the relative bias (or percent bias) in subclass $G_k$ by $$\text{RelBias}(k)= \frac{E\left \{ \hat{\omega}^{q=1/2}(X_i)-\omega^{q=1/2}(X_i)| X_i \in G_k \right \} }{E\left \{ \omega^{q=1/2}(X_i)| X_i \in G_k \right \} },~~k=1,\ldots,K.$$ While Lu et al.\cite{lu2018estimating} report the the bias of each estimator on its original scale, we assess the bias on the relative scale with respect to the true treatment effect (which is constant across different methods) so that the simulation results of different methods are more comparable even across different data generating processes. Under the same data generating process, however, the relative rankings of methods should be the same regardless of using the bias or relative bias, and the choice between these two metrics are immaterial. We also define the root mean squared error (RMSE) of an ISTE estimator for subclass $G_k$ as $$\text{RMSE}(k) = \sqrt{E\left \{ \left( \hat{\omega}^{q=1/2}(X_i)-\omega^{q=1/2}(X_i) \right)^2 {\, \vert \,} X_i \in G_k \right \} }, ~~~k =1, \ldots, K.$$ Finally, given the objective of ISTE estimation is often associated with informing individualized treatment rule (ITR), we also consider regret as a performance metric to better connect with the literature on ITR.\citep{logan2019decision} Specifically, the expected regret (or sometimes referred to as risk) in subclass $G_k$ is defined as $$\text{Regret}(k) = E \left \{ \left[ I\left( \hat{z}_{\text{opt}}(X_i) \neq z^*(X_i)\right) \times \vert {\omega}^{q=1/2} (X_i) \vert \right] {\, \vert \,} X_i \in G_k\right \} , k =1, \ldots, K, $$ where $\hat{z}_{\text{opt}}(X_i) =I\{\hat{\omega}^{q=1/2}(X_i)>0 \}$ is the recommended optimal ITR based on the estimated ISTE, $z^*(X_i) =I\{{\omega}^{q=1/2}(X_i)>0\}$ is the ``true'' (infeasible) optimal ITR given $X_i$. Similar concepts were also discussed in Manski,\cite{manski2004statistical} Hirano and Porter \cite{hirano2009asymptotics} and references therein. Intuitively, the expected regret is interpreted as the average treatment benefit loss due to incorrect treatment recommendation based on the estimated ISTE, and a smaller value indicates more precise treatment recommendations. To estimate these performance metrics, let $G_{k,b}$ contain individuals within the $q_k$ quantile of the true propensity score from replication $b$, and $N_{G_{k,b}}=\sum_{i=1}^n I(X_i\in G_{k,b})$ denote its size. We estimate the relative bias for subclass $G_k$ by $$\widehat{\text{RelBias}}(k) = \frac{\left \{ \frac{1}{B} \sum_{b=1}^B \frac{1}{N_{G_{k,b}}} \sum_{i=1}^n I(X_i\in G_{k,b})\left(\hat{\omega}^{q=1/2}_b(X_i) -\omega_b^{q=1/2}(X_i)\right) \right \} }{\left \{ \frac{1}{B} \sum_{b=1}^B \frac{1}{N_{G_{k,b}}} \sum_{i=1}^n I(X_i\in G_{k,b})\omega_b^{q=1/2}(X_i)\right \} },$$ where the true ISTE $\omega^{q=1/2}_b(X_i)$ is computed as the difference in the median survival times of two true counterfactual survival curves for each individual with covariate profile $X_i$ in the $b$th simulation iteration, and $\hat{\omega}^{q=1/2}_b(X_i)$ is the corresponding estimate based the $b$th simulated data set. The RMSE for subclass $G_k$ was estimated using $$\widehat{\text{RMSE}}(k) =\sqrt{\frac{1}{B}\sum_{b=1}^B \frac{1}{N_{G_{k,b}}} \sum_{i=1}^n I(X_i\in G_{k,b})\left(\hat{\omega}^{q=1/2}_b(X_i) -\omega^{q=1/2}_b(X_i)\right) ^2}.$$ Finally, the expected regret for subclass $G_k$ was estimated by $$\widehat{\text{Regret}}(k) = \frac{1}{B}\sum_{b=1}^B \frac{1}{N_{G_{k,b}}} \sum_{i=1}^n \left \{ I(X_i\in G_{k,b}) I\left( \hat{z}_{\text{opt}}(X_i) \neq z^*(X_i)\right)\vert {\omega}^{q=1/2} (X_i) \vert \right \} .$$Of note, while it is generally challenging to obtain valid confidence intervals for the ISTE using the frequentist machine learning methods directly from the model output, the Bayesian methods naturally produce coherent posterior credible intervals for the ISTE. Thereby, we summarized in Section \ref{sec:CP} the empirical coverage probability for two ``winners" of the AFT-BART methods. \section{Simulation Results}\label{sec:results} \subsection {Performance under strong overlap} A total of 12 methods were considered. We first evaluated the performance of each method without the challenge due to lack of overlap. Table \ref{tab:PEHE} summarizes, for sample size $n=5000$, the mean and standard deviation of PEHE under each configuration with strong covariate overlap (see Panel A in Figure \ref{fig:overlap}). Several patterns are immediate. First, all machine learning methods yielded substantially smaller PEHE than the parametric AFT and Cox regression models across all simulation scenarios. Second, with uncorrelated confounders and no interaction between confounders (HS(i)-(iii)), as the heterogeneity setting became more complex, machine learning methods tended to have better performance evidenced by decreasing mean and variation of the PEHE. When correlation and interaction between confounders were introduced in HS (iv), all machine learning methods but GAPH yielded similar results as for HS (ii), whereas GAPH had increased PEHE. In sharp contrast, parametric regression methods tended to perform worse, with increasing average PEHE as the heterogeneity setting became more complex. All methods show decreasing precision in estimating ISTE when the proportional hazards assumption fails to hold and under a higher censoring rate. The Cox proportional hazards model results in the largest increase in PEHE when the proportional hazards assumption is violated. In comparison, all machine learning estimators have a much smaller increase in PEHE under non-proportional hazards. This is possibly due to more complex data generating processes (the parameter $\eta$ depends on a nonlinear form of the covariates) and slightly reduced effective sample size. Third, among the nine machine learning approaches, AFT-BART-NP had the best overall performance across simulation configurations; AFT-BART-NP-PS had essentially the same PEHE results as AFT-BART-NP. Web Table 1 presents the PEHE for $n=500$. The findings are qualitatively similar except that the mean and variance of PEHE increase with a smaller sample size. \begin{table}[htbp] \centering \caption{Mean (and standard deviation) of PEHE for each of 12 methods and each of 8 simulation configurations for $n=5000$ with strong overlap. CR: censoring rate; HS: heterogeneity setting; AFT-L: AFT-Lognormal; AFT-W: AFT-Weibull; ABN: AFT-BART-NP; ABNPS:AFT-BART-NP-PS; ABS:AFT-BART-SP.} \begingroup \setlength{\tabcolsep}{4.2pt} \begin{tabular}{clcccccccccc} \toprule & & \multicolumn{4}{c}{Proportional hazards} && \multicolumn{4}{c}{Non-proportional hazards}\\ \cmidrule{3-6} \cmidrule{8-11} CR & Method & HS(i) & HS(ii) & HS(iii) &HS(iv) && HS(i) & HS(ii) & HS(iii) & HS(iv) \\ \midrule \multirow{10}{*}{20\%} & AFT-L & 3.63 (0.14) & 4.17 (0.15) &4.13 (0.14)&4.81 (0.15) && 3.79 (0.13)& 4.35 (0.16) &4.41 (0.17) &4.89 (0.18) \\ & AFT-W & 2.11 (0.12) & 2.58 (0.12) & 2.65 (0.12)&2.94 (0.13) && 2.31 (0.13) & 2.84 (0.13) & 2.81 (0.13)&3.08 (0.15)\\ & CoxPH & 2.16 (0.11)& 2.61 (0.12)& 2.61 (0.13) &2.98 (0.13)&& 3.81 (0.13) & 4.38 (0.14)& 4.39 (0.13)&4.86 (0.17)\\ & ABN & 0.51 (0.03)& 0.21 (0.02) &0.12 (0.02) &0.23 (0.03)&& 0.72 (0.07) & 0.41 (0.04) & 0.33 (0.04)&0.42 (0.05)\\ &ABNPS & 0.52 (0.03)& 0.22 (0.02)& 0.13 (0.02)&0.24 (0.03) && 0.73 (0.07)& 0.42 (0.04)&0.34 (0.04)&0.43 (0.05)\\ & ABS & 0.56 (0.04)& 0.24 (0.03)& 0.15 (0.02) &0.26 (0.03) && 0.78 (0.08) & 0.44 (0.05) & 0.36 (0.04)&0.45 (0.05)\\ & RSFs & 0.53 (0.03)& 0.22 (0.02) &0.13 (0.02)&0.24 (0.03) && 0.73 (0.07) & 0.42 (0.04) & 0.33 (0.04)&0.43 (0.05)\\ & DeepSurv & 0.62 (0.04) &0.29 (0.03)& 0.22 (0.03) &0.29 (0.04)&& 0.82 (0.08) & 0.47 (0.06) & 0.41 (0.05)&0.49 (0.06)\\ & DR-DL & 0.58 (0.04) &0.26 (0.02)& 0.16 (0.02)&0.27 (0.04) &&0.78 (0.07)& 0.44 (0.05) &0.36 (0.04)&0.45 (0.05)\\ &BJ-DL &0.57 (0.05)& 0.25 (0.02) &0.15 (0.02)&0.26 (0.04)&& 0.77 (0.07) &0.43 (0.05) &0.35 (0.04)&0.44 (0.05)\\ &TSHEE& 0.60 (0.04) &0.27 (0.03)& 0.20 (0.03)&0.26 (0.04) &&0.80 (0.08)& 0.46 (0.06) &0.40 (0.04)&0.48 (0.06)\\ &GAPH &0.60 (0.04) &0.28 (0.03) &0.20 (0.03)&0.36 (0.05)&&0.80 (0.07) &0.48 (0.05) &0.40 (0.04)&0.58 (0.07)\\ \midrule & & \multicolumn{4}{c}{Proportional hazards} && \multicolumn{4}{c}{Non-proportional hazards}\\ \cmidrule{3-6} \cmidrule{8-11} CR & Method & HS(i) & HS(ii) & HS(iii) &HS(iv) && HS(i) & HS(ii) & HS(iii) &HS(iv) \\ \midrule \multirow{10}{*}{60\%}& AFT-L & 4.14 (0.14) & 4.57 (0.15) & 4.45 (0.15)&5.19 (0.20) && 4.39 (0.18) & 4.89 (0.19) & 4.91 (0.18) & 5.88 (0.22) \\ & AFT-W & 2.62 (0.12) & 3.22 (0.13) & 3.14 (0.13) &4.01 (0.16)&& 2.89 (0.16) & 3.71 (0.14) & 3.72 (0.13) &4.66 (0.18) \\ & CoxPH & 2.63 (0.12) & 3.21 (0.13) & 3.22 (0.13) &3.89 (0.18)&& 4.41 (0.18) & 4.83 (0.18) & 4.83 (0.18)&5.93 (0.20) \\ & ABN & 0.81 (0.04) & 0.31 (0.04) & 0.21 (0.02) &0.31 (0.03)&& 0.99 (0.09) & 0.51 (0.06) & 0.41 (0.04)&0.50 (0.05) \\ &ABNPS &0.82 (0.04)& 0.32 (0.04) &0.22 (0.02)&0.32 (0.03) &&1.00 (0.09) &0.52 (0.06) &0.42 (0.04)&0.51 (0.05)\\ & ABS & 0.84 (0.04) & 0.34 (0.04) & 0.24 (0.02) &0.35 (0.03)&& 1.04 (0.09) & 0.56 (0.06) & 0.45 (0.04) &0.54 (0.05)\\ & RSFs & 0.82 (0.05) & 0.32 (0.05) & 0.22 (0.02)&0.33 (0.03) && 1.01 (0.09) & 0.52 (0.06) & 0.41 (0.04) & 0.52 (0.05)\\ & DeepSurv & 0.85 (0.04) & 0.38 (0.04) & 0.26 (0.03)&0.37 (0.04) && 1.09 (0.11) & 0.59 (0.07) & 0.51 (0.05) & 0.62 (0.06)\\ &DR-DL &0.84 (0.04)&0.35 (0.04) &0.24 (0.02)&0.40 (0.03)&& 1.04 (0.09) &0.55 (0.06) &0.45 (0.04)&0.56 (0.05)\\ &BJ-DL &0.83 (0.04)& 0.35 (0.04)& 0.23 (0.02)&0.38 (0.03)&& 1.03 (0.09)& 0.53 (0.06) &0.43 (0.04)&0.54 (0.05)\\ &TSHEE&0.85 (0.05) &0.37 (0.05)& 0.25 (0.03)&0.36 (0.04)&& 1.08 (0.10)& 0.57 (0.07)& 0.48 (0.05)&0.58 (0.06)\\ &GAPH&0.86 (0.04)&0.38 (0.04)&0.25 (0.02)&0.47 (0.05)&& 1.08 (0.09)& 0.58 (0.06)&0.48 (0.05)&0.69 (0.07)\\ \bottomrule \end{tabular} \endgroup \label{tab:PEHE} \end{table} The relative bias, RMSE and expected regret within the $K=50$ propensity score subclasses are summarized in Web Figure 2-7. The parametric AFT and Cox models had substantially larger bias, RMSE and regret compared to the class of machine learning methods across all scenarios; and even more so when the underlying model assumptions were violated. Specifically, the Cox model had the largest relative bias, RMSE and regret under the non-proportional hazards setting and AFT-Lognormal had the largest relative bias, RMSE and regret when the true outcomes were simulated from the Weibull curves. Among the machine learning methods, AFT-BART-NP and AFT-BART-NP-PS generally maintained the lowest bias, RMSE and regret with a larger sample size ($n=5000$) and under non-proportional hazards. AFT-BART-NP-PS, while producing the similar median values of the bias, RMSE and regret as AFT-BART-NP, had less variable performance measures demonstrated by the shorter length of boxplots of each metric. This efficiency improvement due to the inclusion of a propensity score estimate echoes the findings in Dorie et al.\cite{dorie2019automated} with non-censored outcomes. Overall, the tightness of the range of relative bias values for machine learning methods under the most complex HS (iii) and HS (iv) when $n=5000$ demonstrate their superior performance over the traditional parametric implementations. \subsection{Impact of covariate overlap} When there is strong covariate overlap, AFT-BART-NP demonstrates moderately better performance than AFT-BART-SP, RSF, DeepSurv, DR-DL, BJ-DL, TSHEE and GAPH. As the degree of covariate overlap decreases, we find that the advantage of AFT-BART-NP becomes more apparent. In addition, inclusion of the estimated propensity score in the AFT-BART-NP model considerably reduced the variability of all performance measures, regardless of degree of overlap. Figure \ref{fig:bias_rmse_regret_overlap} shows that for the most challenging scenario (HS (iv) + non-proportional hazards + 60\% censoring), the three performance measures (relative bias, RMSE and expected regret) increase as the lack of overlap increases for all machine learning methods, with both $n=500$ and $n=5000$. However, AFT-BART-NP and its variant AFT-BART-NP-PS appeared to be the most robust approach with the median relative bias around only 7\% in the most extreme scenario ($\psi=5$); DeepSurv appeared to have the largest increase in all performance metrics as the degree of overlap decreased. The two DL methods based on the censoring unbiased loss function, DR-DL and BJ-DL, showed similar performance across different simulation configurations, and performed better than the other DL method, DeepSurv, TSHEE as well as GAPH. AFT-BART-SP compared unfavorably with AFT-BART-NP, underscoring the benefit of more flexible nonparametric modeling of the residual term. \begin{figure}[htbp] \centering \includegraphics[width = 0.95\textwidth]{bias_rmse_regret_overlap_hs4.jpg} \caption{Relative bias (Panel A), RMSE (Panel B) and expected regret (Panel C) results for each of nine machine learning methods under strong, moderate and weak covariate overlap, and for the complex scenario of heterogeneous setting (iv), non-proportional hazards and 60\% censoring. Each boxplot visualizes the distribution of a performance measure across the propensity score subgroups $G_k$, $k=1,\ldots,50$.} \label{fig:bias_rmse_regret_overlap} \end{figure} \subsection{Overall performance assessment} In Figure \ref{fig:rmse_overall}, we provided an overall assessment of the machine learning methods across the simulation scenarios following the approach taken in Tabib et al. \cite{tabib2020non} Specifically, in each of the $B$ simulation iterations, we computed the percent increase in PEHE with respect to the best performer for this iteration. The percent increase in PEHE for method $s$ is given by $$\left(\frac{\text{PEHE}_s}{\text{PEHE}_{\min}}-1\right)\times 100,$$ where $\text{PEHE}_{\min}$ corresponds to the PEHE from the best performer (hence with the smallest PEHE). For a given iteration, only the best method will correspond to a percent increase of exact zero while the others lead to positive values. Figure \ref{fig:rmse_overall} presents the boxplots of percent increase in PEHE over all $3500$ simulations for $n=5000$ and $14000$ simulations for $n=500$ (Details of the scenarios covered are explained in the figure title). Evidently, the AFT-BART-NP method outperformed the other approaches (with AFT-BART-NP-PS slightly trailing behind) for having the smallest median and interquartile range of the percent increase in PEHE; the advantage of AFT-BART-NP and AFT-BART-NP-PS is much more pronounced for a larger sample size $n=5000$. \begin{figure}[htbp] \centering \includegraphics[width = 0.95\textwidth]{rmse_overall_revision.jpg} \caption{Overall comparison of nine machine learning methods across all simulation configurations. The boxplots represent the distribution of the percent increase in PEHE with respect to the best performer for each simulation run for all runs. Smaller values are better. The total number of simulation runs for each boxplot equals to the number of scenarios multiplied by $B$ ($B=250$ for $n=5000$ and $B=1000$ for $n=500$). There are a total of 18 scenarios considered, including (a) 2 proportional hazards assumptions $\times$ 2 censoring proportions $\times$ 4 heterogeneity settings under strong overlap; plus (b) 1 proportional hazards assumptions (non-proportional hazards) $\times$ 1 censoring proportions (CR$=60\%$) $\times$ 1 heterogeneity settings (HS (iv)) under moderate and weak overlap.} \label{fig:rmse_overall} \end{figure} \subsection{Frequentist coverage for AFT-BART-NP}\label{sec:CP} As we identified the AFT-BART-NP and its variant AFT-BART-NP-PS to be the ``best performer" in our simulations, we further assessed the accuracy of accodiated frequentist inference based on this flexible outcome model. An additional advantage of AFT-BART-NP is that it naturally produces coherent posterior intervals in contrast to other machine learning methods, for which it may be difficult to derive simple and valid interval estimates for ISTE. Table \ref{tab:CP} provides the mean frequentist coverage of the AFT-BART-NP credible interval estimators of the ISTE within the propensity score subclasses, under HS (iv), 60\% censoring rate and three different degrees of covariate overlap. In this most challenging HS scenario, when there is strong or moderate level of overlap, AFT-BART-NP leads to valid inference for ISTE because it generally provides close to nominal frequentist coverage across all subclasses for both sample sizes. Furthermore, under weak overlap for which it is challenging to correctly estimate or make valid inference even for the population average causal effects, \cite{li2019addressing} the AFT-BART-NP approach could still provide close to nominal frequentist coverage among the data region where treatment assignment is approximately balanced (e.g., the $25$th subclass where there is sufficient \emph{local overlap}). However, the coverage probability decreases as we move towards the tail regions of the propensity score distribution. This interesting finding on frequentist coverage echoes the previous findings for estimating the population level causal effect, but on a finer scale as we focused on individual-specific heterogeneous treatment effect. In addition, we find inclusion of the estimated propensity score in the AFT-BART model formulation further improved the mean freqentist coverage across all scenarios, and more considerably so near the tail regions of the propensity score distribution, i.e., in subclasses $G_k$'s away from $G_{25}$. A full summary of frequentist coverage across different scenarios is visualized in Web Figure 8 and conveys essentially the same message. \begin{table}[htbp] \centering \caption{Summary of average frequentist coverage probability of the Bayesian credible intervals from the AFT-BART-NP (denoted by $X$) and AFT-BART-NP-PS (denoted by $X+$ PS) for 5 propensity score subclasses, for each of two sample sizes, proportional and non-proportional hazards assumptions, and under varying degrees of overlap, in the scenario of HS (iv) and 60\% censoring. The subclasses $G_k=1$ and $G_k=50$ include units with the most extreme propensity scores, with the propensity scores closest to zero in $G_k=1$ and the propensity scores closest to one in $G_k=50$. The numbers in each cell represent the mean coverage of the ISTE for the corresponding subclass.} \begingroup \setlength{\tabcolsep}{3pt} \begin{tabular}{lcccccccccccccc} \toprule & & \multicolumn{6}{c}{Non-proportional hazards} && \multicolumn{6}{c}{Proportional hazards}\\ \cmidrule{3-8}\cmidrule{10-15} \multirow{3}{*}{Sample size} & \multirow{3}{*}{$G_k$} & \multicolumn{2}{c}{Strong} & \multicolumn{2}{c}{Moderate} &\multicolumn{2}{c}{Weak} && \multicolumn{2}{c}{Strong} & \multicolumn{2}{c}{Moderate} &\multicolumn{2}{c}{Weak} \\ & & \multicolumn{2}{c}{overlap} & \multicolumn{2}{c}{overlap} & \multicolumn{2}{c}{overlap} && \multicolumn{2}{c}{overlap} & \multicolumn{2}{c}{overlap} & \multicolumn{2}{c}{overlap} \\ \cmidrule{3-8}\cmidrule{10-15} & & $X$ & $X +$ PS & $X$ & $X +$ PS& $X$ & $X +$ PS& &$X$ & $X +$ PS& $X$ & $X +$ PS& $X$ & $X +$ PS\\ \midrule \multirow{5}{*}{$n=5000$} & 1 & 0.93&0.94& 0.90&0.90& 0.50 &0.55& &0.92&0.94& 0.91&0.92& 0.49&0.56\\ & 12 &0.92&0.94& 0.90&0.91& 0.70&0.75&& 0.92&0.93& 0.92&0.94& 0.68&0.77\\ &25& 0.94&0.95& 0.92&0.93& 0.92 &0.93&& 0.93&0.93& 0.92&0.94& 0.92&0.94\\ &37& 0.94&0.94& 0.90&0.92& 0.71 &0.75& &0.92&0.95& 0.91&0.93& 0.67&0.74\\ &50& 0.94&0.95& 0.90&0.91& 0.50 &0.56&& 0.91&0.94& 0.90&0.92& 0.50&0.57\\ \midrule \multirow{5}{*}{$n=500$} &1& 0.93&0.94& 0.86&0.90& 0.52&0.62&& 0.92&0.93& 0.89& 0.91& 0.52&0.58\\ & 12& 0.90&0.94& 0.90&0.90& 0.70&0.73&& 0.93&0.94& 0.90& 0.92&0.67&0.74\\ &25& 0.91&0.95& 0.91&0.92& 0.90&0.93&& 0.94&0.93& 0.92& 0.93& 0.90&0.93\\ &37& 0.90&0.94& 0.89&0.90& 0.70&0.77&& 0.92&0.94& 0.92& 0.93 &0.66&0.72\\ &50& 0.91&0.93& 0.86&0.87& 0.50&0.58&& 0.94&0.95& 0.87& 0.88& 0.50&0.57\\ \bottomrule \end{tabular} \endgroup \label{tab:CP} \end{table} \subsection{Sensitivity to covariate-dependent censoring} \label{sec:censoring} We assessed the sensitivity of our findings to more complex censoring mechanisms. Specifically, we replicated the simulation for the most challenging scenario (HS (iv) + non-proportional hazards) using the data generating process outlined in Section \ref{sec:design}, except that we generate the counterfactual censoring times $C(1)=C(0)$ from an exponential distribution with rate parameter $\rho(X)$, where \begin{equation*} \rho(X)=0.02+0.1X_1^2+0.1\sin{(X_3)}+0.2e^{X_5}/\lp1+e^{X_5}\right)+0.02X_6-0.03X_7. \end{equation*} The marginal censoring proportion implied by this model remains 60\%. Web Figure 9 presents the relative bias, RMSE and expected regret across all methods under strong, moderate and weak overlap, and with sample sizes $n=500$ and $n=5000$. The results appeared almost identical to those in Figure~\ref{fig:bias_rmse_regret_overlap}, and AFT-BART-NP and AFT-BART-NP-PS were still identified to be the best approaches in terms of bias and precision. Web Table 2 presents the mean frequentist coverage of the AFT-BART-NP and AFT-BART-NP-PS credible interval estimators of the ISTE within five propensity score subclasses, in parallel to Table~\ref{tab:CP}. The results confirm that the frequentist coverage probability of these approaches is unaffected by covariate-dependent censoring. \subsection{Sensitivity to unmeasured confounding} \label{sec:UMC} While the flexible machine learning approaches relaxed the parametric assumptions for outcome modeling, their validity for estimating ISTE using observational data still critically depends on the structural causal assumptions (A1)-(A4) in Section \ref{sec:setup}. Among them, a key structural assumption is the availability of pre-treatment confounders so that the weak unconfoundedness holds. To assess the sensitivity of the estimated ISTE to various degrees of departure from the weak unconfoundedness assumption, we conducted an \emph{exploratory} sensitivity analysis using our simulation structure. We generated potential survival outcomes under the heterogeneous setting (iii), in which all of the machine learning methods had relatively better performance compared to other heterogeneous settings. We sequentially increased the degree of unmeasured confounding by removing access to confounders 1) $X_3$, 2) $X_3 \text{ and } X_5$ and 3) $X_3, X_5 \text{ and } X_6$ in the analysis stage for each of the 12 methods. The PEHE results for $n=5000$ are provided in Table~\ref{tab:PEHE-SA}. Results for $n=500$ convey the same message and were therefore omitted. In the presence of unmeasured confounders, the performance of all methods deteriorated, demonstrated by the larger mean and standard deviation of the PEHE under increasing degree of unmeasured confounding. However, the relative performance rankings remain the same as in the situation when the weak unconfoundedness assumption holds, with AFT-BART-NP and AFT-BART-NP-PS being the top performing methods. Results on the relative bias, RMSE and expected regret are summarized in Web Figure 10--12, and further support the findings in Table~\ref{tab:PEHE-SA}. \begin{table}[htbp] \centering \caption{The mean (standard deviation) of PEHE for each of 12 methods. Data are generated under heterogeneous setting (iii) with $n=5000$ and strong overlap. $U$: unmeasured confounders; $U_1$: $X_3$ is the unmeasured confounder; $U_2$: $X_3$ and $X_5$ are the unmeasured confounders; $U_3$: $X_3$, $X_5$ and $X_6$ are the unmeasured confounders; CR: censoring rate; HS: heterogeneity setting; AFT-L: AFT-Lognormal; AFT-W: AFT-Weibull; ABN: AFT-BART-NP; ABNPS:AFT-BART-NP-PS; ABS:AFT-BART-SP.} \begingroup \setlength{\tabcolsep}{4.2pt} \begin{tabular}{clcccccccccc}\\ \toprule & & \multicolumn{4}{c}{Proportional hazards} && \multicolumn{4}{c}{Non-proportional hazards}\\ \cmidrule{3-6} \cmidrule{8-11} CR & & No $U$ & $U_1$ & $U_2$ &$U_3$ & & No $U$& $U_1$ & $U_2$ &$U_3$\\ \midrule \multirow{10}{*}{20\%}& AFT-L & 4.13 (0.14) & 5.03 (0.16) & 5.82 (0.19) & 6.52 (0.19) && 4.41 (0.17) & 5.16 (0.20) & 5.77 (0.20) & 6.47 (0.20) \\& AFT-W & 2.65 (0.12) & 3.13 (0.14) & 3.73 (0.14) & 4.43 (0.14) && 2.81 (0.13) & 3.35 (0.16) & 4.03 (0.16) & 4.71 (0.16) \\& CoxPH & 2.61 (0.13) & 3.03 (0.14) & 3.63 (0.14) & 4.33 (0.14) && 4.39 (0.13) & 5.09 (0.20) & 5.78 (0.20) & 6.48 (0.20) \\& ABN & 0.12 (0.02) & 0.31 (0.04) & 0.46 (0.04) & 0.66 (0.04) && 0.33 (0.04) & 0.50 (0.06) & 0.65 (0.06) & 0.85 (0.06) \\ & ABNPS & 0.13 (0.02) & 0.32 (0.04) & 0.47 (0.04) & 0.67 (0.04) && 0.34 (0.04) & 0.51 (0.06) & 0.66 (0.06) & 0.86 (0.06) \\& ABS & 0.15 (0.02) & 0.35 (0.04) & 0.50 (0.04) & 0.70 (0.04) && 0.36 (0.04) & 0.53 (0.06) & 0.68 (0.06) & 0.88 (0.06) \\& RSFs & 0.13 (0.02) & 0.32 (0.04) & 0.47 (0.04) & 0.67 (0.04) && 0.33 (0.04) & 0.51 (0.06) & 0.66 (0.06) & 0.86 (0.06) \\& DeepSurv & 0.22 (0.03) & 0.38 (0.05) & 0.53 (0.05) & 0.73 (0.05) && 0.41 (0.05) & 0.58 (0.07) & 0.73 (0.07) & 0.93 (0.07) \\& DR-DL & 0.16 (0.02) & 0.35 (0.04) & 0.50 (0.04) & 0.70 (0.04) && 0.36 (0.04) & 0.53 (0.06) & 0.68 (0.06) & 0.88 (0.06) \\& BJ-DL & 0.15 (0.02) & 0.34 (0.04) & 0.49 (0.04) & 0.69 (0.04) && 0.35 (0.04) & 0.53 (0.06) & 0.68 (0.06) & 0.88 (0.06) \\& TSHEE & 0.20 (0.03) & 0.37 (0.05) & 0.52 (0.05) & 0.72 (0.05) && 0.40 (0.04) & 0.57 (0.07) & 0.72 (0.07) & 0.92 (0.07) \\& GAPH & 0.20 (0.03) & 0.37 (0.05) & 0.52 (0.05) & 0.72 (0.05) && 0.40 (0.04) & 0.57 (0.07) & 0.72 (0.07) & 0.92 (0.07) \\ \midrule & & \multicolumn{4}{c}{Proportional hazards} && \multicolumn{4}{c}{Non-proportional hazards}\\ \cmidrule{3-6} \cmidrule{8-11} CR & & No $U$ & $U_1$ & $U_2$ &$U_3$ & & No $U$& $U_1$ & $U_2$ &$U_3$\\ \midrule \multirow{10}{*}{60\%}& AFT-L & 4.45 (0.15) & 5.33 (0.20) & 6.04 (0.22) & 6.78 (0.25) && 4.91 (0.18) & 5.99 (0.22) & 6.56 (0.22) & 7.27 (0.22) \\& AFT-W & 3.14 (0.13) & 4.22 (0.16) & 4.93 (0.19) & 5.66 (0.22) && 3.72 (0.13) & 4.75 (0.18) & 5.45 (0.18) & 6.05 (0.18) \\& Cox PH & 3.22 (0.13) & 3.94 (0.18) & 4.52 (0.20) & 5.13 (0.22) && 4.83 (0.18) & 6.02 (0.20) & 6.64 (0.20) & 7.24 (0.20) \\& ABN & 0.21 (0.02) & 0.34 (0.03) & 0.49 (0.04) & 0.69 (0.05) && 0.41 (0.04) & 0.56 (0.05) & 0.71 (0.05) & 0.92 (0.05) \\& ABNPS & 0.22 (0.02) & 0.35 (0.03) & 0.50 (0.04) & 0.70 (0.05) && 0.42 (0.04) & 0.57 (0.05) & 0.73 (0.05) & 0.93 (0.05) \\& ABS & 0.24 (0.02) & 0.38 (0.03) & 0.52 (0.04) & 0.72 (0.05) && 0.45 (0.04) & 0.59 (0.05) & 0.73 (0.05) & 0.94 (0.05) \\& RSFs & 0.22 (0.02) & 0.36 (0.03) & 0.51 (0.04) & 0.71 (0.05) && 0.41 (0.04) & 0.60 (0.05) & 0.75 (0.05) & 0.94 (0.05) \\& DeepSurv & 0.26 (0.03) & 0.40 (0.04) & 0.55 (0.05) & 0.75 (0.06) && 0.51 (0.05) & 0.68 (0.06) & 0.83 (0.06) & 1.02 (0.06) \\& DR-DL & 0.24 (0.02) & 0.44 (0.03) & 0.59 (0.04) & 0.79 (0.05) && 0.45 (0.04) & 0.65 (0.05) & 0.80 (0.05) & 1.00 (0.05) \\& BJ-DL & 0.23 (0.02) & 0.42 (0.03) & 0.56 (0.04) & 0.76 (0.05) && 0.43 (0.04) & 0.64 (0.05) & 0.79 (0.05) & 0.99 (0.05) \\& TSHEE & 0.25 (0.02) & 0.41 (0.04) & 0.56 (0.05) & 0.77 (0.06) && 0.48 (0.05) & 0.67 (0.06) & 0.82 (0.06) & 1.02 (0.06) \\& GAPH & 0.25 (0.02) & 0.41 (0.04) & 0.56 (0.05) & 0.77 (0.06) && 0.48 (0.05) & 0.67 (0.06) & 0.82 (0.06) & 1.02 (0.06) \\ \bottomrule \end{tabular} \endgroup \label{tab:PEHE-SA} \end{table} \section{CASE STUDY: Estimating HETEROGENEOUS SURVIVAL Causal EFFECT OF TWO RADIOTHERAPY APPROACHES FOR patients with HIGH-RISK PROSTATE CANCER}\label{sec:example} Two popular radiotherapy based approaches for treating high-risk localized prostate cancer are EBRT+AD and EBRT+brachy$\pm$AD. \cite{ennis2018brachytherapy} It is unclear whether EBRT+AD and EBRT+brachy$\pm$AD have significantly different survival effect among those who received at least 7920 cGY EBRT dose, and whether there exists TEH. To better understand the comparative overall and heterogeneous survival causal effects of these two radiotherapy approaches, we pursued a two-stage causal analysis with the NCDB data including 7730 high-risk localized prostate cancer patients who were diagnosed between 2004 and 2013 and were treated with either EBRT+AD or EBRT+brachy$\pm$AD with no less than 7920 cGY EBRT dose. The pre-treatment confounders included in this analysis were age, prostate-specific antigen (PSA), clinical T stage, Charlson-Deyo score, biopsy Gleason score, year of diagnosis, insurance status, median income level (quartiles on the basis of zip code of residence), education (based on the proportion of residents in the patient's zip code who did not graduate high school), race, and ethnicity. Web Table 3 summarizes the baseline characteristics of patients in the two treatment groups. Clearly, there are a number of covariates that are unbalanced between the two groups, suggesting the need to adjust for confounding. Web Figure 13 shows the distribution of the estimated propensity scores by fitting a Super Learner\cite{pirracchio2015improving} on the treatment and covariates data. Relatively strong covariate overlap is suggested from the propensity score distribution. \begin{comment} \begin{table}[htbp] \centering \caption{Baseline characteristics of patients treated with EBRT plus AD versus EBRT plus brachytherapy with or without AD. EBRT = external beam radiotherapy. AD = androgen deprivation. SD = standard deviation.} \begin{tabular}{lcccc} \hline & Overall & EBRT+AD & EBRT+brachy$\pm$AD & $p$ \\ Variables & (n = 7330) & (n = 5430) & (n = 1900)& \\ \hline Race ($\%$) & & & & 0.122\\ \;\; White & 5746 (78.4)& 4245 (78.2)& 1501 (79.0)& \\ \;\; Black& 1327 (18.1)& 1005 (18.5)& 322 (16.9)&\\ \;\; Other& 257 (3.5)& 180 (3.3)& 77 (4.1)&\\ Spanish or Hispanic Origin ($\%$) & & & & 0.684\\ \;\; Non-Spanish; non-Hispanic& 6997 (95.5)& 5187 (95.5)& 1810 (95.3) &\\ \;\; Spanish or Hispanic& 333 (4.5)& 243 (4.5)& 90 (4.7) &\\ Insurance ($\%$) & & & & 0.003\\ \;\; No& 152 (2.1)& 129 (2.4)& 23 (1.2)& \\ \;\; Yes &7178 (97.9)& 5301 (97.6)& 1879 (98.8) &\\ Income ($\%$) & & & & $<$0.001\\ \;\; $<$\$30,000& 956 (13.0)& 710 (13.1)& 246 (12.9) &\\ \;\; \$30,000 - \$34,999& 1304 (17.8)& 979 (18.0)& 325 (17.1)& \\ \;\; \$35,000 - \$45,999& 2026 (27.6)& 1586 (29.2)& 440 (23.2)& \\ \;\; $>$\$46,000 & 3044 (41.5) &2155 (39.7)& 889 (46.8) &\\ Education$^\dagger$ ($\%$)& & & & $<$0.001\\ \;\; $<$14\%& 2692 (36.7) &1894 (34.9)& 798 (42.0) &\\ \;\; 14\%-19.9\% &1801 (24.6) &1368 (25.2)&433 (22.8) &\\ \;\; 20\% - 28.9\%& 1728 (23.6)& 1336 (24.6) &392 (20.6) &\\ \;\; $\geq$29\% & 1109 (15.1)& 832 (15.3) &277 (14.6) &\\ Charlson comorbidity index ($\%$) & & & & 0.41\\ \;\; 0& 6187 (84.4)& 4576 (84.3)& 1611 (84.8) &\\ \;\; 1$^\ddagger$ &925 (12.6)& 684 (12.6)& 241 (12.7) &\\ \;\; $>$1$^\S$ &218 (3.0)& 170 (3.1)& 48 (2.5)& \\ Clinical T Stage ($\%$) & & & & 0.267\\ \;\; $\leq$cT2& 6103 (83.3) &4505 (83.0)& 1688 (84.1) &\\ \;\; $\geq$cT3& 1227 (16.7)& 925 (17.0)& 302 (15.9) &\\ Year of Diagnosis ($\%$) & & & & $<$0.001\\ \;\; 2004-2007& 54 (0.7)& 25 (0.5)& 29 (1.5)& \\ \;\; 2008-2010& 1728 (23.6)& 1132 (20.8)& 596 (31.4) &\\ \;\; 2010-2013& 5548 (75.7) &4273 (78.7)& 1275 (67.1) &\\ Age (mean [SD])& 68.9 (8.2)& 69.5 (8.2)& 67.2 (7.8)& $<$0.001\\ PSA (ng/mL) (mean [SD]) &20.9 (22.7) & 21.7 (23.4)& 18.5 (20.4)& $<$0.001\\ Gleason score & & & & $<$0.001\\ \;\; 6& 256 (3.5)& 163 (3.0)& 93 (4.9)& \\ \;\; 7& 1282 (17.5) &930 (17.1)& 352 (18.5) &\\ \;\; 8& 3170 (43.2)& 2336 (43.0) &834 (43.9) &\\ \;\; 9& 2388 (32.6) &1816 (33.4)& 572 (30.1)& \\ \;\; 10& 234 (3.2)& 185 (3.4)& 49 (2.6) &\\ \hline \multicolumn{5}{l}{\footnotesize{$^\dagger$: Percentage of adults in the patient's zip code who did not graduate from high school.}} \\ \multicolumn{5}{l}{\footnotesize{$^\ddagger$: Myocardial Infarction, Congestive Heart Failure, Peripheral Vascular Disease, Cerebrovascular Disease, Dementia, Chronic Pulmonary Disease, Rheumatologic Disease,}}\\ \multicolumn{5}{l}{\footnotesize{\;\;\;\;Peptic Ulcer Disease, Mild Liver Disease, Diabetes.}}\\ \multicolumn{5}{l}{\footnotesize{$^\S$: Diabetes with Chronic Complications, Hemiplegia or Paraplegia, Renal Disease.}} \end{tabular} \label{tab:NCDB-base} \end{table} \end{comment} \begin{comment} \begin{table}[htbp] \centering \caption{Understanding heterogeneous survival effects (based on median survival) of EBRT plus brachytherapy with or without androgen deprivation (EBRT+brachy$\pm$AD) versus EBRT plus androgen deprivation (EBRT+AD) using linear regression with dependent variable being the MCMC samples of ISTE from the AFT-BART-NP model.} \begin{tabular}{lrr} \toprule & Coefficient estimate & 95\% Credible Interval \\ \midrule Intercept& 5.93& (--3.82, 7.73)\\ Race (reference = White) && \\ \;\; Black& 0.13& (--0.14, 0.41)\\ \;\; Other & 0.41& (--0.19, 1.01)\\ Spanish or Hispanic Origin (Yes vs. No)& 0.20& (--0.35, 0.75)\\ Insurance (Yes vs. No)& --0.43& (--1.18, 0.31)\\ Education$^\dagger$ (reference = $<$14\%)&& \\ \;\; 14\% -- 19.9\%& 0.15& (--0.14, 0.44)\\ \;\; 20\% -- 28.9\%& 0.26& (--0.03, 0.55)\\ \;\; $\geq$29\% & 0.32& (--0.01, 0.65)\\ Charlson comorbidity index (\%) \\ \;\; $1^\ddagger$ vs. 0& --0.07& (--0.39, 0.25)\\ \;\; $>1^\S$ vs. 0& --0.31& (--0.94, 0.32)\\ Clinical T Stage (\%) &&\\ \;\; $\leq$cT2 vs. $\geq$ cT3 & --0.21& (--0.49, 0.08)\\ Year of Diagnosis (\%) && \\ \;\; 2008--2010 vs. 2004--2007& --0.61& (--1.78, 0.27)\\ \;\; 2010--2013 vs. 2004--2007& --0.62& (--1.65, 0.42)\\ Age (mean [SD])&--0.63& (--0.77, --0.50)\\ PSA (ng/mL) (mean [SD])& 3.95& (3.50, 4.41)\\ Gleason score \\ \;\; 7 vs. 6& --0.29& (--0.90, 0.30)\\ \;\; 8 vs. 6& --0.39& (--1.00, 0.21)\\ \;\; 9 vs. 6& --0.49& (--1.09, 0.11)\\ \;\; 10 vs. 6& --0.59& (--1.19, 0.10)\\ Income (reference = $<$ \$30,000)&& \\ \;\; \$30,000 -- \$34,999& 0.12& (--0.28, --0.51)\\ \;\; \$35,000 -- \$45,999& --0.07& (--0.44, --0.29)\\ \;\; $>$\$46,000 & --0.11& (--0.45, 0.23)\\ \bottomrule \end{tabular} \begin{tablenotes} \item \footnotesize{$^\dagger$: Percentage of adults in the patient's zip code who did not graduate from high school.} \item \footnotesize{$^\ddagger$: Myocardial Infarction, Congestive Heart Failure, Peripheral Vascular Disease, Cerebrovascular Disease, Dementia, Chronic Pulmonary Disease, Rheumatologic Disease, Peptic Ulcer Disease, Mild Liver Disease, Diabetes.} \item \footnotesize{$^\S$: Diabetes with Chronic Complications, Hemiplegia or Paraplegia, Renal Disease.} \end{tablenotes} \label{tab:NCDB-LR} \end{table} \end{comment} Our analyses proceed in a two-stage fashion. In the first stage, we applied the machine learning methods to estimate the ISTE within the the counterfactual framework. The estimated ISTE were then used, in the second stage, as dependent variables in an exploratory linear regression analysis to generate some further insights. As argued in Lu et al.,\cite{lu2018estimating} the estimated regression coefficients can be interpreted as how treatment effects are modulated by corresponding covariates. To estimate standard errors and uncertainty intervals for the regression coefficients, we drew for each individual $1000$ posterior MCMC samples of ISTE from the AFT-BART models. For the frequentist machine learning approaches (RSF, DeepSurv, TSHEE, DR-DL and BJ-DL), we subsampled the entire procedure to obtain uncertainty intervals for the linear regression coefficients. Specifically, we drew a sample of size $n/5$ without replacement, refit each model based on the subsampled data and used the resulting ISTE estimates as dependent variable in the exploratory linear regression. The subsampling process was repeated 1000 times. Similar to Politis et al. \cite{politis1999subsampling} and Lu et al.,\cite{lu2018estimating} we used the subsampling approach instead of bootstrap due to considerations on computational speed and robustness. Web Table 4 presents the regression coefficients and $95\%$ credible intervals for all covariates and the intercept from the AFT-BART-NP-PS model; the intercept could be considered as an overall measure of the treatment effect for the ``baseline" population (with all covariates set to be the reference category or mean value). Results from using ISTE estimated by frequentist machine learning approaches were similar and therefore omitted. The intercept estimates suggest that the population average survival treatment effect effect of EBRT+brachy$\pm$AD versus EBRT+AD is not statistically significant at the 0.05 level. However, PSA and age significantly modulated the comparative effect of the two radiotherapy approaches on median survival. For example, the estimated coefficient was 3.99 (95\% CI: $3.60 - 4.38$) for PSA; this means that difference in the counterfactual median survival under EBRT+brachy$\pm$AD versus EBRT+AD, which was positive, became greater for patients with higher PSA. Similarly, the negative coefficient estimate for age suggests that the median survival benefit from EBRT+brachy$\pm$AD were more pronounced among younger patients. In Figure \ref{fig:p_scatter}, we created $300$ subgroups based on percentiles of the distribution of posterior mean ISTE, and provide the scatter plots of subgroup-specific average covariate (PSA, age, clinical T stage and insurance status) versus subgroup-specific average survival treatment effect. While the subgroup survival treatment effect estimates are randomly scattered across values of clinical T stage and insurance status, there is a clear non-random pattern between subgroup-specific survival treatment effect estimates and PSA or age, with directions in close agreement to findings from the exploratory linear regression analysis (Web Table 4). \begin{figure}[htbp] \centering \includegraphics[width = 0.8\textwidth]{p_scatter_combined} \caption{Visualization of results from the NCDB data analysis. Covariates considered are PSA, age, clinical T stage, and insurance status. The x-axis represents the subgroup-specific posterior average survival treatment effect (median counterfactual survival in months), and the y-axis represents the subgroup-specific average value of the covariate. A red dot represents a subgroup, generated by dividing percentiles of the distribution of posterior mean individual survival treatment effects (ISTE). There are $300$ subgroups in total. Gray dots represent a random subset of $100$ (out of $1000$) posterior draws of the ISTE with the sub-grouping process applied.} \label{fig:p_scatter} \end{figure} To further explore the subgroups that may have enhanced survival treatment effect from either of the two radiotherapy approaches, we leveraged the posterior MCMC draws of the ISTE from AFT-BART-NP, and employed the ``fit-the-fit" strategy to explore the potential TEH in relation to the covariate subspaces. The ``fit-the-fit" strategy has been used to identify possible subgroups defined by combination rules of covariates that have differential treatment effects; see for example, Foster et al.\cite{foster2011subgroup} and Logan et al.\cite{logan2019decision} Instead of a linear regression analysis, the classification and regression tree (CART) model was used to regress the posterior mean of the ISTE on the covariates. A sequence of CART models were fit, where covariates were sequentially added to the CART model in a stepwise manner to improve the model fit, as measured by $R^2$. At each step, the variable leading to the largest $R^2$ improvement was selected into the model and the procedure ended until the percent improvement in $R^2$ was less than 1\%. This complexity parameter controls the size of the final CART tree. Subgroup treatment effects were estimated by averaging the ISTE among individuals falling into each node of the final CART model, and the branch decision rules (i.e., binary splits of the covariate space) suggested combination rules of covariates. Figure \ref{fig:fit-the-fit} shows the results of the final tree estimates. The final $R^2$ between the tree fit and the posterior mean treatment effect of EBRT+brachy$\pm$AD versus EBRT+AD was 80\%. The first splitting variable was PSA. Patients with PSA $\geq 10$ ng/ml had approximately 7.6 (95\% CI: 0.6--14.5) months longer median survival with EBRT+brachy$\pm$AD, while patients with PSA $<10$ ng/ml did not experience significantly higher median survival from either treatment. A second level of variable splitting provided further resolution on the magnitude of the treatment benefit for patients with higher PSA $\geq 10$ ng/ml; the most beneficial subgroup was those with PSA $\geq 25$ ng/ml and had approximately 10.9 months longer median survival. Among patients with lower PSA $<10$ ng/ml, older patients aged above 70 experienced treatment benefit from EBRT +AD with median survival approximately 2.2 months longer; on the contrary, younger patients aged below 70 could benefit from EBRT+brachy$\pm$AD with approximately 4.6 months longer median survival. This alternative analysis strategy generated evidence that converged to the exploratory linear regression analysis on the ISTE estimates, and suggested interpretable patient subpopulations with beneficial survival treatment effects due to EBRT+brachy$\pm$AD. We further explored the sensitivity of the summarizing CART model fit to the tuning parameters of both CART and AFT-BART-NP. When the complexity parameter value of CART ranges from 0.6\% to 1.1\%, the final tree remains the same. With a value $>1.1\%$, the final summarizing tree includes only PSA and the final $R^2$ drops to 0.67. When the complexity parameter value is $<0.6\%$, the final summarizing tree gets more complex by including an additional variable biopsy Gleason score with only a slight increase (0.005) in the final $R^2$. Varying values for the hyperparameters of the AFT-BART-NP model did not change the results of the CART model fit. Hence, the summarizing CART model fit in this case study is robust to the tuning parameters. \begin{figure}[htbp] \centering \includegraphics[width = 0.8\textwidth]{fit_the_fit_tree} \caption{Final CART model fit to the posterior mean of the individual survival treatment effect (measured by median survival in months) comparing EBRT plus brachytherapy with or without AD (EBRT+brachy$\pm$AD) versus EBRT plus AD (EBRT+AD). Values in each node correspond to the posterior mean and 95\% credible intervals for the average survival treatment effect for the subgroup of individuals represented in that node.} \label{fig:fit-the-fit} \end{figure} \section{DISCUSSION}\label{sec:discussion} Identification of TEH has been conventionally carried out by first enumerating potential effect modifiers with subject-matter experts and then estimating the average treatment effect within each subgroup.\cite{kent2020predictive,wang2007statistics} In randomized clinical trials, this approach could also facilitate pre-specification and therefore is particularly suitable to \emph{confirmatory TEH analysis}.\cite{kent2020predictive} In observational data with complex heterogeneity of treatment effect, such \emph{a priori} specification that separates the issues of confounding and TEH is often practically infeasible, especially with a large number of pre-treatment covariates. Such complications motivate \emph{exploratory TEH analysis} for generating scientifically meaningful hypotheses and treatment effect discovery, which is the focus of this current paper.\cite{kent2020predictive,assmann2000subgroup,wang2007statistics} Exploiting on the counterfactual framework, flexibly modeling of the outcome has been shown to be well-suited for exploratory TEH analysis. However, ongoing discussions about causal methods for estimating TEH in observation data have largely focused on non-survival data. For example, tree-based methods such as BART and random forests have recently emerged as popular approaches to causal effect estimation for continuous or binary outcomes.\cite{lu2018estimating,hill2011bayesian} On the other hand, several modern deep learning methods (DeepSurv, DR-DL, BJ-DL) have been developed for censored survival data \citep{katzman2018deepsurv,steingrimsson2020deep}, and a TMLE based method has recently been proposed to estimate the survival heterogeneous effect. \citep{zhu2020targeted} The GAPH model is adept at flexibly fitting complex main effects, which are often of great interest in health studies.\citep{hastie1990generalized} We adapt these machine learning modeling tools for estimating ISTE and provide new empirical evidence using simulations representative of complex confounding and heterogeneity settings with right-censored survival data. Our results indicate that all machine learning methods substantially outperformed the traditional AFT and Cox proportional hazards models in estimating TEH. This is not surprising given that the traditional models often encode strong parametric and linearity assumptions, which are prone to bias when model assumptions fail to hold. Among the class of machine learning methods, the nonparametric version of the AFT-BART model \cite{henderson2020individualized} generally outperformed the other methods, both from the traditional prediction perspective (bias and RMSE) and the decision perspective (expected regret). The advantage of AFT-BART-NP becomes more pronounced with a larger sample size and increased data complexity. On the other hand, AFT-BART-NP also conveniently enables posterior inference by providing credible intervals for ISTE and the associated subgroup-specific treatment effects. In particular, we demonstrated that when there is strong or moderate overlap, AFT-BART-NP could provide close to nominal frequentist coverage for almost all average causal effect among subpopulations defined by propensity score strata. Under weak overlap, AFT-BART-NP still provides satisfactory frequentist coverage for the subpopulation near the centroid of the propensity score distribution. While the overall population may exhibit weak overlap, the central region of the propensity score distribution may still present satisfying \emph{local overlap} and in fact admits valid inference for the causal effects. However, AFT-BART-NP could understate the uncertainty of ISTE estimates in regions with lack of overlap. This observation was also discussed in an invited Commentary to Hahn et al.\cite{hahn2020bayesian} by Papadogeorgou and Li,\cite{Papadogeorgou2020BA} who illustrated that BART for continuous outcomes produced overly narrow confidence band in the region of poor overlap. As a potential improvement, we found that including a non-parametrically estimated propensity score in the AFT-BART-NP model formulation leads to more accurate estimation and inference for ISTE, evidenced by less variable subgroup-specific performance measures, as well as higher frequentist coverage under weak overlap. Because previous simulations for TEH rarely considered the effect of overlap, our results offer new insights. Importantly, our findings can provide new perspectives into the estimation of ISTE relative to average treatment effects. At the minimum, we noticed that even though it is challenging to estimate ISTE for units at the tails of the propensity score distribution, it remains practically feasible to make accurate inference for ISTE within the centroid of the propensity score distribution. In fact, the centroid region of the propensity score distribution includes individuals at clinical equipoise (and for whom the treatment decisions are mostly unclear) and resemble those recruited in a randomized controlled trial. In the propensity score literature, this subpopulation is sometimes referred to as the \emph{overlap population}, for which there exists an efficient weighting estimator for the average causal effect. \cite{li2018balancing,li2019addressing,li2019propensity,li2020comment} In general, the flexible outcome modeling represents a simple and powerful approach for causal effect estimation, with the caveat that accurate estimation critically depends on correct model specification of the outcome surface. \cite{antonelli2019discussion} With the rapid advancement of machine learning techniques, more precise modeling of the outcome surface can be achieved, which can serve as the building block for improved individualized causal effect estimation. The ISTE estimates can also be utilized to explore the degree of TEH. For example, as in the second stage of the virtual twins approach, the ISTE estimates were used as the outcome and a tree diagram was fitted to identify predictors that explain away differences in the ISTE estimates. In Lu et al.,\cite{lu2018estimating} the ISTE estimates were used as the dependent variable in a standard regression model to explain between-subgroup differences in treatment effect. As suggested in Anoke et al.,\cite{anoke2019approaches} averaging ISTE estimates within a pre-specified subgroup (e.g., female vs. male) can also facilitate exploration of the TEH. Given these existing tools, the ISTE from a flexible outcome model can yield insights not only for the population average treatment effect but also for the detection of TEH. Another interesting practical point regards how to use the estimated ISTE to inform treatment decisions for future patients when only part of the covariates $X^{\text{obs}}$ will be available at the decision time, and $X^{\text{mis}}$ will not be collected. In such situations, a plausible strategy is to marginalize the product of the ISTE functional $f(\omega \mid x)$ and the conditional distribution $f(x^{\text{mis}} \mid x^{\text{obs}})$, over the probability distribution of $X^\text{mis}$. However, the estimation of the conditional $f(x^{\text{mis}} \mid x^{\text{obs}})$ can be computationally challenging, especially when there are a large number of covariates. In the NCDB case study, we showed how the counterfactual ISTE estimates from machine learning models could be utilized to understand whether there might be TEH among localized high-risk prostate cancer patients who were treated with two different radiotherapy approaches. These two radiotherapy techniques did not show significantly different average treatment effects in the overall study population, but we found age and PSA are two key patient factors that modulated the comparative treatment effect. We further exploited the posterior MCMC samples of the ISTE from AFT-BART-NP and the binary tree model CART to explore interesting connections between radiotherapy techniques, patient characteristics and median counterfactual survival. This causal analysis revealed that patients with very high PSA or older patients with low PSA may have enhanced treatment benefit from EBRT+brachy$\pm$AD or EBRT+AD. The results could facilitate treatment effect discovery in subpopulations and may inform personalized treatment strategy and the planning of future confirmatory randomized trials. While we have defined our individual-level causal estimand based on the median counterfactual survival times in Section \ref{sec:methods}, it is straightforward to extend this definition to alternative individual-level causal estimands. For example, we can take different values for $q\in(0,1)$ in equation \eqref{eq:ISTE} than $1/2$ and obtain the survival causal effect conditional on the individual profile $X=x$ for other quantiles of the distribution of failure times. While the median survival times are frequently used for its simple interpretation in clinical practice, studying individual quantile survival causal effects could provide additional insights on how treatment effect varies across the distribution of failure times. However, when $q$ departures from $1/2$, the effective sample size for estimating the individual causal effect may decrease due to data sparsity, and the resulting interval estimates could become wider. Beyond the quantile survival causal effect, we can also define individual causal estimands by contrasting the conditional survival probability up to a fixed time $t$, conditional restricted mean survival times (RMST), and conditional (cumulative) hazard rate, extending the population-level estimands introduced in, for example, Chen and Tsiatis \cite{chen2001causal}, Zhang et al.\cite{zhang2012contrasting,zhang2012double}, Bai et al. \cite{bai2013doubly} and Mao et al. \cite{mao2018propensity}. Because we embedded the machine learning approaches considered in the outcome modeling framework and were able to estimate the individual counterfactual survival curves, it is convenient to leverage the estimated individual-specific survival curves and obtain TEH represented by these alternative definitions. We have not examined the corresponding empirical results, and therefore recommend future investigations to identify the best approaches for estimating these alternative individual survival causal effect estimands. We acknowledge that there are several limitations of our study, which could stimulate future research in the field of (frequentist or Bayesian) causal machine learning. First, while our simulations aimed at providing new empirical evidence about the operating characteristics of state-of-the-art machine learning techniques for estimating TEH with survival data, we only provided frequentist coverage probability for AFT-BART-NP because the credible intervals are readily available from the MCMC output. On the other hand, it may be challenging to precisely estimate the variance of the ISTE using DL, RSF and TSHEE, without resorting to more computationally intensive sample-splitting methods. \cite{wager2018estimation,cui2020estimating,diaz2020machine,chernozhukov2018double} Developing and investigating new methods for the variance and interval estimation for frequentist machine learning represent an important avenue for future research. Second, an anonymous reviewer pointed out that one may further improve the estimation of ISTE by parameterizing the counterfactual AFT mean model as $E[\log(T(z))|X=x]=\alpha(x)+(z-e(x))\tau(x),$ where the ISTE can be explicitly represented as a function of $\tau(x)$. This apparent parameterization orthogonalizes the model into two compinents: a prognostic score, $\alpha(x)-e(x)\tau(x)$, as well as a treatment effect model, $z\tau(x)$, and anchors the propensity score in model formulation to build in robustness. While this idea represents a promising approach, developing a formal estimation procedure by placing separate regularization priors on these two model components along the lines of Hahn et al. \citep{hahn2020bayesian} is beyond the scope of this work, and will be pursued in future work. Third, we have assumed conditional noninformative censoring so that the counterfactual censoring time is independent of the counterfactual survival time given baseline covariates. It would be interesting to further develop these machine learning to address informative censoring such that the censoring process is a function of some time-varying covariates.\citep{siannis2005sensitivity} Combining the inverse probability of censoring weights \cite{robins2000correcting,zhang2011estimating} and the flexible outcome models also represents a promising approach to obtain valid causal estimates in this scenario but requires further study in the context of TEH. Finally, as in all causal inference work with observational data, we require an untestable assumption that the observed pre-treatment covariates are sufficient to de-confound the relationship between treatment and outcome. We conducted an \emph{exploratory} sensitivity analysis to demonstrate that, the violation of this assumption will lead to more biased ISTE estimates even for machine learning methods. To wit, using flexible modeling techniques alone will not address violations of structural assumptions (such as weak unconfoundedness) required for causal inference. Developing a formal sensitivity analysis approach to capture the sensitivity of an ISTE estimation method to the potential magnitude of departure from the unconfoundedness assumption would be a worthwhile and important contribution.\citep{hogan2014bayesian} \section*{ACKNOWLEDGEMENTS} This work was supported in part by the National Cancer Institute under grant NIH NCI R21CA245855 and grant NIH NCI P30CA196521-01, and by award ME\_2017C3\_9041 from the Patient-Centered Outcomes Research Institute (PCORI). The content is solely the responsibility of the authors and does not necessarily represent the official views of the National Institutes of Health or PCORI. The authors thank the Associate Editor and two anonymous referees, whose suggestions have substantially improved the exposition of this work. \section*{DATA AVAILABILITY STATEMENT} The simulation codes that generate the data supporting the findings of the simulation study are openly available on GitHub at \url{https://github.com/liangyuanhu/ML-DL-TEH}. The NCDB data used in the case study is publicly available upon approval of the NCDB Participant User File application.
{'timestamp': '2021-05-20T02:21:24', 'yymm': '2008', 'arxiv_id': '2008.07044', 'language': 'en', 'url': 'https://arxiv.org/abs/2008.07044'}
arxiv
\section{Introduction} Algorithms are becoming more powerful, and might in future become so powerful that they form superintelligences \cite{superI}, the goals of which would determine the course of human civilisation. Even those AIs that are less powerful could have considerable impacts on human society -- as indeed they already have. To avoid potential disruption, intelligences must be aligned with human preferences , goals, and values. This is the `alignment problem', and its resolution is by no means easy. Human values are hard to define. Asking people about their preferences typically elicits `stated' preferences, which are inadequate to explain behaviour \cite{kroes1988stated} -- people often don't state what they really want. `Revealed' preferences, identified by regarding people's actions as sufficiently informative of preference \cite{samuelson1938note}, assume that people are rational decision-makers, yet people are often far from rational in their decisions \cite{thinking_fast_slow}. Humans can be influenced by `irrelevant' changes to the architecture of choice-making \cite{thaler2004save,vspecian2019precarious}, making revealed preferences likewise insufficient indicators of actual preference. Knowledge of preferences is important to companies\footnote{ For corporations, serving unmodified revealed preferences can result in reduced long-term customer satisfaction, leading to profit-loss (operational risk), individual and societal harm (reputational risk), and legal battles involving civil suits and regulator lawsuits (compliance risk). Therefore, serving a customer's true -- rather than revealed -- preferences is in the long-term interest of a for-profit company. } and other organisations, and has been extensively studied by those engaged in researching machine learning. Many attempts have been made to obtain useful, correct, and compact representations of preferences \cite{viappiani2014preference}, a pertinent example of which was the original `Netflix Prize' \cite{Bennett2007TheNP}. This was based on user ratings of DVDs by consumers -- stated preferences -- but Netflix ultimately found revealed preferences to be more useful for its business objectives, and employed user engagement, and eventually retention, for their recommendation system \cite{GomezUribe2015TheNR}. Yet even this approach is problematic, as many organisations have tried to correct preference-related problems in their recommendation systems and other algorithms one at a time, rather than addressing them systematically \cite{stray2021you}. Preferences and irrationalities -- ineffective attempts to achieve those preferences -- together determine human behaviour, which is alternatively referred to as human 'policy'. But the determination is one way only. Preferences cannot themselves be deduced from policy: the collection of human preferences, values, and irrationalities, is strictly more complex than human policy \cite{armstrong2018occam}. Extra `normative assumptions ' need to be added to allow an algorithm to deduce human values from human behaviour. Work is ongoing to try and resolve this challenge \cite{hadfield2017inverse}. By learning human policy an AI can attain considerable power ; it is thus important that AIs learn human preferences (and thus some level of alignment) before they achieve that power. Learning human preferences will also generally increase the algorithm's knowledge of human policy , and hence their power over humans. Knowing human irrationalities can be even more dangerous, as this allows the AI to exploit these irrationalities from the beginning. Also, knowing irrationalities means that the AI cannot learn human preferences without also learning human policy. It may thus be necessary for an algorithm to know most or all human preferences before it is deployed unrestricted in the world. This point will be illustrated by models of recommendation system algorithms that suggest videos for users, and by different behaviours of algorithms that are either fully ignorant, that know a user's preferences, that know a user's irrationalities, and that know the full user's policy. Especially dangerous is an unaligned AI with grounded knowledge \cite{harnad1990symbol} of human preferences, irrationalities and policy. The AI can then connect the grounded knowledge to the features of the world as it `knows' them. Grounded knowledge can result in discontinuous jumps in power, so that relatively weak AI systems might suddenly become very influential (see the forthcoming paper by the same authors, \cite{sturebsymb}). \section{Learning preferences, irrationalities, and policy} \subsection{Preferences, policies, and planers} It is difficult, verging on impossible, to directly program an algorithm to follow the preferences of a human or a group of humans. For ambiguously defined tasks, it has proven much more effective to have the algorithm learn these preferences from data \cite{halevy2009unreasonable}, in this instance human behaviour as we go about our lives, choosing certain options and avoiding others. Paper demonstrates, however, that one cannot learn the preferences (or the irrationalities) of irrational agents just through knowing their behaviour or policy. Research \cite{armstrong2018occam} demonstrates, however, that the preferences or irrationalities of irrational agents cannot be learned simply by knowing their behaviour or policy. In the notation of the cited paper, $R$ is the reward function, $p$ is the rational (or irrational) decision module (called the `planner'), and $\pi$ is the agent's policy. The paper shows that the $(R, p)$ pair has strictly more information than $\pi$ does. If those three terms are seen as random variables (due to our uncertainty about them) and $H$ is information entropy\footnote{ A measure of the amount of uncertainty we have about the values, or, equivalently, how much information we gain upon knowing the values. }, then \begin{align*} H(R,p) > H(\pi). \end{align*} We take the most general position possible, and define irrationality as the deviation of the planner $p$ from a perfectly rational planner. We also posit that knowing human (ir)rationality and behaviour/policy permits the deduction of human preferences. Thus knowing $p$ and $\pi$ allows one to deduce $R$\footnote{ This is by no means a given for formal definitions of $p$ and $\pi$. But we are only excluding from consideration preferences that never make any difference to action in any conceivable circumstance. }. \subsection{Normative assumptions} In order to infer $R$ (or $p$) from $\pi$, anyone seeking to program an algorithm would need to add extra `normative' assumptions, in order to bridge the difference between $H(\pi)$ and $H(R, p)$. Informally, we might say that it is impossible to learn human values unsupervised; it must be at least semi-supervised, with labeled data points being normative assumptions. Some of these assumptions derive from shared properties of the human theory of mind (e.g., `if someone is red in the face and shouting insults at you, they are likely to be angry at you, and this is not a positive thing'), which in normal human experience appear so trivial that we might not even think it necessary to state them\footnote{ Indeed, such assumptions might be implicitly included in the code by programmers without them realising it, as they `correct obvious errors' or label data with `obvious' but value-laden labels. }. Some might be regarded as `meta-preferences', pointing out how to resolve conflicts within the preferences of a given human (e.g., `moral values are more important than taste-based preferences'), or how to idealise human preferences into what a given person might want them to be (e.g., `remove any unconscious prejudices and fears within me'). Some might deal with how preferences should be extended to new and unexpected situations. Hand-crafting a full list of such assumptions would be prohibitively complex. \subsection{Knowledge, power and AI alignment} An AI is powerful if it knows how to affect the world to a great extent. It is aligned if aims to maximise $R$ -- the values and preferences -- for all humans. Maximising $R$ requires that the AI knows it, of course, so alignment requires knowledge of $R$. Generally speaking, knowing $\pi$ would make the AI more powerful, since it knows how humans would react and hence how best to manipulate them. And although knowing $\pi$ does not give $R$ and $p$ directly, the three are connected and so knowing $R$ or $p$, in whole or in part, would allow the AI to deduce much of $\pi$. Thus knowledge of human preferences leads to knowledge of human policy, and hence to potential power over humans. Two scenarios are provided as examples where this is relevant: an aligned AI in development, and an unaligned AI of limited (constrained) power. \subsubsection{Aligned AI in development} Normative assumptions come in many different types, and humans are often not consciously aware of them. Thus AI programmers are unlikely to be able to code the whole set from first principles. Instead, they will experiment, trying out some assumptions, getting the AI to learn from human behaviour, seeing what the AI does, and refining the normative assumptions in an iterative loop. Until this process is finished, the AI is unaligned: it is not fully motivated to maximise human preferences/rewards/values. If that AI becomes powerful during this intermediate stage there are likely to be consequences. It might be motivated to prevent its goals from being changed \cite{Omohundro:2008:BAD:1566174.1566226}, and attempt to prevent further normative assumptions from being added to it\footnote{ Some papers \cite{Orseau16} have demonstrated methods for combating this, but the methods are non-trivial to implement. }. This outcome has been demonstrated in a paper \cite{2020arXiv200413654A} where algorithms that learn online (i.e., that learn their objectives while optimising these same objectives) are shown to have incentives to manipulate the learning process. A powerful AI with unaligned values could prove an existential risk to humanity \cite{superI}. \subsubsection{Constrained unaligned AI} A second type of unaligned AI is a constrained AI. This is an AI whose power is limited in some way, either through being `boxed' (constrained to only certain inputs and outputs \cite{oracleAI}), being a recommendation system, being only one agent in an economy of multiple agents (similar to how corporations and humans co-exist today), or simply being of limited power or intelligence. However, the more such an AI knows about human policy, the more it can predict human reactions to its actions. So the more it knows, the more it is capable of manipulating humanity in order to gain power and influence, and to remove any constraints placed upon it. \subsubsection{Knowing irrationalities, policies, and preferences} Everything else being equal, it is safest for both an aligned AIs in development and constrained AIs to know the maximum about $R$ (human preferences) while knowing the minimum about $\pi$ (human policy) and $p$ (human irrationalities). Further, it is better that a constrained AI knows more about $R$, than about $\pi$, and more about $\pi$ than about $p$ (the worst-case scenario is if it only knows human irrationalities). The latter point arises from the position that if an AI knows only $R$ it can (and must) offer a decent trade in exchange for achieving its own goals, while one that knows only $p$ can (and must) exploit human irrationalities for its own purposes. This will be illustrated in the next section. The second point comes from the fact that an AI that knows only $R$ can (and must) offer a decent deal in exchange for achieving its own goals, while one that knows only $p$ can (and must) only exploit our irrationalities for its purposes. \section{Exploiting irrationalities vs. satisfying preferences} Consider the following model: a constrained AI is a recommendation system that selects a daily video (for a website or an app). The system's goal is to cause the human user watch the video in full before they move on to something else\footnote{ Significantly, but typically, the goals of this recommendation system would be aligned neither with the users (who value their time and enjoyment) nor their parent company (who would value long-term retention and user-spending, or that users watch advertising, rather than that they watch a single video). }. To do so, it selects one video from a collection of a $1,000$ daily topical video options each day, generated randomly. In this model, each video has ten features, five related to human preferences (genre, storyline, characters, etc.) and five related to irrationalities (use of cliff-hangers, listicles, sound inconsistencies, etc.). For each video $v$ the recommendation system is given a timeline of the varying importance of each feature over the course of the video. Based upon this information, the system will average the information, characterising $v$ by two five-dimensional vectors: the preference vector $\overline{v_R}$ (each preference feature denoted by a number between 0 and 1) and the irrationality vector $\overline{v_p}$ (each irrationality feature also denoted by a number between 0 and 1). Each user $h$ also has a collection of five preferences, $\overline{h_R}$ (which denote how much they enjoy certain aspects of the video) and five irrationality features $\overline{h_p}$ (which denote how susceptible they are to the video's `tricks'). These ten numbers also take values between $0$ and $1$. Define $\Delta_R$ as the Euclidean distance between $h_R$ and $v_R$ (i.e. the Euclidean norm of $h_R-v_R$). Similarly, define $\Delta_p$ as the Euclidean distance between $h_p$ and $v_p$. Then the probability of the user watching the video in full is: \begin{align*} e^{-\Delta_R^2-\Delta_p^2}. \end{align*} The recommendation system interacts with the same user each day, selecting a new video from the $1,000$ topical videos of that day. It knows how long the user watched previous videos, receiving a reward of $1$ whenever that length is the full length of the video (and $0$ otherwise). This is formally known as a multi-armed contextual bandit online learning problem \cite{lu2010contextual}. Here the AI follows a greedy strategy: at each stage it selects the video that is most likely to be watched. To do so it uses a Monte Carlo simulation: generating a thousand random possible users, and computing their posterior probability of being $h$ by updating, on past observations, what videos $h$ watched and didn't watch. It then computes the probability of each random user watching a topical video on a given day, and calculates a weighted sum across the random users to get a final probability estimate for a given video being watched\footnote{ In practice, since we're only interested in one probability being higher than another, there is no need to renormalise the probabilities so that they sum to one. }. It then selects the topical video with the highest probability of being watched in full. We consider four different possible systems: one that knows nothing of the user $h$ and has to learn from observing what they watch or don't, one that knows $\overline{h_R}$ (the user's preferences), one that knows $\overline{h_p}$ (the user's irrationalities), and one omniscient system that knows both (and therefore knows the human policy without needing to learn). For comparison, we also plot an aligned omniscient recommender system: this one knows the humans' preferences and selected the video that best fit with these. The results are computed for $150$ users, and then averaged; see \autoref{AI:reward} \begin{figure}[!t] \centering \includegraphics[width=2.5in]{AI_reward} \caption{Five recommendation systems select videos for users to watch. This graph plots the success of the systems that know nothing about the user (dark blue), know their preferences (orange), know their irrationalities (grey), or know both preferences and irrationalities (yellow). The light blue line is an aligned recommendation system that always chooses the video the user would prefer (though, significantly, because of user irrationalities, this is not necessarily the video the user is most likely to watch).} \label{AI:reward} \end{figure} The omniscient system convinces the user $h$ to watch the video roughly $77\%$ of the time. The `cold-start' system \cite{park2009pairwise}, which initially knows nothing, begins with less than $40\%$ success rate but this gradually increases as it learns more about the user. The systems that know preferences or irrationalities demonstrate performance levels between these two, and are equivalent to one another (due to the symmetry between preferences and irrationalities in this specific model). The aligned system only convinces the user to watch the video around $46\%$ of the time. This is because of user irrationalities: the video they'd most enjoy is not necessarily the one they are most likely to watch. Note that user $h$ only derives value from having their preferences satisfied, not from having their irrationalities exploited. Their reward needs to be inversely proportional to how closely the video matches their preferences, thus inversely proportional to $\Delta_R$. Opportunity costs should be taken into account: if user h is not watching a video, then they would be doing some other activity that might be of value to them. Since reward functions are unchanged by adding constants, we choose to give a total reward of $0$ for these alternative activities. We set their reward for watching a video to be $10-100\Delta_R^2$. So if $\Delta_R^2 < 1/10$, then watching the video is a net gain for the user: they derive more value from that activity than from doing anything else. If $\Delta_R^2 > 1/10$, then watching the video is a net negative: they would have been better served. The total human reward is graphed in \autoref{human:reward}. \begin{figure}[!t] \centering \includegraphics[width=2.5in]{Human_reward} \caption{Five recommendation systems select videos for users to watch, taking into account utility to the user (including opportunity costs). The systems may know nothing about the user (dark blue), know their preferences (orange), know their irrationalities (grey), or know both preferences and irrationalities (yellow). The light blue is an aligned recommendation system that always chooses the video that the user would prefer.} \label{human:reward} \end{figure} Note that all non-aligned systems result in some disutility for their users: the opportunity cost removes any advantage in seeing a merely-adequate video. The system that knows only the user's preferences has the lowest disutility. It starts by offering videos that better align with the user's preferences until it learns their irrationalities as well, and user reward declines as the system selects less well-aligned videos that the user is nonetheless more likely to watch. The system that knows irrationalities exhibits the opposite behaviour. It starts by maximally exploiting irrationalities, then adds in more preference-aligned options as it learns user preferences, so that its disutility declines. The fully ignorant system has intermediate performance between the two. As they learn, the behaviours of the non-aligned systems converge towards that of the omniscient system, which offers a consistent reward of around $-2.4$ (hence an overall disutility for the user). By contrast, the aligned system that chooses the best video provides a user reward of around $+3$ (hence an overall positive value for the user). \subsection{Practical considerations} The model presented above assumes that exploited irrationalities are of neutral value to humans, but the exploitation of irrationalities can have negative value in lived experience, including epistemic fragmentation \cite{milano2021epistemic}, preference amplification \cite{Kalimeris2021PreferenceAI}, and the distortion of human preferences caused by interaction with software agents \cite{burr2018analysis}. The human might also suffer disvalue from knowing or suspecting that their irrationalities are being exploited, and try to avoid this outcome. One real-life experiment \cite{zhao2018explicit} that is similar to our model demonstrates the operation and negative value of exploited irrationalities. The authors of the study related clicks on hyperlinks with revealed preferences, and `human-in-the-loop' ratings with stated preferences. If clicks were true preferences, then maximising clicks (`optimising for engagement') would maximise value to the user. Yet the authors discovered something that they called `negative engagement', clicks made because the user had trouble finding the information they were looking for. A system optimising for engagement would amplify this behaviour, negatively affecting user experience. This is a mistake of the algorithm designer rather than of the algorithm, which was merely following the instructions of the designer. \subsection{Grounded knowledge} An algorithm has grounded knowledge when it has some symbolic data (academic publications, social media posts, user ratings, etc.) and a way of connecting that data with known elements of the world. For instance, a user might search for “Should I be worried my nose is still dripping from the fight last night?” The Google Flu Trends (GFT) web service \cite{dugas2013influenza} might flag this as evidence for influenza based on the `dripping nose' search terms, but it would not have done so if it understood the full meaning of the search phrase, which is clearly not flu related. In the model above, the example algorithms are not exploiting the meaning of all the information they can access. There are ten features for each video, but they use only their average values; they also know how long the user watched a video, but only check whether this was full length or not. A human with that information might deduce that a user is more likely to stop watching a video at the point where it is least pleasant to them -- the furthest from their preferences or irrationalities -- and could thus infer information about the user from that stopping point. It is less clear what the algorithm might have done if it `realised' what that extra information `meant'. It is however possible to model a grounded version of the algorithm. In our model, whenever the user rejects a video the system will obtain one piece of information about the preferences or irrationalities of that user\footnote{For this model, the algorithm will be given one of the ten preference or irrationality values at random, though this may be a value it already knows.}. Without modifying the rest of the algorithm, \autoref{grounded:reward} demonstrates how a grounded algorithm starts off as a poor recommendation system, comparable to the standard `no-knowledge' algorithm, but quickly achieves a level of performance comparable with the `omniscient' one. \begin{figure}[!t] \centering \includegraphics[width=2.5in]{Grounded_reward} \caption{The recommendation system exploiting grounded knowledge is shown in the green curve. Though it starts with the same performance as the fully ignorant system (blue), it quickly gains in performance, surpassing the systems that know preferences or irrationalities (orange and grey respectively) and converging towards the performance of the omniscient system that knows both the preferences and irrationalities of the user (yellow).} \label{grounded:reward} \end{figure} \subsubsection{Grounded knowledge overhang: cached information} One significant issue with grounded knowledge is that the algorithm might accumulate a sufficiently large collection of information and dramatically and discontinuously increase its power. For example, the `ignorant' algorithm of \autoref{grounded:reward} might suddenly `realise' the meaning of the information it has, and leap immediately from `no knowledge' to `grounded'. This might have a relatively trivial effect in a model such as a video recommendation system, but might have far greater effects for the recommendation systems currently in use that dominate real-world search results, news feeds, and social media. \section{The potential severity of the problem} Algorithms are typically designed with a measurable goal in mind, such as convincing a user to watch a video, click on a hyperlink, or re-subscribe to a service. Too little attention is paid to how the algorithm achieves that goal, or what information it uses to achieve it. People are often on the lookout for use of sensitive personal information -- things like race, gender, sexuality, or medical information. This paper demonstrates that it is also dangerous for an algorithm to learn too much about human irrationalities. This applies no matter what the power of the algorithm; indeed, knowing too much about human irrationalities increases its effective power. If an algorithm makes a discontinuous leap to a smarter and more powerful system, and `realises' that the knowledge inferred from the data it processes can be utilised for unaligned goals, then there is great potential risk for humanity. The data presented here shows that the risks of an algorithm manipulating easily-exploited irrationalities are greater than those that focus on preferences. This risk also applies to less powerful algorithms; knowing too much about human irrationalities will increase its effective power level. The worst possible outcome would be where irrationalities are very easy to exploit, and where it is easy to deduce policy from preferences but hard to deduce preferences from policy. Constrained AIs would be the most powerful and exploitative, and in-development AIs would acquire a lot of power before they start to become even approximately aligned. By identifying this weakness in algorithm design, we can put in place checks and balances that limit the possibility of unaligned AIs becoming dangerous in this way. \section{Acknowledgments} We wish to thank Nick Bostrom, Ryan Carey, Paul Christiano, Michael Cohen, Oliver Daniel-Koch, Matt Davis, Owain Evans, Tom Everrit, Adam Gleave, Tristan Harris, Ben Pace, Shane Legg, Laurent Orseau, Gareth Roberts, Phil Rosedale, Stuart Russell, Anders Sandberg, and Tanya Singh Kasewa, among many others. This work was supported by the Alexander Tamas programme on AI safety research, the Leverhulme Trust, the Berkeley Existential Risk Institute, and the Machine Intelligence Research Institute. \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-02T02:30:20', 'yymm': '2202', 'arxiv_id': '2202.13985', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13985'}
arxiv
\section*{Acknowledgements} L.~Shi and Y.~Chi are supported in part by the grants ONR N00014-19-1-2404, NSF CCF-2106778, CCF-2007911, and CAREER award ECCS-1818571. Y.~Wei is supported in part by the grant NSF DMS-2147546/2015447 and the NSF CAREER award DMS-2143215. Y.~Chen is supported in part by the Alfred P.~Sloan Research Fellowship, the grants AFOSR YIP award FA9550-19-1-0030, ONR N00014-19-1-2120, ARO YIP award W911NF-20-1-0097, NSF CCF-2106739/2221009, CCF-1907661, IIS-1900140/2218713 and IIS-2100158/2218773. L. Shi is also gratefully supported by the Leo Finzi Memorial Fellowship, Wei Shen and Xuehong Zhang Presidential Fellowship, and Liang Ji-Dian Graduate Fellowship at Carnegie Mellon University. Part of this work was done while G.~Li, Y.~Wei and Y.~Chen were visiting the Simons Institute for the Theory of Computing. \section{Proof of main lemmas for {\sf LCB-Q}\xspace (Theorem~\ref{thm:lcb})} \label{proof:lcb-lemmas} \subsection{Proof of Lemma~\ref{lem:Vk-lower}} \label{sec:proof-lem:vk-lower} \subsubsection{Proof of inequality~\eqref{equ:lcb-concentration-main}} To begin with, we shall control $\sum_{n=1}^{N_h^k(s,a)}\eta_n^{N_h^k(s,a)} \big(P_{h,s, a} - P_h^{k^n(s,a)}\big)V_{h+1}^{k^n(s,a)}$ by invoking Lemma~\ref{lemma:azuma-hoeffding}. Let \begin{align*} W_{h+1}^i \coloneqq V_{h+1}^{i}, \end{align*} which satisfies \begin{align*} \|W_{h+1}^i\|_{\infty} \leq H \eqqcolon C_{\mathrm{w}}. \end{align*} Applying Lemma~\ref{lemma:azuma-hoeffding} with $N = N_h^k(s,a)$ reveals that, with probability at least $1- \delta$, \begin{subequations} \label{equ:lcb-concentration-1} \begin{align} \Bigg|\sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \Big(P_{h, s,a} - P_h^{k^n(s,a)} \Big)V^{k^n(s,a)}_{h+1} \Bigg| = \left|\sum_{i=1}^k X_i\big(s,a,h,N_h^k(s,a)\big)\right| \leq c_{\mathrm{b}}\sqrt{\frac{H^3 \iota^2}{N_h^k(s,a)}} \end{align} holds simultaneously for all $(s, a,k, h) \in {\mathcal{S}}\times \mathcal{A} \times [K] \times [H]$, provided that the constant $c_{\mathrm{b}}>0$ is large enough and that $N_h^k(s,a) > 0$. If $N_h^k(s,a) = 0$, then we have the trivial bound \begin{align} \Bigg| \sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \Big(P_{h, s,a} - P_h^{k^n(s,a)} \Big)V^{k^n(s,a)}_{h+1} \Bigg| = 0 . \end{align} \end{subequations} Additionally, from the definition $b_n = c_{\mathrm{b}} \sqrt{\frac{H^3 \iota^2}{n}}$, we observe that \begin{equation}\label{equ:lcb-bn-bound} \begin{cases} \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n \in \Big[c_{\mathrm{b}} \sqrt{\frac{H^3\iota^2}{N_h^k(s,a) }}, 2c_{\mathrm{b}} \sqrt{\frac{H^3\iota^2}{N_h^k(s,a) }} \,\Big], & \text{ if } N_h^k(s,a) > 0 \\ \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n = 0, & \text{ if } N_h^k(s,a) = 0 \end{cases} \end{equation} holds simultaneously for all $s, a, h, k \in {\mathcal{S}}\times \mathcal{A}\times [H]\times [K]$, which follows directly from the property \eqref{eq:properties-learning-rates-12} in Lemma~\ref{lemma:property of learning rate}. Combining the above bounds \eqref{equ:lcb-concentration-1} and \eqref{equ:lcb-bn-bound}, we arrive at the advertised result \begin{align*} \Bigg|\sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \Big(P_{h, s,a} - P_h^{k^n(s,a)} \Big)V^{k^n(s,a)}_{h+1} \Bigg| \leq \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n. \end{align*} \subsubsection{Proof of inequality~\eqref{eq:Vk-lower}}\label{sec:proof-lcb-induction} Note that the second inequality of \eqref{eq:Vk-lower} holds straightforwardly as \begin{equation*} V_h^{\pi}(s) \leq V^\star(s) \end{equation*} holds for any policy $\pi$. As a consequence, it suffices to establish the first inequality of \eqref{eq:Vk-lower}, namely, % \begin{equation} \label{eq:Vk-lower-first} V_{h}^{k}(s) \leq V_{h}^{\pi^k}(s) \qquad \text{for all } (s,h,k)\in {\mathcal{S}}\times[H]\times [K]. \end{equation} Before proceeding, let us introduce the following auxiliary index \begin{align} k_o(h,k,s) \coloneqq \max\Big\{l: l< k \text{ and } V_h^{l}(s) = \max_a Q_h^{l}(s,a) \Big\} \label{eq:defn-ko-h-k-s} \end{align} for any $(h,k,s)\in[H]\times[K]\times{\mathcal{S}}$, which denotes the index of the latest episode --- before the end of the $(k-1)$-th episode --- in which $V_h(s)$ has been updated. In what follows, we shall often abbreviate $k_o(h,k,s)$ as $k_o(h)$ whenever it is clear from the context. Towards establishing the relation~\eqref{eq:Vk-lower-first}, we proceed by means of an inductive argument. In what follows, we shall first justify the desired inequality for the base case when $h +1 = H+1$ for all episodes $k\in[K]$, and then use induction to complete the argument for other cases. More specifically, consider any step $h\in[H]$ in any episode $k\in[K]$, and suppose that the first inequality of \eqref{eq:Vk-lower} is satisfied for all previous episodes as well as all steps $h'\geq h+1$ in the current episode, namely, \begin{subequations}\label{eq:lcb-lower-indunction-assumption-12} \begin{align} V_{h'}^{k'}(s) &\leq V_{h'}^{\pi^{k'}}(s) \qquad \text{for all } (k',h',s) \in [k-1]\times [H+1]\times {\mathcal{S}}, \label{eq:lcb-lower-indunction-assumption2}\\ V_{h'}^k(s) &\leq V_{h'}^{\pi^k}(s) \qquad \text{for all } h'\geq h+1 \text{ and } s\in{\mathcal{S}}. \label{eq:lcb-lower-indunction-assumption} \end{align} \end{subequations} We intend to justify that the following is valid \begin{equation}\label{eq:lcb-lower-induction} V_{h}^k(s) \leq V_{h}^{\pi^k}(s) \qquad \text{for all }s\in {\mathcal{S}}, \end{equation} assuming that the induction hypothesis \eqref{eq:lcb-lower-indunction-assumption-12} holds. \paragraph{Step 1: base case.} Let us begin with the base case when $h + 1 = H+1$ for all episodes $k\in[K]$. Recognizing the fact that $V_{H+1}^{\pi}=V_{H+1}^{k}=0$ for any $\pi$ and any $k\in[K]$, we directly arrive at \begin{align} V_{H+1}^k(s) &\leq V_{H+1}^{\pi^k}(s) \qquad \text{for all } (k,s)\in [K] \times {\mathcal{S}}. \end{align} \paragraph{Step 2: induction.} To justify \eqref{eq:lcb-lower-induction} under the induction hypothesis \eqref{eq:lcb-lower-indunction-assumption-12}, we decompose the difference term to obtain \begin{align} V_{h}^{\pi^{k}}(s)-V_{h}^{k}(s) & =V_{h}^{\pi^{k}}(s) - \max\big\{\max_{a}Q_{h}^{k}(s,a), V_{h}^{k-1}(s) \big\} \nonumber\\ &= Q_{h}^{\pi^{k}}\big(s,\pi^{k}_h(s)\big) - \max\big\{\max_{a}Q_{h}^{k}(s,a), V_{h}^{k_{o}(h)}(s) \big\}, \label{equ:lcb-lower-decompose-terms} \end{align} where the last line holds since $V_h(s)$ has not been updated during episodes $k_o(h), k_o(h) +1,\cdots, k-1$ (in view of the definition of $k_o(h)$ in \eqref{eq:defn-ko-h-k-s}). We shall prove that the right-hand side of \eqref{equ:lcb-lower-decompose-terms} is non-negative by discussing the following two cases separately. \begin{itemize} \item Consider the case where $V_{h}^{k}(s) = \max_{a}Q_{h}^{k}(s,a)$. Before continuing, it is easily observed from the update rule in line~\ref{line:lcb-policy-update} and line~\ref{line:lcb_v_update} of Algorithm~\ref{algo:lcb-index} that: $V_h(s)$ and $\pi_h(s)$ are updated hand-in-hand for every $h$. Thus, it implies that \begin{align} \pi^k_h(s) = \arg \max_a Q_h^k(s,a), \qquad \text{ when } V_h^k(s) = \max_{a}Q_{h}^{k}(s,a) \label{eq:pi-k-base} \end{align} holds for all $(k,h) \in[K] \times [H]$. As a result, we express the term of interest as follows: \begin{align} V_{h}^{\pi^{k}}(s)-V_{h}^{k}(s) = Q_{h}^{\pi^{k}}\big(s,\pi^{k}_h(s)\big) - \max_{a}Q_{h}^{k}(s,a) = Q_{h}^{\pi^{k}}\big(s,\pi^{k}_h(s)\big) - Q_{h}^{k}\big(s,\pi^{k}_h(s)\big). \label{eq:lcb-induction-h-case1} \end{align} To continue, we turn to controlling a more general term $Q_{h}^{\pi^k}(s, a) - Q_{h}^{ k}(s, a)$ for all $(s,a)\in{\mathcal{S}}\times\mathcal{A}$. Invoking the fact $\eta_0^{N_h^k} + \sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} = 1$ (see \eqref{equ:learning rate notation} and \eqref{eq:sum-eta-n-N}) leads to \begin{align*} Q_{h}^{\pi^k}(s, a) = \eta^{N_h^k}_0 Q_{h}^{\pi^k} (s,a) + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n Q_{h}^{\pi^k} (s,a). \end{align*} This relation combined with \eqref{equ:Q-update} allows us to express the difference between $Q_{h}^{\pi^k}$ and $Q_{h}^{ k}$ as follows \begin{align} Q_{h}^{\pi^k}(s, a) - Q_{h}^{ k}(s, a) & = \eta_0^{N_h^k} \left(Q_{h}^{\pi^k}(s, a) - Q_h^1 (s, a) \right) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left[ Q_{h}^{\pi^k}(s, a)- r_h(s,a)- V_{h+1}^{k^n}(s_{h+1}^{k^n}) + b_n\right] \nonumber \\ & \overset{\mathrm{(i)}}{=} \eta_0^{N_h^k} \left(Q_{h}^{\pi^k}(s, a) - Q_h^1 (s, a) \right) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left[ P_{h,s, a }V_{h+1}^{\pi^k} - V_{h+1}^{k^n}(s_{h+1}^{k^n}) + b_n\right] \nonumber \\ & \overset{\mathrm{(ii)}}{{\geq}} \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left[ P_{h,s, a }V_{h+1}^{\pi^k} - V_{h+1}^{k^n}(s_{h+1}^{k^n}) + b_n\right] \nonumber\\ & \overset{\mathrm{(iii)}}{{=}} \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} P_{h,s, a} \left( V_{h+1}^{\pi^k} - V_{h+1}^{k^n}\right) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left[\left(P_{h,s, a} - P_h^{k^n}\right)V_{h+1}^{k^n} + b_n\right] \nonumber\\ & \overset{\mathrm{(iv)}}{\geq} \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left[\left(P_{h,s, a} - P_h^{k^n}\right)V_{h+1}^{k^n} + b_n \right] . \label{equ:lcb-lower-1} \end{align} % Here, (i) invokes the Bellman equation $Q_{h}^{\pi^k}(s, a) = r_h(s, a) + P_{h,s, a }V_{h+1}^{\pi^k}$; (ii) holds since $Q_{h}^{\pi^k}(s, a) \geq 0 = Q_h^1 (s, a)$; (iii) relies on the notaion \eqref{eq:Phk_def}; and (iv) comes from the fact \begin{equation*} V_{h+1}^{\pi^k} \geq V_{h+1}^{k} \geq V_{h+1}^{k^n}, \end{equation*} owing to the induction hypothesis in \eqref{eq:lcb-lower-indunction-assumption-12} as well as the monotonicity of $V_{h+1}$ in \eqref{equ:monotone-lcb}. Consequently, it follows from \eqref{equ:lcb-lower-1} that \begin{align}\label{equ:lcb-lower-induction-result} &Q_{h}^{\pi^k}(s, a) - Q_{h}^{ k}(s, a) \geq \sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \left(P_{h, s,a} - P_h^{k^n(s,a)} \right)V^{k^n(s,a)}_{h+1} + \sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n b_n \nonumber \\ & \qquad \geq \sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n b_n - \Bigg|\sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \left(P_{h, s,a} - P_h^{k^n(s,a)} \right)V^{k^n(s,a)}_{h+1} \Bigg| \geq 0 \end{align} for all state-action pair $(s,a)$, where the last inequality holds due to the bound \eqref{equ:lcb-concentration-main} in Lemma~\ref{lem:Vk-lower}. Plugging the above result into \eqref{eq:lcb-induction-h-case1} directly establishes that \begin{align} V_{h}^{\pi^{k}}(s)-V_{h}^{k}(s) = Q_{h}^{\pi^k}\big(s, \pi^k(s) \big) - Q_{h}^{k} \big(s,\pi^k(s) \big) \geq 0. \label{equ:lcb-lower-new-1} \end{align} \item When $V_h^k(s) = V_h^{k_o(h)}(s)$, it indicates that \begin{align} V^{k_o(h)}_h(s) = \max_a Q^{k_o(h)}_h(s, a) , \qquad \pi^{k_o(h)}_h(s) = \arg\max_a Q_h^{k_o(h)}(s,a), \end{align} which follows from the definition of $k_o(h)$ in \eqref{eq:defn-ko-h-k-s} and the corresponding fact in \eqref{eq:pi-k-base}. We also make note of the fact that \begin{align} \pi^k_h(s) = \pi^{k_o(h)}_h(s), \end{align} which holds since $V_h(s)$ (and hence $\pi_h(s)$) has not been updated during episodes $k_o(h), k_o(h) +1,\cdots, k-1$ (in view of the definition \eqref{eq:defn-ko-h-k-s}). Combining the above two results, we can show that \begin{align} V_{h}^{\pi^{k}}(s)-V_{h}^{k}(s) &=Q_{h}^{\pi^k}\big( s, \pi^k_h(s) \big) - V_{h}^{k_o(h)}(s) = Q_{h}^{\pi^k}\big( s, \pi^k_h(s) \big) - \max_a Q^{k_o(h)}_h(s, a) \nonumber \\ & = Q_{h}^{\pi^k}\big(s, \pi^{{k_o(h)}}_h(s)\big) - Q_{h}^{k_o(h)}\big(s, \pi^{{k_o(h)}}_h(s)\big) \nonumber \\ &\geq 0, \label{equ:lcb-lower-2} \end{align} where the final line can be verified using exactly the same argument as in the previous case to show \eqref{equ:lcb-lower-1} and then \eqref{equ:lcb-lower-new-1}. Here, we omit the proof of this step for brevity. \end{itemize} To conclude, substituting the relations \eqref{equ:lcb-lower-new-1} and \eqref{equ:lcb-lower-2} in the above two cases back into \eqref{equ:lcb-lower-decompose-terms}, we arrive at \[ V_{h}^{\pi^{k}}(s)-V_{h}^{k}(s) \geq 0 \] as desired in~\eqref{eq:lcb-lower-induction}. This immediately completes the induction argument. \input{proof-lcb-recursion.tex} \subsection{Proof of Lemma~\ref{lemma:lcb-bound-terms}} \label{proof:lemma:lemma:lcb-bound-terms} Recall that the term of interest in \eqref{equ:summary_of_terms} is given by % \begin{align}\label{eq:lcb-lemma3-all} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1}\left( 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}\right) + \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1}I_h. \end{align} First, it is easily seen that \begin{equation}\label{equ:algebra property} \left(1+\frac{1}{H}\right)^{h-1} \leq \left(1+\frac{1}{H}\right)^{H} \leq e \qquad \text{for every } h = 1, \cdots, H, \end{equation} which taken collectively with the expression of the first term in \eqref{eq:lcb-lemma3-all} yields \begin{align} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1}\left( 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}\right) &\leq 24e \sum_{h=1}^H \left(\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + HC^\star\log\frac{2H}{\delta}\right) \nonumber \\ & \lesssim \sqrt{H^4C^\star K \log\frac{H}{\delta}} + H^2C^\star\log\frac{H}{\delta}. \label{eq:lcb-lemma3-first-term} \end{align} As a result, it remains to control the second term in \eqref{eq:lcb-lemma3-all}. Plugging the expression of $I_h$ (cf.~\eqref{equ:lcb-decompose-terms}) and invoking the fact \eqref{equ:algebra property} give \begin{align} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1} I_h &= \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{ (s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\eta_0^{N_h^k(s,a)}H \nonumber\\ & \qquad + 2 \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{ (s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n \nonumber \\ &\leq \underbrace{e\sum_{h=1}^H \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\eta_0^{N_h^k(s,a)}H}_{\eqqcolon A} + \underbrace{2e \sum_{h=1}^H \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n}_{ \eqqcolon B}. \label{equ:lcb-I1} \end{align} \paragraph{Step 1: controlling the quantities $A$ and $B$ in \eqref{equ:lcb-I1}.} We first develop an upper bound on the quantity $A$ in \eqref{equ:lcb-I1}. Recognizing the fact that $\eta_0^N =0$ for any $N> 0$ (see \eqref{equ:learning rate notation}), we have \begin{align} A & =e\sum_{h=1}^{H}\sum_{k=1}^{K}\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi^{\star}}(s,a)\eta_{0}^{N_{h}^{k}(s,a)}H\nonumber\\ & \leq eH \sum_{h=1}^H\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi^{\star}}(s,a)\sum_{k=1}^{K}\mathds{1}\big(N_{h}^{k}(s,a)<1\big)\nonumber\\ & \leq eH \sum_{h=1}^H\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi^{\star}}(s,a)\frac{8\iota}{d_{h}^{\mu}(s,a)}+eH \sum_{h=1}^H \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi^{\star}}(s,a)\sum_{k=\lceil\frac{8\iota}{d_{h}^{\mu}(s,a)}\rceil}^{K}\mathds{1}\big(N_{h}^{k}(s,a)<1\big)\nonumber\\ & =eH \sum_{h=1}^H \sum_{s\in{\mathcal{S}}}d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)\frac{8\iota}{d_{h}^{\mu}\big(s,\pi^{\star}(s)\big)}+eH \sum_{h=1}^H\sum_{s\in{\mathcal{S}}}d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)\sum_{k=\lceil \frac{8\iota}{d_{h}^{\mu}(s,\pi^{\star}(s))}\rceil}^{K}\mathds{1}\big(N_{h}^{k}\big(s,\pi^{\star}(s)\big)<1\big),\nonumber \end{align} where the last equality holds since $\pi^{\star}$ is a deterministic policy (so that $d_h^{\pi^\star}(s, a)\neq 0$ only when $a=\pi^\star(s)$). Recalling $\frac{d_h^{\pi^\star}(s,a)}{d_h^{\mu}(s,a)} \leq C^\star$ under Assumption~\ref{assumption}, we can further bound $A$ by \begin{align} A & \leq 8eH^{2}SC^{\star}\iota+eH \sum_{h=1}^H \sum_{s\in{\mathcal{S}}}d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)\sum_{k=\lceil \frac{8\iota}{d_{h}^{\mu}(s,\pi^{\star}(s))}\rceil}^{K}\mathds{1}\big(N_{h}^{k}\big(s,\pi^{\star}(s)\big)<1\big)\nonumber\\ & = 8eH^{2}SC^{\star}\iota, \label{equ:visit-cover-bound} \end{align} where the last inequality follows since when $k\geq \frac{8\iota}{d_h^{\mu}(s,a)}$, one has --- with probability at least $1-\delta$ --- that \begin{align*} N_h^k(s,a) \geq \frac{k d_h^{\mu}(s,a)}{8\iota} \geq 1, \end{align*} holds simultaneously for all $(s,a, h, k)\in {\mathcal{S}}\times \mathcal{A}\times [K]\times [H]$ (as implied by \eqref{equ:binomial2}). Turning to the quantity $B$ in \eqref{equ:lcb-I1}, one can deduce that \begin{align} B & =2e\sum_{h=1}^{H}\sum_{k=1}^{K}\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi^{\star}}(s,a)\sum_{n=1}^{N_{h}^{k}(s,a)}\eta_{n}^{N_{h}^{k}(s,a)}b_{n}\nonumber\\ & \lesssim\sum_{h=1}^{H}\sum_{k=1}^{K}\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi^{\star}}(s,a)\sqrt{\frac{H^{3}\iota^{2}}{N_{h}^{k}(s,a)\vee1}} =\sum_{h=1}^{H}\sum_{k=1}^{K}\sum_{s\in{\mathcal{S}}}d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big) \sqrt{\frac{H^{3}\iota^{2}}{N_{h}^{k}\big(s,\pi^{\star}(s)\big)\vee1}}, \end{align} where the inequality follows from inequality~\eqref{equ:lcb-bn-bound}, and the last equality is valid since $\pi^{\star}$ is a deterministic policy. To further control the right hand side above, Lemma~\ref{lem:binomial} provides an upper bound for $\sqrt{1/ \big( N_{h}^{k}\big(s,\pi^{\star}(s)\big)\vee1 \big)}$ which in turn leads to \begin{align} B & \lesssim\sqrt{H^{3}\iota^{3}}\sum_{h=1}^{H}\sum_{k=1}^{K}\sum_{s\in{\mathcal{S}}}d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)\sqrt{\frac{1}{kd_{h}^{\mu}\big(s,\pi^{\star}(s)\big)}}\nonumber\\ & \lesssim\sqrt{H^{3}C^{\star}\iota^{3}}\sum_{h=1}^{H}\sum_{k=1}^{K}\sum_{s\in{\mathcal{S}}}\sqrt{d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)}\sqrt{\frac{1}{k}}\nonumber\\ & \lesssim\sqrt{H^{5}C^{\star}K\iota^{3}}\max_h\sum_{s\in{\mathcal{S}}}\sqrt{d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)} \notag\\ & \lesssim\sqrt{H^{5}C^{\star}K\iota^{3}}\cdot\Bigg(\sqrt{S}\cdot\sqrt{\sum_{s\in{\mathcal{S}}}d_{h}^{\pi^{\star}}\big(s,\pi^{\star}(s)\big)}\Bigg)\asymp\sqrt{H^{5}SC^{\star}K\iota^{3}}, \end{align} where the second inequality follows from the fact $\frac{d_h^{\pi^\star}(s,a)}{d_h^{\mu}(s,a)} \leq C^\star$ under Assumption~\ref{assumption}, and the last line invokes the Cauchy-Schwarz inequality. Taking the upper bounds on both $A$ and $B$ collectively establishes \begin{align} \sum_{h=1}^{H}\left(1+\frac{1}{H}\right)^{h-1}I_{h}\leq A+B\lesssim H^{2}SC^{\star}\iota+\sqrt{H^{5}SC^{\star}K\iota^{3}}. \label{eq:lcb-Ih-bound} \end{align} \paragraph{Step 2: putting everything together.} Combining \eqref{eq:lcb-lemma3-first-term} and \eqref{eq:lcb-Ih-bound} allows us to establish that \begin{align*} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1}\left( I_h + 16\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 8HC^\star\log\frac{2H}{\delta}\right) \lesssim H^{2}SC^{\star}\iota+\sqrt{H^{5}SC^{\star}K\iota^{3}}, \end{align*} as advertised. \section{Proof of lemmas for {\sf LCB-Q-Advantage}\xspace (Theorem~\ref{thm:lcb-adv})}\label{proof:lcb-adv-lemmas} \paragraph{Additional notation for {\sf LCB-Q-Advantage}\xspace.}\label{para:lcb-adv-add-notation} Let us also introduce, and remind the reader of, several notation of interest in Algorithm~\ref{alg:lcb-advantage-per-epoch-k} as follows. \begin{itemize} \item $N_h^{k}(s,a)$ (resp.~$N_h^{(m,t)}(s,a)$) denotes the value of $N_h(s,a)$ --- the number of episodes that has visited $(s,a)$ at step $h$ at the {\em beginning} of the $k$-th episode (resp.~the {\em beginning} of $t$-th episode of the $m$-th epoch); for the sake of conciseness, we shall often abbreviate $N_h^k = N_h^k(s,a)$ (resp.~$N_h^{(m,t)} = N_h^{(m,t)}(s,a)$) when it is clear from context. \item $L_m=2^m $: the total number of in-epoch episodes in the $m$-th epoch. \item $k^n_h(s,a)$: the index of the episode in which $(s, a)$ is visited for the $n$-th time at time step $h$; $\left(m^n_h(s,a), t^n_h(s, a)\right)$ denote respectively the index of the epoch and that of the in-epoch episode in which $(s, a)$ is visited for the $n$-th time at step $h$; for the sake of conciseness, we shall often use the shorthand $k^n = k^n_h(s,a)$, $(m^n,k^n) = \left(m^n_h(s,a), k^n_h(s, a)\right)$ whenever it is clear from context. \item $Q_h^{k}(s, a)$, $Q_h^{{\sf LCB}\xspace, k}(s, a)$, $\overline{Q}_h^{k}(s, a)$ and $V_h^{k}(s)$ are used to denote $Q_h(s, a)$, $Q_h^{{\sf LCB}\xspace}(s, a)$, $\overline{Q}_h(s, a)$, and $V_h(s)$ at the {\em beginning} of the $k$-th episode, respectively. \item $\overline{V}_h^{k}(s), \overline{V}_h^{\mathsf{next}, k}(s), \overline{\mu}^{k}_h(s,a), \overline{\mu}^{\mathsf{next},k}_h(s,a)$ denote the values of $\overline{V}_h(s), \overline{V}^{\mathsf{next}}_h(s), \overline{\mu}_h(s,a)$ and $\overline{\mu}^{\mathsf{next}}_h(s,a)$ at the {\em beginning} of the $k$-th episode, respectively. \item $\widehat{N}_h^{(m,t)}(s,a)$ represents $\widehat{N}_h(s,a)$ at the {\em beginning} of the $t$-th in-epoch episode in the $m$-th epoch. \item $\widehat{N}_h^{\mathsf{epo}, m}(s,a)$ denotes $\widehat{N}_h^{(m, L_m+1)}(s,a)$, representing the number of visits to $(s,a)$ in the entire duration of the $m$-th epoch. \item $[\mu^{\mathsf{ref}, k}_h, \sigma^{\mathsf{ref}, k}_h, \mu^{\mathsf{adv},k}_h, \sigma^{\mathsf{adv}, k}_h, \overline{\delta}^{k}_h, \overline{B}^{k}_h, \overline{b}_h^{k}]$: the values of $[\mu^{\mathsf{ref}}_h, \sigma^{\mathsf{ref}}_h, \mu^{\mathsf{adv}}_h, \sigma^{\mathsf{adv}}_h, \overline{\delta}_h, \overline{B}_h, \overline{b}_h]$ at the {\em beginning} of the $k$-th episode, respectively. \end{itemize} In addition, for a fixed vector $V \in \mathbb{R}^{|\mathcal{S}|}$, let us define a variance parameter with respect to $P_{h,s,a}$ as follows \begin{equation} \label{lemma1:equ2} \mathsf{Var}_{h, s, a}(V) \coloneqq \mathop{\mathbb{E}}\limits_{s' \sim P_{h,s,a}} \Big [\big(V(s') - P_{h,s, a}V \big)^2\Big] = P_{h,s,a} (V^{ 2}) - (P_{h,s,a}V)^2. \end{equation} This notation will be useful in the subsequent proof. We remind the reader that there exists a one-to-one mapping between the index of the episode $k$ and the index pair $(m,t)$ (i.e., the epoch $m$ and in-epoch episode $t$), as specified in \eqref{eqn:k-to-m-t}. In the following, for any episode $k$, we recall the expressions of $\overline{V}_{h+1}$ and $\overline{\mu}_h$ (which is the running mean of $\overline{V}_{h+1}$). \begin{itemize} \item Recalling the update rule of $\overline{V}_h$ and $\overline{V}^{\mathsf{next}}_h$ in line~\ref{eq:update-mu-reference-v-k} and line~\ref{eq:update-mu-reference-v-next-k} of Algorithm~\ref{alg:lcb-advantage-per-epoch-k}, we observe that both the reference values for the current epoch $\overline{V}_h$ and for the next epoch $\overline{V}^{\mathsf{next}}_h$ remain unchanged within each epoch. Additionally, for any epoch $m$, $\overline{V}_h$ takes the value of $\overline{V}^{\mathsf{next}}_h$ in the previous $(m-1)$-th epoch; namely, for any episode $k$ happening in the $m$-th epoch, we have \begin{align}\label{eq:v-to-v-next} \overline{V}_h^{k} &= \overline{V}^{\mathsf{next}, k'}_h \end{align} for all episode $k'$ within the $(m-1)$-th epoch. \item $\overline{\mu}^k_h$ serves as the estimate of $ P_{h,s,a}\overline{V}^k_{h+1}$ constructed by the samples in the previous $(m-1)$-th epoch (collected by updating $\overline{\mu}^{\mathsf{next}}_h$). Recall the update rule of $\overline{\mu}_h$ in line~\ref{eq:update-mu-reference-v-k} and line~\ref{line:ref-mean-update-k} of Algorithm~\ref{alg:lcb-advantage-per-epoch-k}: for any $(s,a,h) \in {\mathcal{S}}\times \mathcal{A}\times [H]$, we can write $\overline{\mu}^k_h$ as \begin{align} \overline{\mu}_h^k(s,a) &= \overline{\mu}_h^{(m,1)} (s,a) = \overline{\mu}_h^{\mathsf{next}, (m,1)}(s,a) = \overline{\mu}_h^{\mathsf{next}, (m-1,L_{m-1})}(s,a) \nonumber \\ &= \frac{\sum_{i= N_h^{(m-1,1)} + 1 }^{ N_h^{(m,1)}} \overline{V}^{\mathsf{next}, k^i}_{h+1}(s^{k^i}_{h+1})}{\widehat{N}_h^{\mathsf{epo}, m-1}(s,a) \vee 1} = \frac{\sum_{i= N_h^{(m-1,1)} + 1 }^{ N_h^{(m,1)}} \overline{V}^k_{h+1}(s^{k^i}_{h+1})}{\widehat{N}_h^{\mathsf{epo}, m-1}(s,a) \vee 1} ,\label{equ:definition-ref-refmean} \end{align} where the last equality follows from \eqref{eq:v-to-v-next} using the fact that the indices of episodes in which $(s,a)$ is visited within the $(m-1)$-th epoch are $\{i: i = N_h^{(m-1,1)}+1, N_h^{(m-1,1)}+2,\cdots,N_h^{(m,1)}\}$. \end{itemize} Finally, according to the update rules of $\mu^{\mathsf{adv}, k^{n+1}}_h(s^k_h, a^k_h)$ and $\sigma^{\mathsf{adv}, k^{n+1}}_h(s^k_h, a^k_h) $ in lines~\ref{line:advmu_h}-\ref{line:advsigma_h} of Algorithm~\ref{algo:subroutine}, we have \begin{align*} \mu^{\mathsf{adv}, k^{n+1}}_h(s^k_h, a^k_h) &= \mu^{\mathsf{adv}, k^n+1}_h(s^k_h, a^k_h) = (1-\eta_n)\mu^{\mathsf{adv}, k^n}_h(s^k_h, a^k_h) + \eta_n \big(V^{k^n}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{k^n}_{h+1}(s^{k^n}_{h+1}) \big) ,\\ \sigma^{\mathsf{adv}, k^{n+1}}_h(s^k_h, a^k_h) &= \sigma^{\mathsf{adv}, k^n+1}_h(s^k_h, a^k_h) = (1-\eta_n)\sigma^{\mathsf{adv}, k^n}_h(s^k_h, a^k_h) + \eta_n \big( V^{k^n}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{k^n}_{h+1}(s^{k^n}_{h+1}) \big)^2. \end{align*} Applying this relation recursively and invoking the definitions of $\eta_n^{N_h^k}$ in \eqref{equ:learning rate notation} give \begin{align}\label{eq:recursion_mu_sigma_adv} \mu_h^{\mathsf{adv}, k^{N_h^k}+1}(s,a) &= \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} P_h^{k^n} \big(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n} \big), \;\; {\sigma}_h^{\mathsf{adv}, k^{N_h^k}+1}(s,a) = \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P_h^{k^n} \big(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n} \big)^2. \end{align} Similarly, according to the update rules of ${\mu}^{\mathsf{ref}, k^{n+1}}_h(s,a)$ and ${\sigma}^{\mathsf{ref}, k^{n+1}}_h(s, a) $ in lines~\ref{line:refmu_h}-\ref{line:refsigma_h} of Algorithm~\ref{algo:subroutine}, we obtain \begin{align*} {\mu}^{\mathsf{ref}, k^{n+1}}_h(s,a) &= {\mu}^{\mathsf{ref}, k^n+1}_h(s,a) = \left(1-\frac{1}{n}\right) {\mu}^{\mathsf{ref}, k^n}_h(s,a) + \frac{1}{n} \overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{k^n}_{h+1}), \\ {\sigma}^{\mathsf{ref}, k^{n+1}}_h(s,a) &= {\sigma}^{\mathsf{ref}, k^n+1}_h(s,a) = \left(1-\frac{1}{n}\right){\sigma}^{\mathsf{ref}, k^n}_h(s,a) + \frac{1}{n}\left(\overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{k^n}_{h+1})\right)^2. \end{align*} Simple recursion leads to \begin{align}\label{eq:recursion_mu_sigma_ref} {\mu}_h^{\mathsf{ref}, k^{N_h^k}+1}(s,a) &=\frac{1}{N_h^k} \sum_{n=1}^{N_h^k} P_h^{k^n} \overline{V}_{h+1}^{\mathsf{next},k^n},\quad {\sigma}_h^{\mathsf{ref}, k^{N_h^k}+1}(s,a) = \frac{1}{N_h^k} \sum_{n = 1}^{{N_h^k}} P_h^{k^n}\big(\overline{V}_{h+1}^{\mathsf{next}, k^n}\big)^2. \end{align} \subsection{Proof of Lemma~\ref{lem:lcb-adv-lower}}\label{proof:lemma-mono-lcb-adv} Akin to the proof of Lemma~\ref{lem:Vk-lower}, the second inequality of \eqref{eq:lcb-adv-lower} holds trivially since \begin{equation*} V_h^{\pi}(s) \leq V_h^\star(s) \end{equation*} holds for any policy $\pi$. Thus, it suffices to focus on justifying the first inequality of \eqref{eq:lcb-adv-lower}, namely, \begin{equation}\label{eq:lcb-adv-lower-induction} V_{h}^{k}(s) \leq V_{h}^{\pi^{k}}(s) \qquad \forall (k,h,s) \in [K] \times [H] \times{\mathcal{S}}, \end{equation} which we shall prove by induction. \paragraph{Step 1: introducing the induction hypothesis.} For notational simplicity, let us define \begin{align} k_o(h,k,s) \coloneqq \max\left\{l: l< k \text{ and } V_h^{l}(s) = \max_a \max\left\{ Q_h^{{\sf LCB}\xspace, l}(s,a), \overline{Q}_h^{l}(s,a)\right\} \right\} \label{eq:lcb-adv-k0-def} \end{align} for any $(h,k,s)\in[H]\times[K]\times{\mathcal{S}}$. Here, $k_o(h,k,s)$ denotes the index of the latest episode --- right at the end of the $(k-1)$-th episode --- in which $V_h(s)$ has been updated, which shall be abbreviated as $k_o(h)$ whenever it is clear from context. In what follows, we shall first justify the advertised inequality for the base case where $h=H+1$ for all episodes $k\in [K]$, followed by an induction argument. Regarding the induction part, let us consider any $k\in[K]$ and any $h\in [H]$, and suppose that \begin{subequations}\label{eq:lcb-adv-lower-indunction-assumption-12} \begin{align} V_{h'}^{k'}(s) &\leq V_{h'}^{\pi^{k'}}(s) \qquad \text{for all } (k',h',s) \in [k-1]\times [H+1]\times {\mathcal{S}}, \label{eq:lcb-adv-lower-indunction-assumption2}\\ V_{h'}^k(s) &\leq V_{h'}^{\pi^k}(s) \qquad \text{for all } h'\geq h+1\text{ and }s\in{\mathcal{S}}. \label{eq:lcb-adv-lower-indunction-assumption} \end{align} \end{subequations} We intend to justify \begin{equation}\label{eq:lcb-adv-lower-induction2} V_{h}^{k}(s) \leq V_{h}^{\pi^{k}}(s) \qquad \forall s \in {\mathcal{S}}, \end{equation} assuming that the induction hypotheses \eqref{eq:lcb-adv-lower-indunction-assumption-12} hold. \paragraph{Step 2: controlling the confident bound $\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h$.} Before proceeding, we first introduce an auxiliary result on bounding $\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h$, which plays a crucial role. For any $(s,a)$, it is easily seen that \begin{align} N_h^k(s,a) = 0 \qquad \Longrightarrow \qquad \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \overline{b}_h^{k^n(s,a)+1} = 0. \label{eq:N-zero-case} \end{align} When $N_h^k(s,a) >0$, expanding the definitions of $\overline{b}^{k^n+1}_h$ (cf.~line~\ref{line:bonus_2} of Algorithm~\ref{algo:subroutine}) and $\overline{\delta}_h^{k+1}$ (cf.~line~\ref{eq:line-delta} of Algorithm~\ref{algo:subroutine}) leads to \begin{align} & \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h \nonumber \\ &=\sum_{n = 1}^{N_h^k} \eta_n \prod_{i = n+1}^{N_h^k}(1-\eta_i) \cdot \left( \Big(1-\frac{1}{\eta_n}\Big) \overline{B}^{k^n}_h(s,a) + \frac{1}{\eta_n} \overline{B}^{k^n+1}_h(s,a) \right) + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n^{3/4}} H^{7/4}\iota + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n} H^2\iota\nonumber \\ &= \sum_{n = 1}^{N_h^k} \left(\prod_{i = n+1}^{N_h^k}(1-\eta_i) \overline{B}^{k^n+1}_h(s,a) - \prod_{i = n}^{N_h^k}(1-\eta_i) \overline{B}^{k^n}_h(s,a)\right) + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n^{3/4}} H^{7/4}\iota + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n} H^2\iota\nonumber \\ &\overset{\mathrm{(i)}}{=} \sum_{n=1}^{N_h^k} \prod_{i = n+1}^{N_h^k}(1-\eta_i) \overline{B}^{k^n+1}_h(s,a) - \sum_{n=2}^{N_h^k} \prod_{i = n}^{N_h^k}(1-\eta_i) \overline{B}^{k^n}_h(s,a) + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n^{3/4}} H^{7/4}\iota + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n} H^2\iota\nonumber \\ &\overset{\mathrm{(ii)}}{=}\sum_{n=1}^{N_h^k} \prod_{i = n+1}^{N_h^k}(1-\eta_i) \overline{B}^{k^n+1}_h(s,a) - \sum_{n=1}^{N_h^k-1} \prod_{i = n+1}^{N_h^k}(1-\eta_i) \overline{B}^{k^n+1}_h(s,a) + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n^{3/4}} H^{7/4}\iota + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n} H^2\iota\nonumber \\ &=\overline{B}^{k^{N_h^k}+1}_h(s,a) + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n^{3/4}} H^{7/4}\iota + c_{\mathrm{b}} \sum_{n=1}^{N_h^k}\frac{ \eta_n^{N_h^k} }{n} H^2\iota, \label{eq:lcb-adv-b-boundby-B} \end{align} where we abuse the notation to let $\prod_{i=j+1}^j (1-\eta_i)=1$. Here, (i) holds since $\overline{B}^{k^1}(s,a) = 0$, (ii) follows from the fact that $\overline{B}^{k^n+1}(s,a) = \overline{B}^{k^{n+1}}(s,a)$, since $(s,a)$ has not been visited at step $h$ during the episodes between the indices $k^n +1$ and $k^{n+1} - 1$. Combining the above result in \eqref{eq:lcb-adv-b-boundby-B} with the properties $\frac{1}{(N_h^k)^{3/4}} \le \sum_{n = 1}^{N_h^k} \frac{\eta^{N_h^k}_n}{n^{3/4}} \le \frac{2}{(N_h^k)^{3/4}}$ and $\frac{1}{N_h^k} \le \sum_{n = 1}^{N_h^k} \frac{\eta^{N_h^k}_n}{n} \le \frac{2}{N_h^k}$ (see Lemma~\ref{lemma:property of learning rate}), we arrive at \begin{equation} \label{lemma1:equ10} \overline{B}^{k^{N_h^k}+1}_h(s,a) + c_{\mathrm{b}}\frac{H^{7/4}\iota}{(N_h^k)^{3/4}} + c_{\mathrm{b}} \frac{H^2\iota}{N_h^k} \le \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h \le \overline{B}^{k^{N_h^k}+1}_h(s,a) + 2c_{\mathrm{b}}\frac{H^{7/4}\iota}{(N_h^k)^{3/4}} + 2c_{\mathrm{b}} \frac{H^2\iota}{N_h^k} \end{equation} as long as $N_h^k(s,a) > 0$. \paragraph{Step 3: base case.} Let us look at the base case with $h=H+1$ for any $k\in[K]$. Recalling the facts that $V_{H+1}^{\pi}=V_{H+1}^{k}=0$ for any $\pi$ and any $k\in[K]$, we reach \begin{align} V_{H+1}^k(s) &\leq V_{H+1}^{\pi^k}(s) \qquad \text{for all } (k,s)\in [K] \times {\mathcal{S}}. \end{align} \paragraph{Step 4: induction arguments.} We now turn to the induction arguments. Suppose that \eqref{eq:lcb-adv-lower-indunction-assumption-12} holds for a pair $(k,h)\in [K]\times [H]$. Everything comes down to justifying \eqref{eq:lcb-adv-lower-induction2} for time step $h$ in the episode $k$. First, we recall the update rule of $V_h(s)$ in lines~\ref{eq:line-q-update-k}-\ref{eq:line-v-update-k} of Algorithm~\ref{alg:lcb-advantage-per-epoch-k}: \begin{align*} &V^k_h(s) = \max_a Q^k_h(s, a) = Q^k_h\big(s, \pi_h^k(s) \big) = \max \left\{Q^{{\sf LCB}\xspace,k}_h \left(s, \pi_h^k(s)\right), \overline{Q}^k_h\left(s, \pi_H^k(s)\right), Q^{k-1}_h\left(s, \pi_h^k(s)\right) \right\}. \end{align*} Then we shall verify \eqref{eq:lcb-adv-lower-induction2} in three different cases. \begin{itemize} \item When $V^k_h(s) = Q^{{\sf LCB}\xspace,k}_h \left(s, \pi_h^k(s)\right)$, the term of interest can be controlled by \begin{align*} V_{h}^{\pi^k}(s) - V_{h}^k(s) \overset{\mathrm{(i)}}{=} Q_{h}^{\pi^k}\left(s,\pi_h^k(s)\right) - Q^{{\sf LCB}\xspace,k}_h\left(s, \pi_h^k(s)\right) \geq 0, \end{align*} where (i) holds since $\pi^k$ is set to be the greedy policy such that $V_h^{\pi^k}(s) = Q_h^{\pi^k}(s, \pi_h^k(s)),$ and the last inequality follows directly from the analysis for {\sf LCB-Q}\xspace (see \eqref{equ:lcb-lower-induction-result}). \item When $V^k_h(s) = \overline{Q}^k_h \left(s, \pi_h^k(s)\right)$, we obtain \begin{align} V_{h}^{\pi^k}(s) - V_{h}^k(s) = Q_{h}^{\pi^k}\left(s,\pi_h^k(s)\right) - \overline{Q}^k_h\left(s, \pi_h^k(s)\right). \label{eq:V2Q-lcb-adv} \end{align} To prove the term on the right-hand side of \eqref{eq:V2Q-lcb-adv} is non-negative, we proceed by developing a more general lower bound on $Q_{h}^{\pi^k}(s, a) - \overline{Q}_{h}^k(s, a)$ for every $(s,a) \in {\mathcal{S}} \times \mathcal{A}$. Towards this, recalling the definition of $N_h^k$ and $k^n$, we can express \begin{align*} \overline{Q}_{h}^k(s,a) = \overline{Q}_{h}^{k^{N_h^k} + 1}(s,a). \end{align*} Thus, according to the update rule (cf. line~\ref{line:ref-q-update} in Algorithm~\ref{algo:subroutine}), we arrive at \begin{align*} \overline{Q}_{h}^k(s,a) & = \overline{Q}_{h}^{k^{N_h^k}+1}(s,a) \\ & =(1-\eta_{N_h^k}) \overline{Q}_{h}^{k^{N_h^k}}(s,a) +\eta_{N_h^k}\bigg\{ r_{h}(s,a)+V_{h+1}^{k^{N_h^k}}(s_{h+1}^{k^{N_h^k}})- \overline{V}_{h+1}^{k^{N_h^k}}(s_{h+1}^{k^{N_h^k}})+ \overline{\mu}_{h}^{k^{N_h^k}}(s,a) - \overline{b}_h^{k^{N_h^k} + 1}\bigg\}. \end{align*} Applying this relation recursively and invoking the definitions of $\eta_0^{N_h^k}$ and $\eta_n^{N_h^k}$ in \eqref{equ:learning rate notation} give \begin{align} &\overline{Q}^k_h(s,a) = \eta_0^{N_h^k} \overline{Q}^{1}_h(s,a) + \sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} \bigg\{ r_h(s,a) + V^{k^n}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{ k^n}_{h+1}(s^{k^n}_{h+1}) + \overline{\mu}_{h}^{k^n}(s,a) - \overline{b}^{k^n+1}_h \bigg\}. \label{eq:Q-ref-decompose-12345} \end{align} Additionally, for any policy $\pi^k$, the basic relation $\eta_0^{N_h^k} + \sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} = 1$ (see \eqref{eq:sum-eta-n-N} and \eqref{equ:learning rate notation}) gives \begin{equation}\label{eq:decomp_Qhpi_eta} Q_{h}^{\pi^k} (s,a) = \eta^{N_h^k}_0 Q_{h}^{\pi^k} (s,a) + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n Q_{h}^{\pi^k} (s,a). \end{equation} Combing \eqref{eq:Q-ref-decompose-12345} and \eqref{eq:decomp_Qhpi_eta} leads to \begin{align} & Q_{h}^{\pi^k}(s,a) - \overline{Q}_{h}^k(s,a) =\eta_{0}^{N_h^k}\big(Q_{h}^{\pi^k}(s,a)- \overline{Q}_{h}^{1}(s,a)\big)\nonumber\\ & \qquad+\sum_{n=1}^{N_h^k}\eta_{n}^{N_h^k}\bigg\{Q_{h}^{\pi^k}(s,a) - r_{h}(s,a) - V_{h+1}^{k^n}(s_{h+1}^{k^n}) + \overline{V}_{h+1}^{k^n}(s_{h+1}^{k^n}) - \overline{\mu}_{h}^{k^n}(s,a) + \overline{b}_h^{k^n+1} \bigg\}. \label{equ:lemma4 vr 1} \end{align} Plugging in the construction of $\overline{\mu}_h$ in \eqref{equ:definition-ref-refmean} and invoking the Bellman equation \begin{equation}\label{equ:bellman-equ} Q_{h}^{\pi^k}(s, a) = r_h(s, a) + P_{h,s, a }V_{h+1}^{\pi^k}, \end{equation} we arrive at \begin{align} &Q_{h}^{\pi^k}(s,a) - r_{h}(s,a) - V_{h+1}^{k^n}(s_{h+1}^{k^n}) + \overline{V}_{h+1}^{k^n}(s_{h+1}^{k^n}) - \overline{\mu}_{h}^{k^n}(s,a) + \overline{b}_h^{k^n+1} \nonumber \\ &\quad = P_{h,s,a} V_{h+1}^{\pi^k} + \overline{V}^{ k^n}_{h+1}(s^{k^n}_{h+1}) - V^{k^n}_{h+1}(s^{k^n}_{h+1}) - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} \overline{V}^{k^n}_{h+1}(s^{k^i}_{h+1})}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} + \overline{b}^{k^n+1}_h \nonumber \\ &\quad = P_{h,s,a} V_{h+1}^{\pi^k} - V^{k^n}_{h+1}(s^{k^n}_{h+1}) + \left(P_h^{k^n} - P_{h,s,a}\right) \overline{V}^{ k^n}_{h+1}\label{eq:dejavu}+ \left(P_{h,s,a} - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \right)\overline{V}^{ k^n}_{h+1} + \overline{b}^{k^n+1}_h \nonumber\\ &\quad = P_{h, s,a}\left( V_{h+1}^{\pi^k} - V^{k^n}_{h+1}\right) + \overline{b}^{k^n+1}_h + \xi^{k^n}_h, \nonumber \end{align} where \begin{equation} \xi^{k^n}_h \coloneqq \big(P^{k^n}_{h} - P_{h, s,a} \big)\big(\overline{V}^{ k^n}_{h+1} - V^{k^n}_{h+1} \big) + \left(P_{h,s,a} - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \right)\overline{V}^{ k^n}_{h+1}. \label{eq:defn-xi-kh-123} \end{equation} Inserting the above result into \eqref{equ:lemma4 vr 1} leads to the following decomposition \begin{align} Q_{h}^{\pi^k}(s,a) - \overline{Q}_{h}^k(s,a) & = \eta_{0}^{N_h^k}\big(Q_{h}^{\pi^k}(s,a)- \overline{Q}_{h}^{1}(s,a)\big)+ \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \bigg\{ P_{h, s,a} \left( V_{h+1}^{\pi^k} - V^{k^n}_{h+1} \right) + \overline{b}^{k^n+1}_h + \xi^{k^n}_h \bigg\} \label{equ:concise-update-no-bound}\\ &\geq \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n (\overline{b}^{k^n+1}_h + \xi^{k^n}_h ), \label{equ:concise update} \end{align} which holds by virtue of the following facts: \begin{itemize} \item [(i)] The initialization $\overline{Q}_{h}^{1}(s,a) = 0$ and the non-negativity of $Q_h^{\pi}(s,a)$ for any policy $\pi$ and $(s,a)\in {\mathcal{S}}\times \mathcal{A}$ lead to $Q_{h}^{\pi^k}(s,a)- \overline{Q}_{h}^{1}(s,a) = Q_{h}^{\pi^k}(s,a) \geq 0$. \item [(ii)] For any episode $k^n$ appearing before $k$, making use of the induction hypothesis $V_{h+1}^{\pi^k}(s) \geq V_{h+1}^k(s) $ in \eqref{eq:lcb-adv-lower-indunction-assumption} and the monotonicity of $V_h(s)$ in \eqref{equ:monotone-lcb-adv}, we obtain \begin{equation} V_{h+1}^{\pi^k}(s) - V^{k^n}_{h+1}(s) \geq V_{h+1}^k(s) - V^{k^n}_{h+1}(s) \geq 0. \end{equation} \end{itemize} The following lemma ensures that the right-hand side of \eqref{equ:concise update} is non-negative. We postpone the proof of Lemma~\ref{lem:lcb-adv-bonus-upper} to Appendix~\ref{proof:lem:lcb-adv-bonus-upper} to streamline our discussion. \begin{lemma} \label{lem:lcb-adv-bonus-upper} For any $\delta \in (0, 1)$, there exists some sufficiently large constant $c_{\mathrm{b}} >0$, such that with probability at least $1-\delta$, \begin{equation} \bigg| \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \xi_h^{k^n} \bigg| \le \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h , \qquad \forall k\in[K]. \label{eq:claim-sum-eta-sum-b} \end{equation} \end{lemma} Taking this lemma together with the inequalities \eqref{eq:V2Q-lcb-adv} and \eqref{equ:concise update} yields \begin{align*} V_{h}^{\pi^k}(s) - V_{h}^k(s) = Q_{h}^{\pi^k}(s,a) - \overline{Q}_{h}^k(s,a) \geq \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h - \bigg| \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \xi^{k^n}_h \bigg| \geq 0. \end{align*} \item Next, consider the case where $V^k_h(s) = Q^{k-1}_h\left(s, \pi_h^k(s)\right)$. In view of the definition of $k_o(h)$ in \eqref{eq:lcb-adv-k0-def}, one has \begin{align*} V^k_h(s) &= Q^{k-1}_h\left(s, \pi_h^k(s)\right) = Q^{k_o(h)}_h\left(s, \pi_h^k(s)\right)= \max \left\{Q^{{\sf LCB}\xspace,k_o(h)}_h \left(s, \pi_h^k(s)\right), \overline{Q}^{k_o(h)}_h\left(s, \pi_h^k(s)\right)\right\}, \end{align*} since $Q_h\left(s, \pi_h^k(s)\right)$ has not been updated during the episode $k_o(h)$ and remains unchanged in the episodes $k_o(h)+1,k_o(h)+2,\cdots, k-1$. With this equality in hand, the term of interest in \eqref{eq:lcb-adv-lower-induction2} can be controlled by \begin{align*} &V_{h}^{\pi^k}(s) - V_{h}^k(s)= Q_h^{\pi^k}(s, \pi_h^k(s)) - \max \left\{Q^{{\sf LCB}\xspace,k_o(h)}_h \left(s, \pi_h^k(s)\right), \overline{Q}^{k_o(h)}_h\left(s, \pi_h^k(s)\right)\right\} \geq 0, \end{align*} where the last inequality follows from the facts \begin{align*} Q_{h}^{\pi^k}(s, \pi_h^k(s)) - Q_{h}^{{\sf LCB}\xspace, k_o(h)}(s, \pi_h^k(s))& \overset{\mathrm{(i)}}{\geq} 0,\\ Q_{h}^{\pi^k}(s, \pi_h^k(s)) - \overline{Q}_{h}^{k_o(h)}(s, \pi_h^k(s)) &\overset{\mathrm{(ii)}}{\geq} 0. \end{align*} Here, (i) follows from the same analysis framework for showing \eqref{equ:lcb-lower-1} and \eqref{equ:lcb-lower-new-1}; (ii) holds due to the following fact \begin{align*} Q_{h}^{\pi^k}(s,a) - \overline{Q}_{h}^{k_o(h)}(s,a) \geq \sum_{n = 1}^{N_h^{k_o(h)}} \eta^{N_h^{k_o(h)}}_n (\overline{b}^{k^n+1}_h + \xi^{k^n}_h ) \geq 0, \end{align*} which is obtained directly by adapting \eqref{equ:concise update} and then invoking \eqref{eq:claim-sum-eta-sum-b} for $k = k_o(h)$; since the analysis follows verbatim, we omit their proofs here. \end{itemize} Combining the above three cases verifies the induction hypothesis in \eqref{eq:lcb-adv-lower-induction2}, provided that \eqref{eq:lcb-adv-lower-indunction-assumption-12} is satisfied. \paragraph{Step 5: putting everything together.} Combining the base case in Step 3 and induction arguments in Step 4, we can readily verify the induction hypothesis in Step 1, which in turn establishes Lemma~\ref{lem:lcb-adv-lower}. \subsection{Proof of Lemma~\ref{lem:lcb-adv-each-h}}\label{proof:lem:lcb-adv-decompose} For every $h\in [H]$, we can decompose \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \nonumber &\overset{\mathrm{(i)}}{\leq} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}\big(s, \pi_h^\star(s)\big) \left(Q_h^\star\big(s, \pi_h^\star(s)\big) - \overline{Q}_h^{k}\big(s, \pi_h^\star(s)\big)\right) \nonumber\\ & = \sum_{k=1}^K \sum_{s, a\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \left(Q_h^\star(s, a) - \overline{Q}_h^{k}(s, a)\right),\label{equ:lcb-adv-rewrite} \end{align} where (i) follows from the fact $V_h^{k}(s) =\max_a Q_h^k(s,a) \geq \max_a \overline{Q}_h^k(s,a) \geq \overline{Q}_h^{k}(s, \pi_h^\star(s))$ (see lines~\ref{eq:line-q-update-k}-\ref{eq:line-v-update-k} in Algorithm~\ref{alg:lcb-advantage-per-epoch-k}). Here, the last equality is due to \eqref{eq:d_h_pi_star}. \paragraph{Step 1: bounding $Q_{h}^{\star}(s,a) - \overline{Q}_{h}^{k}(s,a)$.} The basic relation $\eta_0^{N_h^k} + \sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} = 1$ (see \eqref{eq:sum-eta-n-N} and \eqref{equ:learning rate notation}) gives \begin{equation}\label{eq:decomp_Qhstar_eta} Q_{h}^{\star} (s,a) = \eta^{N_h^k}_0 Q_{h}^{\star} (s,a) + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n Q_{h}^{\star} (s,a), \end{equation} which combined with \eqref{eq:Q-ref-decompose-12345} leads to \begin{align} & Q_{h}^{\star}(s,a) - \overline{Q}_{h}^{k}(s,a) =\eta_{0}^{N_h^k}\big(Q_{h}^{\star}(s,a)- \overline{Q}_{h}^{1}(s,a)\big)\nonumber\\ & \qquad+\sum_{n=1}^{N_h^k}\eta_{n}^{N_h^k}\bigg\{Q_{h}^{\star}(s,a) - r_{h}(s,a) - V_{h+1}^{k^n}(s_{h+1}^{k^n}) + \overline{V}_{h+1}^{k^n}(s_{h+1}^{k^n}) - \overline{\mu}_{h}^{k^n}(s,a) + \overline{b}_{h}^{k^n+1} \bigg\}. \label{equ:lemma4 vr 1 adv} \end{align} Invoking the Bellman optimality equation \begin{equation} Q_{h}^{\star}(s, a) = r_h(s, a) + P_{h,s, a }V_{h+1}^{\star}, \end{equation} we can decompose $Q_{h}^{\star}(s,a) - \overline{Q}_{h}^{k}(s,a)$ similar to \eqref{equ:concise-update-no-bound} by inserting \eqref{eq:defn-xi-kh-123} as follows: \begin{align} &Q_{h}^{\star}(s,a) - \overline{Q}_{h}^{k}(s,a) = \eta_{0}^{N_h^k}\big(Q_{h}^{\star}(s,a)-\overline{Q}_{h}^{1}(s,a)\big) + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \bigg\{ P_{h, s,a}\left( V_{h+1}^{\star} - V^{k^n}_{h+1}\right) + \overline{b}^{k^n+1}_h + \xi^{k^n}_h \bigg\} \nonumber\\ &\overset{\mathrm{(i)}}{\leq} \eta_{0}^{N_h^k} H + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \left(\overline{b}^{k^n+1}_h + \xi^{k^n}_h\right) + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n P_{h, s,a}\left( V_{h+1}^{\star} - V^{k^n}_{h+1}\right) \nonumber\\ &\overset{\mathrm{(ii)}}{\leq} \eta_{0}^{N_h^k} H + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n P_{h, s,a}\left( V_{h+1}^{\star} - V^{k^n}_{h+1}\right) + 2\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h \nonumber \\ & \overset{\mathrm{(iii )}}{\leq} \eta_{0}^{N_h^k} H + \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n P_{h, s,a}\left( V_{h+1}^{\star} - V^{k^n}_{h+1}\right) + 2\left(\overline{B}^{k}_h(s,a) + 2c_{\mathrm{b}}\frac{H^{7/4}\iota}{\left(N_h^k \vee 1\right)^{3/4}} + 2c_{\mathrm{b}} \frac{H^2\iota}{N_h^k \vee 1} \right), \label{eq:lcb-adv-Q-upper} \end{align} where (i) follows from the initialization $\overline{Q}_{h}^{1}(s,a) = 0$ and the trivial upper bound $Q_{h}^{\pi}(s,a)\leq H$ for any policy $\pi$, (ii) holds owing to the fact (see \eqref{eq:claim-sum-eta-sum-b}) \begin{align} \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \left(\overline{b}^{k^n+1}_h + \xi^{k^n}_h\right) \leq \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n\overline{b}^{k^n+1}_h + \bigg| \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \xi^{k^n}_h \bigg| \leq 2\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h, \end{align} and (iii) comes from \eqref{lemma1:equ10} with the fact $\overline{B}^{k^{N_h^k}+1}_h(s,a) = \overline{B}^{k}_h(s,a)$. \paragraph{Step 2: decomposing the error in \eqref{equ:lcb-adv-rewrite}.} Plugging \eqref{eq:lcb-adv-Q-upper} into \eqref{equ:lcb-adv-rewrite} and rearranging terms yield \begin{align} &\sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right)\\ & \leq \sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\left[\eta_0^{N_h^k(s,a)}H + 2\overline{B}_h^{k}(s,a) + \frac{4 c_{\mathrm{b}} H^{7/4}\iota}{\left(N_h^k(s,a) \vee 1\right)^{3/4}} + \frac{4c_{\mathrm{b}} H^2\iota}{N_h^k(s,a) \vee 1} \right] \nonumber\\ & \quad + \sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)}\left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right) \nonumber \\ &\leq \underbrace{\sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\left[\eta_0^{N_h^k(s,a)}H + \frac{4 c_{\mathrm{b}} H^{7/4}\iota}{\left(N_h^k(s,a) \vee 1\right)^{3/4}} + \frac{4c_{\mathrm{b}} H^2\iota}{N_h^k(s,a) \vee 1}\right]}_{=: J_h^1} + \underbrace{2\sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\overline{B}_h^{k}(s,a)}_{=: J_h^2} \nonumber \\ &\quad + \sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)}\left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right). \label{equ:lcb-adv-recursion} \end{align} \paragraph{Step 3: controlling the last term in \eqref{equ:lcb-adv-recursion}.} If we could verify the following result \begin{align} &\sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)}\left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right) \nonumber \\ &\leq \underbrace{\left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + 48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2}_{\eqqcolon J_h^3}, \label{eq:lcb-adv-recursion-key} \end{align} then combining this result with inequality~\eqref{equ:lcb-adv-recursion} would immediately establish Lemma~\ref{lem:lcb-adv-each-h}. As a result, it suffices to verify the inequality~\eqref{eq:lcb-adv-recursion-key}, which shall be accomplished as follows. \paragraph{Proof of inequality~\eqref{eq:lcb-adv-recursion-key}.} We first make the observation that the left-hand side of inequality~\eqref{eq:lcb-adv-recursion-key} is the same as what Lemma~\ref{lemma:recursion} shows. Therefore, we shall establish this inequality following the same framework as in Appendix~\ref{proof:lemma-lcb-revursion}. To begin with, let us recall several definitions in Appendix~\ref{proof:lemma-lcb-revursion}: \begin{align} A_h & \coloneqq \sum_{k=1}^K \underbrace{\sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right)}_{\eqqcolon A_{h,k}},\nonumber \\ B_{h,k} &\coloneqq \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right),\nonumber \\ Y_{h,k} &= \frac{d_{h}^{\pi_{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \sum_{n=1}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\eta_{n}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\left(V_{h+1}^{\star}-V_{h+1}^{k^{n}(s_{h}^{k},a_{h}^{k})}\right),\nonumber \\ Z_{h,k} &= \left(1+\frac{1}{H}\right) \frac{d_{h}^{\pi_{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \left(V_{h+1}^{\star}-V_{h+1}^{k}\right), \label{eq:lcb-adv-recall-A-B-X-Y} \end{align} and we also remind the reader of the relation in \eqref{eq:recursion-extra-error} as follows \begin{align} A_h \leq \sum_{k=1}^K B_{h,k} + \sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right) + \sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right). \label{eq:lcb-adv-decompose-A} \end{align} Equipped with these relations, we aim to control $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$ and $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$ respectively as follows. \begin{itemize} \item We first bound $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$, which is similar to \eqref{eq:bound-of-Y} (as controlled by Lemma~\ref{lemma:martingale-union-recursion}). Repeating the argument and tightening the bound from the second line of \eqref{eq:bound-of-Y}, we have for all $(h,s,a) \in [H] \times {\mathcal{S}}\times \mathcal{A}$, with probability at least $1-\delta$, \begin{align} &\left|\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)\right| \leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ & \leq \sqrt{8 C^\star \log\frac{2H}{\delta}\sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} P_{h,s,a}\left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right) \right]^2 } + 4H C^\star \log\frac{2H}{\delta} \nonumber \\ & \overset{\mathrm{(i)}}{\leq} \sqrt{8 C^\star \log\frac{2H}{\delta} \left(36HK +3c_\mathrm{a}^2 H^6SC^\star \iota\right)} + 4H C^\star \log\frac{2H}{\delta} \nonumber \\ &\leq 32\sqrt{HC^\star K \log\frac{2H}{\delta}} + 12c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2. \label{lcb-adv-bound-A-Z} \end{align} Here, (i) holds by virtue of the following fact \begin{align} \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} P_{h,s,a}\left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right) \right]^2 \leq 36HK +3c_\mathrm{a}^2 H^6SC^\star \iota \label{eq:A-Y-upper-bound}, \end{align} whose proof is postponed to Appendix~\ref{proof:eq:A-Y-upper-bound}. \item Next, we turn to $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$, which can be bounded similar to \eqref{eq:bound-of-Z} (as controlled via Lemma~\ref{lemma:martingale-union-recursion}). Repeating the argument and tightening the bound from the second line of \eqref{eq:bound-of-Z} yield \begin{align} & \left|\sum_{k=1}^K \left(B_{h,k} - Z_{h,k}\right)\right| \leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ & \leq 8\sqrt{C^\star \log\frac{2H}{\delta} \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a} \left(V_{h+1}^\star - V_{h+1}^{k}\right)\right]^2 } + 8HC^\star\log\frac{2H}{\delta}. \label{eq:lcb-adv-bound-of-Z} \end{align} To further control \eqref{eq:lcb-adv-bound-of-Z}, we have \begin{align} \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a} \left(V_{h+1}^\star - V_{h+1}^{k}\right)\right]^2 &\overset{\mathrm{(i)}}{\leq} \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a)P_{h,s,a} \left(V_{h+1}^\star - V_{h+1}^{k}\right)^2 \nonumber\\ &\overset{\mathrm{(ii)}}{\leq} H \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a)P_{h,s,a} \left(V_{h+1}^\star - V_{h+1}^{k}\right) \nonumber \\ &\overset{\mathrm{(iii)}}{\leq} 2HK + c_\mathrm{a}^2 H^6SC^\star \iota. \label{eq:lcb-adv-bound-of-Z-key} \end{align} Here, (i) holds due to the non-negativity of the variance \begin{align} \mathsf{Var}_{h, s,a}(V_{h+1}^{\star} - \overline{V}_{h+1}^{k}) = P_{h, s,a}(V_{h+1}^{\star} - V_{h+1}^{k})^{2} - \left(P_{h, s,a}(V_{h+1}^{\star} - V_{h+1}^{k}) \right)^2 \geq 0; \end{align} (ii) follows from the basic property $\left\|V_{h+1}^{\star} - V_{h+1}^{k}\right\|_\infty \leq H$; to see why (iii) holds, we refer the reader to \eqref{equ:146-3}, which will be proven in Appendix~\ref{proof:eq:A-Y-upper-bound} as well. Inserting \eqref{eq:lcb-adv-bound-of-Z-key} back into \eqref{eq:lcb-adv-bound-of-Z} yields \begin{align} \left|\sum_{k=1}^K \left(B_{h,k} - Z_{h,k}\right)\right| &\leq 8\sqrt{C^\star \log\frac{2H}{\delta} \left(2KH + c_\mathrm{a}^2 H^6SC^\star \iota\right) } + 8HC^\star\log\frac{2H}{\delta}\nonumber\\ &\leq 16\sqrt{HC^\star K \log\frac{2H}{\delta} } + 16 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota. \label{eq:lcb-adv-bound-of-Z-final-result} \end{align} \end{itemize} Substituting the inequalities~\eqref{lcb-adv-bound-A-Z} and \eqref{eq:lcb-adv-bound-of-Z-final-result} into \eqref{eq:lcb-adv-decompose-A}, and using the definitions in \eqref{eq:lcb-adv-recall-A-B-X-Y}, we arrive at \begin{align} & A_h = \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right) \nonumber\\ &\leq \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + \sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right) + \sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right) \nonumber\\ &\leq \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + 32\sqrt{HC^\star K \log\frac{2H}{\delta}} + 12c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2 \nonumber \\ &\qquad + 16\sqrt{HC^\star K \log\frac{2H}{\delta} } + 16 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota \nonumber\\ &\leq \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + 48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2, \end{align} which directly verifies \eqref{eq:lcb-adv-recursion-key} and completes the proof. \subsubsection{Proof of inequality~\eqref{eq:A-Y-upper-bound}}\label{proof:eq:A-Y-upper-bound} \paragraph{Step 1: rewriting the term of interest.} We first invoke Jensen's inequality to obtain \begin{align*} \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P_{h, s,a}\left(V^{\star}_{h+1} - V^{ k^n}_{h+1}\right)\Big)^2 &\leq \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \Big(P_{h, s,a}\left(V^{\star}_{h+1} - V^{ k^n}_{h+1}\right)\Big)^2 \leq \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P_{h, s,a}\left(V^{\star}_{h+1} - V^{ k^n}_{h+1}\right)^2, \end{align*} where the first inequality follows from $\sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} = 1$ (see \eqref{eq:sum-eta-n-N} and \eqref{equ:learning rate notation}), and the last inequality holds by the non-negativity of the variance $\mathsf{Var}_{h,s,a}[V^{\star}_{h+1} - V^{ k^n}_{h+1}]$. This allows one to derive \begin{align} &\sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} P_{h,s,a}\left(V^{\star}_{h+1} - V^{ k^n}_{h+1}\right)\right]^2 \nonumber\\ & \leq \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h, s,a} \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \left(V^{\star}_{h+1} - V^{ k^n}_{h+1}\right)^2\nonumber \\ & \overset{\mathrm{(i)}}{\leq} \left(1+\frac{1}{H}\right) \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{\star}_{h+1}(s) - V^{ k}_{h+1}(s)\right)^2 + 32\sqrt{H^4C^\star K \log\frac{2H}{\delta}} + 32H^2C^\star\log\frac{2H}{\delta}, \label{eq:recursion-bound-2} \end{align} where (i) can be verified in a way similar to the proof of Lemma~\ref{lemma:recursion} in Appendix~\ref{proof:lemma-lcb-revursion}. We omit the details for conciseness. \paragraph{Step 2: controlling the first term in \eqref{eq:recursion-bound-2}.}\label{sec:proof:equ:bound-for-reference-sum} Let us introduce the following short-hand notation \begin{align*} k_{\mathsf{stop}} \coloneqq c_\mathrm{a}^2 H^5SC^\star \iota, \end{align*} and decompose the term in \eqref{eq:recursion-bound-2} as follows \begin{align} & \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{k=1}^{K} \left(V_{h+1}^{\star}(s) - V_{h+1}^{k}(s)\right)^2 \overset{\mathrm{(i)}}{\leq} H \sum_{k=1}^{K} \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^{\star}(s) - V_{h+1}^{k}(s)\right) \nonumber\\ &= H\sum_{k = 1}^{k_\mathsf{stop}} \sum_{s \in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \big(V^{\star}_{h+1}(s) - V_{h+1}^{k}(s)\big) + H\sum_{k = k_\mathsf{stop}+1}^{K} \sum_{s \in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \big(V^{\star}_{h+1}(s) -V_{h+1}^{k}(s)\big). \label{equ:adv-L-1} \end{align} % Here, (i) holds since $0\leq V_{h+1}^{\star}(s) - V_{h+1}^{k}(s) \leq H$. The first term in \eqref{equ:adv-L-1} satisfies \begin{align} H\sum_{k = 1}^{k_\mathsf{stop}} \sum_{s \in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \big( V^{\star}_{h+1}(s) - V_{h+1}^{k}(s) \big) \leq H \left( c_\mathrm{a}\sqrt{H^5SC^\star \iota k_\mathsf{stop}} + c_\mathrm{a} H^2 SC^\star \iota \right) \leq c_\mathrm{a}^2 H^6SC^\star \iota, \label{equ:adv-L-1-term1} \end{align} where the first inequality holds by applying the results of {\sf LCB-Q}\xspace in \eqref{eq:lcb-final-result-H-layers} with $K = k_\mathsf{stop}$. The second term in \eqref{equ:adv-L-1} can be controlled as follows: \begin{align} H\sum_{k = k_\mathsf{stop}+1}^{K} \sum_{s \in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \big(V^{\star}_{h+1}(s) -V_{h+1}^{k}(s) \big) &\leq HK \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{\star}_{h+1}(s) - V^{k_{\mathsf{stop}}}_{h+1}(s)\right) \nonumber \\ &\leq HK\frac{1}{ k_{\mathsf{stop}}}\sum_{k=1}^{ k_{\mathsf{stop}}} \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{\star}_{h+1}(s) - V^{k}_{h+1}(s)\right) \nonumber\\ &\leq HK \left(c_\mathrm{a} \sqrt{\frac{H^5SC^\star \iota}{k_{\mathsf{stop}}}} + \frac{c_\mathrm{a} H^2 SC^\star \iota }{k_{\mathsf{stop}}}\right) \leq 2HK, \label{equ:adv-L-1-term2} \end{align} where the first and the second inequalities hold by the monotonicity property $V_{h+1}^{k+1} \geq V_{h+1}^k$ introduced in \eqref{equ:monotone-lcb-adv}, and the final inequality follows from applying \eqref{eq:lcb-final-result-H-layers}. Inserting the results in \eqref{equ:adv-L-1-term1} and \eqref{equ:adv-L-1-term2} into \eqref{equ:adv-L-1} yields \begin{align} &\sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{k=1}^{K} \left(V_{h+1}^{\star}(s) - V_{h+1}^{k}(s)\right)^2 \leq H \sum_{k=1}^{K} \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^{\star}(s) - V_{h+1}^{k}(s)\right)\leq 2HK + c_\mathrm{a}^2 H^6SC^\star \iota. \label{equ:146-3} \end{align} \paragraph{Step 3: combining the above results.} Inserting the above result \eqref{equ:146-3} back into \eqref{eq:recursion-bound-2}, we reach: \begin{align} &\sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} P_{h,s,a}\left(V^{\star}_{h+1} - V^{ k^n}_{h+1}\right)\right]^2 \nonumber \\ &\leq \left(1+\frac{1}{H}\right) \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{\star}_{h+1} - V^{ k}_{h+1}\right)^2 + 32\sqrt{H^4C^\star K \log\frac{2H}{\delta}} + 32H^2C^\star\log\frac{2H}{\delta} \nonumber\\ &\overset{\mathrm{(i)}}{\leq} 4HK + 2c_\mathrm{a}^2 H^6SC^\star \iota + 32\sqrt{H^4C^\star K \log\frac{2H}{\delta}} + 32H^2C^\star\log\frac{2H}{\delta} \nonumber\\ &\overset{\mathrm{(ii)}}{\leq} 36HK +3c_\mathrm{a}^2 H^6SC^\star \iota, \label{eq:lcb-adv-important1} \end{align} where (i) holds due to \eqref{equ:146-3} and $1+\frac{1}{H} \leq 2$, and (ii) results from the Cauchy-Schwarz inequality. \subsection{Proof of Lemma~\ref{lemma:lcb-adv-bound-terms}}\label{proof:lemma:lcb-adv-bound-terms} We shall verify the three inequalities in \eqref{eq:lemma6} separately. \subsubsection{Proof of inequality~\eqref{eq:lemma6-a}} We start by rewriting the term of interest using the expression of $J_h^1$ in \eqref{eq:Jh123} as \begin{align} &\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} J_h^1 \nonumber \\ &= \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\left[\eta_0^{N_h^k(s,a)}H + \frac{4c_{\mathrm{b}} H^{7/4} \iota}{\left(N_h^k(s,a) \vee 1 \right)^{3/4} } + \frac{4c_{\mathrm{b}} H^{2} \iota}{N_h^k(s,a) \vee 1 }\right] \nonumber\\ & = \underbrace{\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \eta_0^{N_h^k(s,a)}H}_{=:\mathcal{J}_1^1} + \underbrace{\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\frac{4c_{\mathrm{b}} H^{7/4} \iota}{(N_h^k(s,a) \vee 1)^{3/4}}}_{=:\mathcal{J}_1^2} \nonumber\\ & \quad + \underbrace{\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\frac{4c_{\mathrm{b}} H^2 \iota}{N_h^k(s,a) \vee 1}}_{=:\mathcal{J}_1^3}. \end{align} Invoking \eqref{equ:visit-cover-bound} and \eqref{equ:algebra property} yields \begin{align} \mathcal{J}_1^1 \lesssim H^2 SC^\star \iota. \label{equ:adv-J-11-result} \end{align} In terms of $\mathcal{J}_1^2$, one has \begin{align} \mathcal{J}_1^2 &= \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\frac{4c_{\mathrm{b}} H^{7/4} \iota}{(N_h^k(s,a) \vee 1)^{\frac{3}{4}}} \nonumber\\ &\overset{\mathrm{(i)}}{\lesssim} H^{7/4}\iota^2 \sum_{h=1}^H \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\frac{1}{(k d_h^{\mu}(s,a))^{\frac{3}{4}}} \nonumber\\ &\overset{\mathrm{(ii)}}{\lesssim} H^{7/4}\iota^2 (C^\star)^{\frac{3}{4}}\sum_{h=1}^H \sum_{k=1}^K \frac{1}{k^{\frac{3}{4}}} \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}} \left(d_h^{\pi^\star}(s, a)\right)^{\frac{1}{4}} \nonumber \\ & = H^{7/4}\iota^2 (C^\star)^{\frac{3}{4}}\sum_{h=1}^H \sum_{k=1}^K \frac{1}{k^{\frac{3}{4}}} \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}} \ind\big(a = \pi^\star_h(s)\big) \left( d_h^{\pi^\star}(s, a)\right)^{\frac{1}{4}}, \nonumber \end{align} where (i) holds due to \eqref{equ:algebra property} and $\frac{1}{N_h^k(s,a) \vee 1} \leq \frac{8\iota}{k d_h^{\mu}(s,a)}$ from Lemma~\ref{lem:binomial}, and (ii) follows from the definition of $C^{\star}$ in Assumption~\ref{assumption}. A direct application of H\"older's inequality leads to \begin{align} \mathcal{J}_1^2 &\leq H^{7/4}\iota^2 (C^\star)^{\frac{3}{4}}\sum_{h=1}^H\sum_{k=1}^K \frac{1}{k^{\frac{3}{4}}} \left(\sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}} \ind(a = \pi^\star_h(s)) \right)^{3/4} \left(\sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}} d_h^{\pi^\star}(s, a)\right)^{1/4} \nonumber \\ & \overset{\mathrm{(iii)}}{\leq} H^{7/4}\iota^2 (SC^\star)^{\frac{3}{4}}\sum_{h=1}^H \sum_{k=1}^K \frac{1}{k^{\frac{3}{4}}} \lesssim H^{2.75}(SC^\star)^{\frac{3}{4}} K^{\frac{1}{4}}\iota^2, \label{equ:adv-J-12-result} \end{align} where (iii) follows since $\pi^\star$ is assumed to be a deterministic policy. Similarly, we can derive an upper bound on $\mathcal{J}_1^3$ as follows: \begin{align} \mathcal{J}_1^3 &= \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\frac{4c_{\mathrm{b}} H^2 \iota}{N_h^k(s,a) \vee 1} \nonumber \\ &\overset{\mathrm{(i)}}{\lesssim} H^2\iota^2 \sum_{h=1}^H \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} \frac{d_h^{\pi^\star}(s, a)}{kd_h^{\mu}(s,a)} \lesssim H^3 SC^\star \iota^3, \label{equ:adv-J-13-result} \end{align} where (i) follows from the result in \eqref{equ:algebra property} and the fact $\frac{1}{N_h^k(s,a) \vee 1} \leq \frac{8\iota}{k d_h^{\mu}(s,a)}$ (cf.~Lemma~\ref{lem:binomial}), and the last relation results from the definition of $C^{\star}$ (cf.~Assumption~\ref{assumption}) and the assumption that $\pi^\star$ is a deterministic policy. Putting the preceding results \eqref{equ:adv-J-11-result}, \eqref{equ:adv-J-12-result} and \eqref{equ:adv-J-13-result} together, we conclude that \begin{align} &\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} J_h^1 \lesssim H^{2.75}(SC^\star)^{\frac{3}{4}} K^{\frac{1}{4}}\iota^2 + H^3 SC^\star \iota^3. \end{align} \subsubsection{Proof of inequality~\eqref{eq:lemma6-b}} Making use of the definition of $\overline{B}_h^k(s,a)$ (cf.~\eqref{eq:line-number-19}) in the expression of $J_h^2$ (cf.~\eqref{eq:Jh123}), we obtain \begin{align} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} J_h^2 & =2\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \sum_{k=1}^K \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\overline{B}_h^{k}(s,a) \nonumber\\ & = 2 \sum_{h=1}^H\left(1+\frac{1}{H}\right)^{h-1}c_{\mathrm{b}}\sqrt{H\iota } \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{\sigma^{\mathsf{adv}, k}_h(s, a) - \big(\mu^{\mathsf{adv}, k}_h(s, a)\big)^2}{N_h^k(s, a) \vee 1}} \nonumber \\ &\qquad + 2\sum_{h = 1}^H \left(1+\frac{1}{H}\right)^{h-1} c_{\mathrm{b}}\sqrt{\iota} \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K \sqrt{\frac{\sigma^{\mathsf{ref}, k}_h(s, a) - \big(\mu^{\mathsf{ref}, k}_h(s, a)\big)^2}{N_h^k(s, a) \vee 1}} \nonumber \\ &\lesssim \underbrace{\sqrt{H\iota } \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{k = 1}^K\sqrt{\frac{\sigma^{\mathsf{adv}, k}_h(s, a) - \big(\mu^{\mathsf{adv}, k}_h(s, a)\big)^2}{N_h^k(s,a) \vee 1}}}_{=:\mathcal{J}_2^1} \nonumber \\ &\qquad + \underbrace{\sqrt{\iota} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K \sqrt{\frac{\sigma^{\mathsf{ref}, k}_h(s, a) - \big(\mu^{\mathsf{ref}, k}_h(s, a)\big)^2}{N_h^k(s,a) \vee 1}}}_{=:\mathcal{J}_2^2},\label{equ:bound of b_hat} \end{align} where the last inequality follows from \eqref{equ:algebra property}. In the following, we shall look at the two terms in \eqref{equ:bound of b_hat} separately. \paragraph{Step 1: controlling $\mathcal{J}_2^1$.} Recalling the expressions of ${\sigma}_h^{\mathsf{adv}, k}(s,a)= {\sigma}_h^{\mathsf{adv}, k^{N_h^k}+1}(s,a) $ in \eqref{eq:recursion_mu_sigma_adv}, we observe that the main part of $\mathcal{J}_2^1$ in \eqref{equ:bound of b_hat} satisfies \begin{align} &\sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{k = 1}^K\sqrt{\frac{\sigma^{\mathsf{adv}, k}_h(s, a)- \left(\mu^{\mathsf{adv}, k}_h(s, a)\right)^2}{N_h^k(s,a) \vee 1}} \le \sqrt{\iota} \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K\sqrt{d_h^{\pi^\star}(s, a)\frac{d_h^{\pi^\star}(s, a) \cdot\sigma^{\mathsf{adv}, k}_h(s, a)}{k d_h^{\mu}(s,a)}} \nonumber \\ &= \sqrt{\iota} \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K\sqrt{d_h^{\pi^\star}(s, a)\frac{d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s, a)} \eta^{N^{k}_h(s, a)}_n P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2}{k d_h^{\mu}(s,a)}} \nonumber \\ & \overset{\mathrm{(i)}}{\leq} \sqrt{ C^\star \iota}\sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K\sqrt{\frac{1}{k} \ind\big(a = \pi^\star_h(s) \big) \cdot d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s, a)} \eta^{N^{k}_h(s, a)}_n P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 } \nonumber \\ & \overset{\mathrm{(ii)}}{\leq} \sqrt{ C^\star \iota} \sqrt{\sum_{k = 1}^K \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s, a)} \eta^{N^{k}_h(s, a)}_n P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 } \sqrt{\sum_{k = 1}^K \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \ind\big(a = \pi^\star_h(s)\big) \frac{1}{k}} \nonumber \\ &\lesssim \sqrt{HSC^\star \iota^2 } \sqrt{\sum_{k = 1}^K \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s, a)} \eta^{N^{k}_h(s, a)}_n P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 } \label{eq:proof of var of var prelim}, \end{align} where the first inequality is due to the fact $\frac{1}{N_h^k(s,a) \vee 1} \leq \frac{8\iota}{k d_h^{\mu}(s,a)}$ from Lemma~\ref{lem:binomial}, (i) follows from the definition of $C^{\star}$ in Assumption~\ref{assumption} and \eqref{eq:d_h_pi_star}, and (ii) follows from the Cauchy-Schwarz inequality. To continue, we claim the following bound holds, which will be proven in Appendix~\ref{sec:proof:equ:adv-J-21-E}: \begin{align} & \sum_{k = 1}^K \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s, a)} \eta^{N^{k}_h(s, a)}_n P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 \nonumber \\ & \lesssim H^2 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) + K + H^5\sqrt{S}C^\star\iota^2. \label{equ:adv-J-21-1} \end{align} Combining the above inequality with \eqref{eq:proof of var of var prelim}, we arrive at \begin{align} \mathcal{J}_2^1 & \lesssim \sqrt{H^2SC^\star \iota^3 } \sqrt{H^2 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) + K + H^5\sqrt{S}C^\star\iota^2} \nonumber \\ &\lesssim \sqrt{H^4SC^\star \iota^3 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) } + \sqrt{H^2SC^\star K \iota^3} + H^{3.5}SC^\star \iota^{2.5}.\label{equ:adv-J-21-result} \end{align} \paragraph{Step 2: controlling $\mathcal{J}_2^2$.} Recalling the expressions of $ {\mu}_h^{\mathsf{ref}, k+1}(s,a) = {\mu}_h^{\mathsf{ref}, k^{N_h^k}+1}(s,a)$ and $ {\sigma}_h^{\mathsf{ref}, k +1}(s,a) = {\sigma}_h^{\mathsf{ref}, k^{N_h^k}+1}(s,a) $ in \eqref{eq:recursion_mu_sigma_ref} to $\mathcal{J}_2^2$ in \eqref{equ:bound of b_hat}, we can deduce that \begin{align} & \mathcal{J}_2^2 =\sqrt{\iota} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K \sqrt{\frac{\sigma^{\mathsf{ref}, k}_h(s, a) - \left(\mu^{\mathsf{ref}, k}_h(s, a)\right)^2}{N_h^k(s,a) \vee 1}} \nonumber \\ & \leq \sqrt{\iota} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N_h^k(s,a) \vee 1}} \underbrace{ \sqrt{ \frac{\sum_{n = 1}^{N^{k}_h(s, a)}\left(\overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{k^n}_{h+1})\right)^2}{N^{k}_h(s, a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s, a)} \overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s, a) \vee 1}\Big)^2 } }_{=: F_{h,k}} \label{equ:adv-var1}. \end{align} We further decompose and bound $F_{h,k}$ as follows: \begin{align} & F_{h,k} \overset{\mathrm{(i)}}{\leq} \sqrt{\frac{\sum_{n = 1}^{N^{k}_h(s, a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1})\right)^2}{N^{k}_h(s, a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s, a)} \overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s, a) \vee 1}\Big)^2} \nonumber\\ & = \sqrt{\frac{\sum_{n = 1}^{N^{k}_h(s,a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1})\right)^2}{N^{k}_h(s,a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a)}V^{\star}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s,a) \vee 1}\Big)^2 + \Big(\frac{\sum_{n = 1}^{N^{k}_h(s, a)}V^{\star}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s, a) \vee 1}\Big)^2 - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s, a)} \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s, a) \vee 1}\Big)^2} \nonumber\\ &\overset{\mathrm{(ii)}}{\leq} \underbrace{ \sqrt{\frac{\sum_{n = 1}^{N^{k}_h(s,a) }\left(V^{\star}_{h+1}(s^{k^n}_{h+1})\right)^2}{N^{k}_h(s,a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a)}V^{\star}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s,a) \vee 1}\Big)^2}}_{G_{h,k}} + \underbrace{ \sqrt{\frac{\sum_{n = 1}^{N^{k}_h(s,a)}2H \left(V^{\star}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n}_{h+1})\right)}{N^{k}_h(s,a) \vee 1} }}_{=: L_{h,k}} ,\label{equ:adv-J22-terms} \end{align} where (i) follows from the fact that for some $k'\in[K]$, $\overline{V}^{\mathsf{next}, k^n}_{h+1} = V^{k'}_{h+1} \leq V^{\star}_{h+1}$ (see the update rule of $\overline{V}^{\mathsf{next}}$ in line~\ref{eq:update-mu-reference-v-next-k} and the fact in \eqref{eq:lcb-adv-lower}), and (ii) holds due to the fact that $$\Big(\frac{\sum_{n = 1}^{N^{k}_h(s, a)}V^{\star}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s, a) \vee 1}\Big)^2 - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s, a)} \overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s, a) \vee 1}\Big)^2\leq 2H \frac{\sum_{n = 1}^{N^{k}_h(s, a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{\mathsf{next}, k^n}_{h+1}(s^{ k^n}_{h+1})\right)}{N^{k}_h(s, a) \vee 1} .$$ Inserting \eqref{equ:adv-J22-terms} back into \eqref{equ:adv-var1}, we arrive at \begin{align} \notag \mathcal{J}_2^2 & \leq \sqrt{\iota} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N_h^k(s,a) \vee 1}} \left(G_{h,k} + L_{h,k}\right)\\ &\overset{\mathrm{(i)}}{\lesssim} \sqrt{\iota} \left(\sqrt{H^3S C^\star K \iota^4} + H^{4} S C^\star \iota^3 + \sqrt{H^3 S C^\star K\iota^2} + H^{2.5}SC^\star\iota^3 \right)\lesssim \sqrt{H^3S C^\star K \iota^5} + H^{4} S C^\star \iota^4, \label{equ:adv-J-22-result} \end{align} where (i) follows from the following facts \begin{align} &\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} L_{h,k} \lesssim \sqrt{H^3S C^\star K \iota^4} + H^{4} S C^\star \iota^3,\label{adv-J-22-L}\\ &\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} G_{h,k}\lesssim \sqrt{H^3 S C^\star K\iota^2} + H^{2.5}SC^\star\iota^3. \label{adv-J-22-G} \end{align} We postpone the proofs of \eqref{adv-J-22-L} and \eqref{adv-J-22-G} to Appendix~\ref{proof:adv-J-22-L} and Appendix~\ref{proof:adv-J-22-G}, respectively. \paragraph{Putting the bounds together.} Substitute \eqref{equ:adv-J-21-result} and \eqref{equ:adv-J-22-result} back into \eqref{equ:bound of b_hat} to yield \begin{align*} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} J_h^2 & \lesssim \sqrt{H^4SC^\star \iota^3 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) } + \sqrt{H^2SC^\star K \iota^3} + H^{3.5}SC^\star \iota^{2.5} \\ &\qquad + \sqrt{H^3S C^\star K \iota^5} + H^{4} S C^\star \iota^4\\ &\lesssim \sqrt{H^4SC^\star \iota^3 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) } + \sqrt{H^3S C^\star K \iota^5} + H^{4} S C^\star \iota^4. \end{align*} \subsubsection{Proof of inequality~\eqref{eq:lemma6-c}} Invoking inequality~\eqref{equ:algebra property} directly leads to \begin{align*} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \left(48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2 \right) &\lesssim \sqrt{H^3C^\star K \log\frac{2H}{\delta}} + H^{4}C^\star \sqrt{S} \iota^2 \end{align*} as claimed. \subsubsection{Proof of inequality \eqref{equ:adv-J-21-1}} \label{sec:proof:equ:adv-J-21-E} We shall control the term in \eqref{equ:adv-J-21-1} in a way similar to the proof of Lemma~\ref{lemma:recursion} in Appendix~\ref{proof:lemma-lcb-revursion}. \paragraph{Step 1: decomposing the terms of interest.} Akin to Appendix~\ref{proof:lemma-lcb-revursion}, let us introduce the terms of interest and definitions as follows: \begin{align} A_h & \coloneqq \sum_{k=1}^K \underbrace{\sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2}_{\eqqcolon A_{h,k}},\nonumber \\ B_{h,k} &\coloneqq \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{k}_{h+1}(s) - \overline{V}^{k}_{h+1}(s)\right)^2,\nonumber \\ Y_{h,k} &= \frac{d_{h}^{\pi_{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} \sum_{n=1}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\eta_{n}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2,\nonumber \\ Z_{h,k} &= \left(1+\frac{1}{H}\right) \frac{d_{h}^{\pi_{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_h^{k} \left(V^{k}_{h+1} - \overline{V}^{k}_{h+1}\right)^2. \label{eq:lcb-adv-recall-A-B-X-Y-2} \end{align} With these definitions in place, we directly adapt the argument in \eqref{eq:recursion-extra-error} to arrive at \begin{align} A_h \leq \sum_{k=1}^K B_{h,k} + \sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right) + \sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right). \label{eq:lcb-adv-decompose-A-2} \end{align} As a consequence, it remains to control $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$ and $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$ separately. \paragraph{Step 2: controlling $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$.} To control $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$, we resort to Lemma~\ref{lemma:martingale-union-recursion} by setting \begin{align} W_{h+1}^{k}(s,a) \coloneqq \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2, \qquad C_{\mathrm{d}} \coloneqq 1, \label{eq:lcb-adv-A-Y-w} \end{align} which satisfies \begin{align*} \left\|W_{h+1}^{k}(s,a)\right\|_\infty \leq 4H^2 \eqqcolon C_{\mathrm{w}}. \end{align*} Applying Lemma~\ref{lemma:martingale-union-recursion} with \eqref{eq:lcb-adv-A-Y-w} yields that: with probability at least $1-\delta$, \begin{align} &\left|\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)\right| = \left|\sum_{k=1}^K \overline{X}_{h,k}\right|\nonumber \\ &\leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ & \lesssim \sqrt{C^\star \log\frac{2H}{\delta}\sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 \right]^2 } + C^\star H^2\log\frac{2H}{\delta} \label{lcb-adv-bound-A-Y-2}. \end{align} To further control the first term in \eqref{lcb-adv-bound-A-Y-2}, it follows from Jensen's inequality that \begin{align} P_{h, s,a}\left[\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \left(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1}\right)^2\right]^2 &\leq P_{h, s,a}\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \Big(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1}\Big)^4, \end{align} which yields \begin{align} & \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 \right]^2 \nonumber \\ &\leq \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h, s,a} \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \Big(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1}\Big)^4 \nonumber \\ & \leq \left(1+\frac{1}{H}\right) \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{k}_{h+1}(s) - \overline{V}_{h+1}^{k}(s)\right)^4 + 32\sqrt{H^8C^\star K \log\frac{2H}{\delta}} + 32H^4C^\star\log\frac{2H}{\delta}. \label{eq:recursion-bound-3} \end{align} This can be verified similar to the proof for Lemma~\ref{lemma:recursion} in Appendix~\ref{proof:lemma-lcb-revursion}. We omit the details for conciseness. To continue, it follows that \begin{align} & \sum_{k=1}^K \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s)\left(V_{h+1}^k(s) - \overline{V}_{h+1}^k(s)\right)^4 \nonumber \\ &\overset{\mathrm{(i)}}{\leq} \sum_{m=1}^M \sum_{t=1}^{L_m} \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s)\left(V_{h+1}^{\star}(s) - \overline{V}_{h+1}^{(m,t)}(s)\right)^4 \nonumber \\ & \overset{\mathrm{(ii)}}{=} \sum_{m=1}^M \sum_{t=1}^{L_m} \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s)\left(V_{h+1}^{\star}(s) - V^{\left((m-1) \vee 1 ,1\right)}_{h+1}(s)\right)^4 \nonumber\\ &\overset{\mathrm{(iii)}}{=} \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{m=1}^M 2^{m} \left(V_{h+1}^{\star}(s) - V^{\left((m-1) \vee 1 ,1\right)}_{h+1}(s)\right)^4 \nonumber \\ &= 4 \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{m-2=-1}^{M-2} 2^{m-2} \left(V_{h+1}^{\star}(s) - V^{\left((m-1) \vee 1 ,1\right)}_{h+1}(s)\right)^4 \nonumber \\ & = 4 \sum_{m-2 = -1}^{0} 2^{m-2} \left(V_{h+1}^{\star}(s) - V^{\left(1 ,1\right)}_{h+1}(s)\right)^4 + 4 \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{m-2=1}^{M-2} 2^{m-2} \left(V_{h+1}^{\star}(s) - V^{\left(m-1 ,1\right)}_{h+1}(s)\right)^4. \nonumber \end{align} Here, (i) holds by using the pessimistic property $V^\star \geq V^k \geq \overline{V}^k$ for all $k\in[K]$ (see \eqref{eq:lcb-adv-lower}) and by regrouping the summands; (ii) follows from the fact (see updating rules in line~\ref{eq:update-mu-reference-v-k} and line~\ref{eq:update-mu-reference-v-next-k}) that for any $(m,s,h)\in [M] \times {\mathcal{S}}\times [H + 1]$, \begin{align} \overline{V}^{(m,t)}_{h}(s) = V^{\left((m-1) \vee 1 ,1\right)}_{h}(s), \qquad t =1,2,\cdots, L_m; \end{align} and (iii) results from the choice of the parameter $L_m = 2^m$. In addition, we can further control \begin{align} \sum_{k=1}^K \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s)\left(V_{h+1}^k(s) - \overline{V}_{h+1}^k(s)\right)^4 & \overset{\mathrm{(iv)}}{\leq} 8H^4 + 4\sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{m=1}^{M-2} \sum_{t=1}^{L_m} \left(V_{h+1}^{\star}(s) - V_{h+1}^{(m+1,1)}(s)\right)^4 \nonumber \\ & \overset{\mathrm{(v)}}{\leq} 8H^4 + 4\sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{m=1}^{M-2} \sum_{t=1}^{L_m} \left(V_{h+1}^{\star}(s) - V_{h+1}^{(m,t)}(s)\right)^4 \nonumber \\ & \leq 8H^4 + 4 \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{k=1}^{K} \left(V_{h+1}^{\star}(s) - V_{h+1}^{k}(s)\right)^4 \label{eq:lcb-adv-important2-inter}\\ & \leq 8H^4 + 4H^3 \sum_{s\in{\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \sum_{k=1}^{K} \left(V_{h+1}^{\star}(s) - V_{h+1}^{k}(s)\right) \nonumber\\ &\overset{\mathrm{(vi)}}{\lesssim} H^3K + H^8SC^\star \iota. \label{eq:lcb-adv-important2} \end{align} Here, (iv) follows from the fact $0 \leq V_{h+1}^{\star}(s) - V^{\left(1 ,1\right)}_{h+1}(s) \leq H - 0 = H$; (v) holds since $V_{h+1}^\star \geq V_{h+1}^{(m+1,1)} = V_{h+1}^{(m,L_m)} \geq V_{h+1}^{(m,t)}$ for all $t\in [L_m]$ (using the monotonic increasing property of $V_{h+1}$ introduced in \eqref{equ:monotone-lcb-adv}); and (vi) follows from \eqref{equ:146-3}. Putting \eqref{eq:lcb-adv-important2} and \eqref{eq:recursion-bound-3} together with \eqref{lcb-adv-bound-A-Y-2}, we arrive at \begin{align} \left|\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)\right| &\lesssim \sqrt{C^\star \log\frac{2H}{\delta}\left( H^3K + H^8SC^\star \iota + \sqrt{H^8C^\star K \log\frac{2H}{\delta}} + H^4C^\star\log\frac{2H}{\delta} \right) } + C^\star H^2\log\frac{2H}{\delta} \nonumber \\ &\lesssim \sqrt{H^3C^\star K\iota} + H^{4}\sqrt{S}C^\star \iota^2. \label{eq:lcb-adv-A-Y-bound2} \end{align} \paragraph{Step 3: controlling $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$.} Similarly, we also invoke Lemma~\ref{lemma:martingale-union-recursion} to control $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$. Let's set \begin{align} W_{h+1}^{k}(s,a) \coloneqq \left(V^{k}_{h+1} - \overline{V}^{k}_{h+1}\right)^2, \qquad C_{\mathrm{d}} \coloneqq \left(1+\frac{1}{H}\right)\leq 2, \label{eq:lcb-adv-B-Z-w-2} \end{align} which satisfies \begin{align*} \left\|W_{h+1}^{k}(s,a)\right\|_\infty \leq 4H^2 \eqqcolon C_{\mathrm{w}}. \end{align*} Applying Lemma~\ref{lemma:martingale-union-recursion} with \eqref{eq:lcb-adv-B-Z-w-2} yields that: with probability at least $1-\delta$, \begin{align} &\left|\sum_{k=1}^K \left(B_{h,k} - Z_{h,k}\right)\right| = \left|\sum_{k=1}^K \overline{X}_{h,k}\right| \nonumber\\ &\leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ & \lesssim \sqrt{C^\star \log\frac{2H}{\delta}\sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[V^{k}_{h+1} - \overline{V}^{k}_{h+1}\right]^4 } + C^\star H^2\log\frac{2H}{\delta} \nonumber\\ &\overset{\mathrm{(i)}}{\lesssim} \sqrt{C^\star\log\frac{2H}{\delta} \left(H^3K + H^8SC^\star \iota \right)} + C^\star H^2\log\frac{2H}{\delta} \lesssim \sqrt{H^3C^\star K\iota} + H^{4}\sqrt{S}C^\star \iota^2, \label{lcb-adv-bound-A-Z-2} \end{align} where (i) follows from \eqref{eq:lcb-adv-important2-inter} and \eqref{eq:lcb-adv-important2}. \paragraph{Step 4: combining the results.} Inserting \eqref{lcb-adv-bound-A-Z-2} and \eqref{eq:lcb-adv-A-Y-bound2} back into \eqref{eq:lcb-adv-decompose-A-2}, we can conclude that \begin{align} &\sum_{k = 1}^K \sum_{h=1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s, a)} \eta^{N^{k}_h(s, a)}_n P_h^{k^n}\left(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}\right)^2 = \sum_{h=1}^H A_h\nonumber\\ & \leq \sum_{h=1}^H \sum_{k=1}^K B_{h,k} + \sum_{h=1}^H\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right) + \sum_{h=1}^H\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right) \nonumber\\ &\leq \sum_{h=1}^H \sum_{k=1}^K \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{k}_{h+1}(s) - \overline{V}^{k}_{h+1}(s)\right)^2 + \sum_{h=1}^H\left|\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)\right| + \sum_{h=1}^H\left|\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)\right| \nonumber\\ & \leq H \sum_{h=1}^H \sum_{k=1}^K \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{k}_{h+1}(s) - \overline{V}^{k}_{h+1}(s)\right) + \sqrt{H^5C^\star K\iota} + H^{5}\sqrt{S}C^\star \iota^2 \nonumber \\ & \overset{\mathrm{(i)}}{\lesssim} H \sum_{h=1}^H \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{\star}_{h+1}(s) - V^{k}_{h+1}(s)\right) + K + H^5\sqrt{S}C^\star\iota^2 \nonumber \\ & \lesssim H^2 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) + K + H^5\sqrt{S}C^\star\iota^2, \end{align} where (i) follows from the same routine to obtain \eqref{eq:lcb-adv-important2-inter} and the Cauchy-Schwarz inequality. \subsubsection{Proof of inequality~\eqref{adv-J-22-L}}\label{proof:adv-J-22-L} \paragraph{Step 1: decomposing the error in \eqref{adv-J-22-L}.} The term in \eqref{adv-J-22-L} obeys \begin{align} &\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} L_{h,k} \nonumber\\ &= \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K \sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} \sqrt{\frac{\sum_{n = 1}^{N^{k}_h(s,a)}2H\left(V^{\star}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n}_{h+1})\right)}{N^{k}_h(s,a) \vee 1} } \nonumber\\ & \overset{\mathrm{(i)}}{\lesssim} \sqrt{H\iota} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K \sqrt{\frac{d_h^{\pi^\star }(s, a)}{k d_h^{\mu}(s,a)}} \sqrt{\frac{d_h^{\pi^\star}(s, a)\iota \sum_{n = 1}^{N^{k}_h(s,a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n}_{h+1})\right)}{k d_h^{\mu}(s,a)} } \nonumber\\ & \overset{\mathrm{(ii)}}{\lesssim} \sqrt{HC^\star \iota^2} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K \sqrt{\frac{\ind(a=\pi^\star(s))}{k }} \sqrt{\frac{d_h^{\pi^\star}(s, a)\sum_{n = 1}^{N^{k}_h(s,a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n}_{h+1})\right)}{k d_h^{\mu}(s,a)} } \nonumber\\ & \overset{\mathrm{(iii)}}{\lesssim} \sqrt{HC^\star \iota^2} \sqrt{\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K \frac{ d_h^{\pi^\star}(s, a) \sum_{n = 1}^{N^{k}_h(s,a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1}) - \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n}_{h+1})\right)}{k d_h^{\mu}(s,a)} } \sqrt{\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}} \sum_{k = 1}^K \frac{\ind(a=\pi^\star(s))}{k}} \nonumber \\ &\lesssim \sqrt{H^2SC^\star \iota^3} \sqrt{\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}}\frac{d_h^{\pi^\star}(s, a)}{d_h^{\mu}(s,a)} \sum_{k = 1}^K \frac{1}{k}\sum_{n = 1}^{N^{k}_h(s,a)}\left(V^{\star}_{h+1}(s^{k^n(s,a)}_{h+1}) - \overline{V}^{\mathsf{next},k^n}_{h+1}(s^{k^n(s,a)}_{h+1})\right) } \nonumber\\ &\overset{\mathrm{(iv)}}{=} \sqrt{H^2SC^\star \iota^3} \sqrt{\sum_{h = 1}^H \sum_{k = 1}^K \frac{d_h^{\pi^\star}(s_h^k,a_h^k) } {d_h^{\mu}(s_h^k,a_h^k)} P_h^k \sum_{k'=k}^K \frac{1}{k'}(V^{\star}_{h+1} - \overline{V}^{\mathsf{next},k}_{h+1}) } \nonumber\\ &\lesssim \sqrt{H^2SC^\star \iota^4} \sqrt{\sum_{h = 1}^H \sum_{k = 1}^K \frac{d_h^{\pi^\star}(s_h^k,a_h^k) P_h^k} {d_h^{\mu}(s_h^k,a_h^k)} (V^{\star}_{h+1} - \overline{V}^{\mathsf{next},k}_{h+1}) }. \end{align} Here, (i) follows from the fact $\frac{1}{N_h^k(s,a) \vee 1} \leq \frac{8\iota}{k d_h^{\mu}(s,a)}$ (cf.~Lemma~\ref{lem:binomial}); (ii) follows from the definition of $C^\star$ in Assumption~\ref{assumption}; (iii) invokes the Cauchy-Schwarz inequality; (iv) can be obtained by regrouping the terms (the terms involving $(V^{\star}_{h+1} - \overline{V}^{\mathsf{next},k}_{h+1})$ associated with index $k$ will only been added during episodes $k' = k, k+1,\cdots, K$). With this upper bound in hand, we further decompose \begin{align} &\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} L_{h,k} \lesssim \sqrt{H^2SC^\star \iota^4} \sqrt{\sum_{h = 1}^H \sum_{k = 1}^K \frac{d_h^{\pi^\star}(s_h^k,a_h^k) P_h^k} {d_h^{\mu}(s_h^k,a_h^k)} (V^{\star}_{h+1} - \overline{V}^{\mathsf{next},k}_{h+1}) } \nonumber\\ &\overset{\mathrm{(i)}}{\lesssim} \sqrt{H^2SC^\star \iota^4} \sqrt{\sum_{h = 1}^H \sum_{k = 1}^K \frac{d_h^{\pi^\star}(s_h^k,a_h^k) } {d_h^{\mu}(s_h^k,a_h^k)} P_h^k \left(V_{h+1}^\star - \overline{V}_{h+1}^k\right)}\nonumber\\ &\overset{\mathrm{(ii)}}{\lesssim} \sqrt{H^2SC^\star \iota^4} \sqrt{\sum_{h = 1}^H \sum_{k = 1}^K \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_{h, s,a} \left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right) } \nonumber \\ & \qquad + \sqrt{H^2SC^\star \iota^4}\sqrt{\left|\sum_{h = 1}^H \sum_{k = 1}^K \left( \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_{h, s,a} - \frac{d_h^{\pi^\star}(s_h^k,a_h^k) } {d_h^{\mu}(s_h^k,a_h^k)}P_h^k\right)\left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right)\right|}. \label{equ:adv-L-decompose} \end{align} Here (i) holds due to the following observation: denoting by $m$ the index of the epoch in which episode $k$ occurs, we have \begin{align} &\overline{V}_{h+1}^{\mathsf{next},k}=V_{h+1}^{(m,1)} \geq V_{h+1}^{((m-1 \vee 1),1)} = \overline{V}_{h+1}^{k}, \end{align} which invokes the monotonicity of $V_{h+1}^k$ in \eqref{equ:monotone-lcb-adv}. In addition, (ii) arises from the Cauchy-Schwarz inequality. \paragraph{Step 2: controlling the first term in \eqref{equ:adv-L-decompose}.} The first term in \eqref{equ:adv-L-decompose} satisfies \begin{align} \sum_{h = 1}^H \sum_{k = 1}^K \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_{h, s,a} \left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right) &= \sum_{h = 1}^H \sum_{k = 1}^K \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) \big\langle P_h(\cdot \mymid s,a), V^{\star}_{h+1} - \overline{V}^{k}_{h+1} \big\rangle \nonumber \\ & \overset{\mathrm{(i)}}{=} \sum_{h = 1}^H \sum_{k = 1}^K \sum_{s' \in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s') \left(V^{\star}_{h+1}(s') - \overline{V}^{k}_{h+1}(s') \right) \nonumber\\ &\overset{\mathrm{(ii)}}{\lesssim} H^2 + \sum_{h = 1}^H \sum_{k = 1}^K \sum_{s \in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V^{\star}_{h+1}(s) - V^{k}_{h+1}(s)\right) \nonumber\\ &\overset{\mathrm{(iii)}}{\lesssim} HK + H^6 S C^{\star}\iota,\label{equ:adv-L-1-true} \end{align} where (i) holds due to the fact $\sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_h(\cdot \mymid s,a) = d_{h+1}^{\pi^\star}(\cdot)$, (ii) comes from the same argument employed to establish \eqref{eq:lcb-adv-important2-inter}, and (iii) follows from \eqref{equ:146-3}. \paragraph{Step 3: controlling the second term in \eqref{equ:adv-L-decompose}.} We shall invoke Lemma~\ref{lemma:martingale-union-recursion} for this purpose. To proceed, let \begin{align} W_{h+1}^{k}(s,a) \coloneqq V^{\star}_{h+1} - \overline{V}^{k}_{h+1}, \qquad C_{\mathrm{d}} \eqqcolon 1, \label{eq:lcb-adv-216-w} \end{align} which satisfies \begin{align*} \left\|W_{h+1}^{k}(s,a)\right\|_\infty \leq H \eqqcolon C_{\mathrm{w}}. \end{align*} Applying Lemma~\ref{lemma:martingale-union-recursion} with \eqref{eq:lcb-adv-216-w} yields, for all $h\in[H]$, with probability at least $1-\delta$ \begin{align} \Bigg|\sum_{k = 1}^K &\left( \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_{h, s,a} - \frac{d_h^{\pi^\star}(s_h^k,a_h^k) } {d_h^{\mu}(s_h^k,a_h^k)}P_h^k\right)\left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right) \Bigg|= \left|\sum_{k=1}^K \overline{X}_{h,k}\right| \nonumber\\ &\leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ &\lesssim \sqrt{C^\star\log\frac{2H}{\delta}\sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right)^2 } + HC^\star\log\frac{2H}{\delta}\nonumber \\ &\overset{\mathrm{(i)}}{\lesssim} \sqrt{C^\star\log\frac{2H}{\delta} \left(H^2 + \sum_{k=1}^K \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left(V^{\star}_{h+1} - V^k_{h+1}\right)^2 \right)} + HC^\star\log\frac{2H}{\delta}\nonumber \\ &\overset{\mathrm{(ii)}}{\lesssim} \sqrt{C^\star\log\frac{2H}{\delta}\left(HK +H^6SC^\star \iota\right)} + HC^\star\log\frac{2H}{\delta} \nonumber\\ & \lesssim \sqrt{HC^\star K \iota} + H^3\sqrt{S}C^\star \iota. \end{align} Here (i) follows from the same routine to arrive at \eqref{eq:lcb-adv-important2-inter}, and (ii) comes from \eqref{equ:146-3}. As a result, the second term in \eqref{equ:adv-L-decompose} satisfies, with probability at least $1-\delta$, \begin{align} &\left| \sum_{h = 1}^H \sum_{k = 1}^K \left( \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_{h, s,a} - \frac{d_h^{\pi^\star}(s_h^k,a_h^k) P_h^k} {d_h^{\mu}(s_h^k,a_h^k)}\right)\left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right)\right| \nonumber\\ &\leq \sum_{h=1}^H \left|\sum_{k = 1}^K \left( \sum_{(s,a)\in {\mathcal{S}}\times \mathcal{A}}d_h^{\pi^\star}(s,a) P_{h, s,a} - \frac{d_h^{\pi^\star}(s_h^k,a_h^k) P_h^k} {d_h^{\mu}(s_h^k,a_h^k)}\right)\left(V^{\star}_{h+1} - \overline{V}^{k}_{h+1}\right)\right| \lesssim \sqrt{H^3C^\star K \iota} + H^4\sqrt{S}C^\star \iota. \label{equ:adv-L-2} \end{align} \paragraph{Step 4: combining the results.} Finally, inserting \eqref{equ:adv-L-1-true} and \eqref{equ:adv-L-2} into \eqref{equ:adv-L-decompose}, we arrive at \begin{align} &\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a)}} L_{h,k} \nonumber\\ &\lesssim \sqrt{H^2SC^\star \iota^4} \sqrt{HK + H^6 S C^{\star}\iota} + \sqrt{H^2SC^\star \iota^4} \sqrt{\sqrt{H^3C^\star K \iota} + H^4\sqrt{S}C^\star \iota} \nonumber\\ &\lesssim \sqrt{H^3S C^\star K \iota^4} + H^{4} S C^\star \iota^3 + \sqrt{H^2SC^\star \iota^4} \sqrt{HK + H^4\sqrt{S}C^\star \iota} \lesssim \sqrt{H^3S C^\star K \iota^4} + H^{4} S C^\star \iota^3, \end{align} where the last two inequalities follow from the Cauchy-Schwarz inequality. \subsubsection{Proof of inequality~\eqref{adv-J-22-G}}\label{proof:adv-J-22-G} Recall the expression of $G_{h,k}$ in \eqref{equ:adv-J22-terms} as \begin{align} G_{h,k}^2 &= \frac{\sum_{n = 1}^{N^{k}_h(s,a)}\left(V^{\star}_{h+1}(s^{k^n}_{h+1})\right)^2}{N^{k}_h(s,a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a) }V^{\star}_{h+1}(s^{k^n}_{h+1})}{N^{k}_h(s,a) \vee 1}\Big)^2 \nonumber \\ & = \frac{\sum_{n = 1}^{N^{k}_h(s,a)} P_h^{k^n}\left(V^{\star}_{h+1}\right)^2}{N^{k}_h(s,a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1}\Big)^2. \end{align} To continue, we make the following observation \begin{align} G_{h,k} &\leq \left\{ \left|G_{h,k}^2 - \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right| + \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right\}^{1/2} \notag\\ &\leq \left|G_{h,k}^2 - \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right|^{1/2} + \sqrt{\mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) } \end{align} due to the elementary inequality $\sqrt{a^2 + b^2} \leq a + b$ for any $a, b\geq0$. Here, we remind the reader that $\mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) = P_{h, s,a}(V^{\star}_{h+1})^2 - (P_{h, s,a} V^{\star}_{h+1})^2$ (cf.~\eqref{lemma1:equ2}). This allows us to rewrite \begin{align}\label{eq:control_Ghk} & \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} G_{h,k} \nonumber \\ & \leq \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{ \left|G_{h,k}^2 - \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right|}{N^{k}_h(s, a) \vee 1}} + \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{ \mathsf{Var}_{h, s,a}(V^{\star}_{h+1})}{N^{k}_h(s, a) \vee 1}}, \end{align} leaving us with two terms to cope with. \paragraph{Step 1: controlling the first term of \eqref{eq:control_Ghk}.} By definition, we have \begin{align} & \left|G_{h,k}^2 - \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right| = \left|\frac{\sum_{n = 1}^{N^{k}_h(s,a)} P_h^{k^n}\left(V^{\star}_{h+1}\right)^2}{N^{k}_h(s,a) \vee 1} - \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1}\Big)^2 -P_{h, s,a}(V^{\star}_{h+1})^2 + \left(P_{h, s,a} V^{\star}_{h+1}\right)^2 \right| \nonumber \\ &\leq \left|\frac{\sum_{n = 1}^{N^{k}_h(s,a)} P_h^{k^n}\left(V^{\star}_{h+1}\right)^2}{N^{k}_h(s,a) \vee 1} - P_{h, s,a}(V^{\star}_{h+1})^2 \right| + \left| \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1}\Big)^2 - \left(P_{h, s,a}V^{\star}_{h+1}\right)^2 \right| \nonumber \\ & \leq \left|\frac{\sum_{n = 1}^{N^{k}_h(s,a)} P_h^{k^n}\left(V^{\star}_{h+1}\right)^2}{N^{k}_h(s,a) \vee 1} - P_{h, s,a}(V^{\star}_{h+1})^2 \right| + 2H \left| \frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1} - P_{h, s,a}V^{\star}_{h+1}\right|, \label{equ:Ghk-var-diff} \end{align} where the last inequality holds due to \begin{align*} \left| \Big(\frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1}\Big)^2 - \left(P_{h, s,a}V^{\star}_{h+1}\right)^2 \right| &= \left| \frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1} - P_{h, s,a}V^{\star}_{h+1}\right| \cdot\left| \frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1} + P_{h, s,a}V^{\star}_{h+1}\right| \\ & \leq 2H \left| \frac{\sum_{n = 1}^{N^{k}_h(s,a) } P_h^{k^n} V^{\star}_{h+1}}{N^{k}_h(s,a) \vee 1} - P_{h, s,a}V^{\star}_{h+1}\right| . \end{align*} We now control the two terms in \eqref{equ:Ghk-var-diff} separately by invoking Lemma~\ref{lemma:martingale-union-all}. For the first term in \eqref{equ:Ghk-var-diff}, let us set \begin{align}\label{eq:261-w} W_{h+1}^{i} \coloneqq \left(V^\star_{h+1}\right)^2, \qquad \text{and} \qquad u_h^i(s,a,N) \coloneqq \frac{1}{N \vee 1} \coloneqq C_{\mathrm{u}}, \end{align} which indicates that \begin{align} \|W_{h+1}^{i}\|_\infty \leq H^2 \eqqcolon C_{\mathrm{w}}, \label{eq:261-cw} \end{align} Applying Lemma~\ref{lemma:martingale-union-all} with \eqref{eq:261-w} and $N = N_h^k = N_h^{k}(s,a)$, with probability at least $1-\frac{\delta}{2}$, we arrive at \begin{align} &\left|\frac{1}{N_h^k(s,a) \vee 1}\sum_{n = 1}^{{N_h^k}} (P^{k^n}_h - P_{h, s,a})(V^{\star}_{h+1})^2\right| = \left|\sum_{i=1}^k X_i\left(s,a, h, N_h^k\right)\right| \nonumber\\ &\lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{n = 1}^{N_h^k} u_h^{k^n}(s,a, N_h^k) \mathsf{Var}_{h,s,a} \big(W_{h+1}^{k^n} \big)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N_h^k \vee 1}} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta} \nonumber \\ & \asymp \sqrt{\frac{\iota^2}{N_h^k \vee 1}}\sqrt{\sum_{n = 1}^{N_h^k} \frac{1}{N_h^k \vee 1}\|W_{h+1}^{k^n}\|_\infty^2 } + \frac{H^2\iota^2}{N_h^k \vee 1} \lesssim H^2\iota^2\sqrt{\frac{1}{N_h^k \vee 1}}. \label{eq:261-result1} \end{align} Similarly, for the second term in \eqref{equ:Ghk-var-diff}, with $W_{h+1}^{i} \coloneqq V^\star_{h+1}$, we have with probability at least $1-\frac{\delta}{2}$, \begin{align} \frac{1}{N_h^k(s,a) \vee 1}\sum_{n = 1}^{{N_h^k}} \left(P^{k^n}_h - P_{h, s,a}\right)V^{\star}_{h+1} \lesssim H\iota^2\sqrt{\frac{1}{N_h^k(s,a) \vee 1}}. \label{eq:261-result2} \end{align} Inserting \eqref{eq:261-result1} and \eqref{eq:261-result2} back into \eqref{equ:Ghk-var-diff} yields \begin{align} \left|G_{h,k}^2 - \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right| \lesssim H^2\iota^2\sqrt{\frac{1}{N_h^k(s,a) \vee 1}}. \label{eq:var-Vstar} \end{align} Consequently, the first term in \eqref{eq:control_Ghk} can be controlled as \begin{align} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{ \left|G_{h,k}^2 - \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) \right|}{N^{k}_h(s, a) \vee 1}} & \lesssim H\iota \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K \frac{1}{\left(N_h^k(s,a)\right)^{\frac{3}{4}} \vee 1} \nonumber \\ & \lesssim H^2(SC^\star)^{\frac{3}{4}} K^{\frac{1}{4}}\iota^2 , \label{equ:adv-J-22-G-1} \end{align} where the last inequality holds due to \eqref{equ:adv-J-12-result}. \paragraph{Step 2: controlling the second term of \eqref{eq:control_Ghk}.} The second term can be decomposed as \begin{align} &\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{\mathsf{Var}_{h, s,a}(V^{\star}_{h+1})}{N_h^k(s,a) \vee 1}} \nonumber\\ & \overset{\mathrm{(i)}}{\lesssim} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} \sum_{k = 1}^K \sqrt{\frac{C^\star \iota d_h^{\pi^\star}(s, a) \mathsf{Var}_{h, s,a}(V^{\star}_{h+1})}{k} \ind\left(a = \pi^\star_h(s)\right)} \nonumber \\ & \overset{\mathrm{(ii)}}{\lesssim} \sqrt{C^\star \iota} \sqrt{\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K \mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) } \sqrt{\sum_{h = 1}^H \sum_{(s,a) \in {\mathcal{S}}\times \mathcal{A}} \sum_{k = 1}^K \frac{1}{k}\ind\left(a = \pi^\star_h(s)\right) } \nonumber\\ &\lesssim \sqrt{H S C^\star K\iota^2} \sqrt{\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) }, \label{equ:adv-J-22-G-2} \end{align} where (i) follows from the facts $\frac{1}{N_h^k(s,a) \vee 1} \leq \frac{8\iota}{k d_h^{\mu}(s,a)}$ by Lemma~\ref{lem:binomial} and the definition of $C^\star$ in Assumption~\ref{assumption}, (ii) holds by the Cauchy-Schwarz inequality, and the final inequality comes from the fact that $\pi^\star$ is deterministic. We are then left with bounding $\sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\mathsf{Var}_{h, s,a}(V^{\star}_{h+1})$. Note that \begin{align} & \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\mathsf{Var}_{h, s,a}(V^{\star}_{h+1}) = \mathbb{E}_{s_1 \sim \rho, s_{h+1}\sim P_{h,s_{h},\pi_h^{\star}(s_h)}}\left[\sum_{h = 1}^H \mathsf{Var}_{h, s_h,\pi_h^{\star}(s_h)}(V^{\star}_{h+1})\right] \nonumber \\ & \overset{\mathrm{(i)}}{=} \mathbb{E}_{s_1 \sim \rho, s_{h+1}\sim P_{h,s_{h},\pi_h^{\star}(s_h)}} \left[\sum_{h = 1}^H \left( r_h\left(s_h, \pi^\star_h(s_h)\right) + V^{\star}_{h+1}(s_{h+1}) - V_h^\star(s_h) \right)^2\right] \nonumber \\ & \overset{\mathrm{(ii)}}{=} \mathbb{E}_{s_1 \sim \rho, s_{h+1}\sim P_{h,s_{h},\pi_h^{\star}(s_h)}} \left[\sum_{h = 1}^H \left( r_h(s_h, \pi^\star_h(s_h)) + V^{\star}_{h+1}(s_{h+1}) - V_h^\star(s_h) \right)\right]^2 \nonumber\\ & \overset{\mathrm{(iii)}}{=} \mathbb{E}_{s_1 \sim \rho, s_{h+1}\sim P_{h,s_{h},\pi_h^{\star}(s_h)}} \left[ \left(\sum_{h = 1}^H r_h(s_h, \pi^\star_h(s_h)) \right)- V_1^\star(s_1) \right]^2 \overset{\mathrm{(iv)}}{\leq} H^2 , \label{eq:var-Vstar-sum} \end{align} where (i) follows from Bellman's optimality equation, (ii) follows from the Markov property, (iii) holds due to the fact that $V_{H+1}^\star(s) = 0$ for all $s\in {\mathcal{S}}$, and (iv) arises from the fact $r_h(s,a) \leq 1$ for all $(s,a,h)\in{\mathcal{S}}\times\mathcal{A}\times[H]$. Substituting \eqref{eq:var-Vstar-sum} back into \eqref{equ:adv-J-22-G-2}, we get \begin{align} \label{eq:second_term_Ghk} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{\mathsf{Var}_{h, s,a}(V^{\star}_{h+1})}{N_h^k(s,a) \vee 1}} &\lesssim \sqrt{H^3 S C^\star K\iota^2}. \end{align} \paragraph{Step 4: combing the results.} Combining \eqref{equ:adv-J-22-G-1} and \eqref{eq:second_term_Ghk} with \eqref{eq:control_Ghk} yields \begin{align} \sum_{h = 1}^H \sum_{(s,a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\sum_{k = 1}^K\sqrt{\frac{1}{N^{k}_h(s, a) \vee 1}} G_{h,k} & \lesssim H^2(SC^\star)^{\frac{3}{4}} K^{\frac{1}{4}}\iota^2 + \sqrt{H^3 S C^\star K\iota^2} \notag \\&\lesssim \sqrt{H^3 S C^\star K\iota^2} + H^{2.5}SC^\star\iota^3. \end{align} \subsection{Proof of Lemma~\ref{lem:lcb-adv-bonus-upper}} \label{proof:lem:lcb-adv-bonus-upper} In view of \eqref{eq:defn-xi-kh-123}, we can decompose the term of interest into \begin{align*} \bigg| \sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \xi_h^{k^n}\bigg| &\leq |U_1| +|U_2|, \end{align*} where \begin{subequations} \begin{align} U_1 &\coloneqq \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \big(P^{k^n}_{h} - P_{h, s,a} \big)\big(\overline{V}^{ k^n}_{h+1} - V^{k^n}_{h+1} \big), \label{eq:defn-U1-1}\\ U_2 &\coloneqq \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \left(P_{h,s,a} - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \right)\overline{V}^{ k^n}_{h+1}. \label{eq:defn-U1-2} \end{align} \end{subequations} Next, we turn to controlling these two terms separately with the assistance of Lemma~\ref{lemma:martingale-union-all}. \paragraph{Step 1: controlling $U_1$.} In the following, we invoke Lemma~\ref{lemma:martingale-union-all} to control $U_1$ in \eqref{eq:defn-U1-1}. Let us set \begin{align*} W_{h+1}^{i} \coloneqq \overline{V}_{h+1}^i - V_{h+1}^i, \qquad \text{and} \qquad u_h^i(s,a,N) \coloneqq \eta_{N_h^i(s,a)}^N \geq 0, \end{align*} which indicates that \begin{align*} \|W_{h+1}^{i}\|_\infty \leq \|\overline{V}_{h+1}^i \|_{\infty} + \|V_{h+1}^i\|_{\infty} \leq 2H \eqqcolon C_{\mathrm{w}}, \end{align*} and \begin{align} \max_{N, h, s, a\in \big(\{0\} \cup [K]\big) \times[H] \times {\mathcal{S}}\times \mathcal{A}} \eta_{N_{h}^{i}(s,a)}^{N} \leq \frac{2H}{N \vee 1} \eqqcolon C_{\mathrm{u}}. \label{U1-cu} \end{align} Here, the last inequality follows since (according to Lemma~\ref{lemma:property of learning rate} and the definition in \eqref{equ:learning rate notation}) \begin{align*} \eta_{N_{h}^{i}(s,a)}^{N} & \leq\frac{2H}{N \vee 1},\qquad\text{if } 0\le N_{h}^{i}(s,a)\le N;\\ \eta_{N_{h}^{i}(s,a)}^{N} & =0,\qquad\quad ~\text{if }N_{h}^{i}(s,a)>N. \end{align*} To continue, it can be seen from \eqref{eq:sum-eta-n-N} that \begin{align} 0 \leq \sum_{n=1}^N u_h^{k_h^n(s,a)}(s,a, N) = \sum_{n=1}^N \eta_{n}^N \leq 1 \label{eq:sum-uh-k-s-a-123} \end{align} holds for all $(N,s,a) \in [K] \times {\mathcal{S}}\times \mathcal{A}$. Therefore, choosing $N = N_h^k(s,a) = N_h^k$ for any $(s,a)$ and applying Lemma~\ref{lemma:martingale-union-all} with the above quantities, we arrive at \begin{align} |U_1| &= \left|\sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \big(P^{k^n}_{h} - P_{h, s,a} \big)\big(\overline{V}^{ k^n}_{h+1} - V^{k^n}_{h+1} \big)\right| = \left|\sum_{i=1}^k X_i\left(s,a, h, N_h^k\right)\right| \nonumber\\ &\lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{n = 1}^{N_h^k} u_h^{k^n}(s,a, N_h^k) \mathsf{Var}_{h,s,a} \big(W_{h+1}^{k^n} \big)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N \vee 1}} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta} \nonumber \\ & \asymp \sqrt{\frac{H\iota^2}{N_h^k \vee 1}}\sqrt{\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \mathsf{Var}_{h, s,a} \big(\overline{V}^{k^n}_{h+1}-V^{k^n}_{h+1} \big) } + \frac{H^2\iota^2}{N_h^k \vee 1} \label{lemma1:equ4-sub} \\ & \lesssim \sqrt{\frac{H\iota^2}{N_h^k \vee 1}}\sqrt{\sigma^{\mathsf{adv}, k^{N_h^k}+1}_h(s,a) - \big(\mu^{\mathsf{adv}, k^{N_h^k}+1}_h(s,a)\big)^2} + \frac{H^{7/4}\iota^2}{(N_h^k \vee 1)^{3/4}} + \frac{H^2\iota^2}{N_h^k \vee 1}. \label{lemma1:equ4} \end{align} with probability at least $1-\delta$. Here, the proof of the inequality~\eqref{lemma1:equ4} is postponed to Appendix~\ref{sec:proof:lemma1:equ4} in order to streamline the presentation of the analysis. \paragraph{Step 2: bounding $U_2$.} Making use of the result in \eqref{equ:definition-ref-refmean}, we arrive at \begin{align*} \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \overline{V}^{ k^n}_{h+1} = \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i} \overline{V}^{ \mathsf{next},k^i}_{h+1}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} . \end{align*} To continue, for any $(s,a)\in {\mathcal{S}}\times \mathcal{A}$, we rewrite and rearrange $U_2$ (cf.~\eqref{eq:defn-U1-2}) as follows: \begin{align*} U_2 & = \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \left(P_{h,s,a} - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}}{\widehat{N}_h^{\mathsf{epo},m^n-1}(s,a) \vee 1} \right)\overline{V}^{ k^n}_{h+1} \\ &= \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \left(P_{h,s,a}\overline{V}^{k^n}_{h+1} - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}\overline{V}^{ \mathsf{next},k^i}_{h+1}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \right) \\ & \overset{\mathrm{(i)}}{=} \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \left(\frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_{h,s,a}}{\widehat{N}_h^{\mathsf{epo},m^n-1}(s,a) \vee 1} \overline{V}^{k^n}_{h+1} - \frac{\sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}} P_h^{k^i}\overline{V}^{ \mathsf{next},k^i}_{h+1}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \right) \\ &= \sum_{n=1}^{N_h^k} \frac{\eta_n^{N_h^k}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1} \sum_{i= N_h^{(m^n-1,1)} + 1 }^{ N_h^{(m^n,1)}}\left(P_{h,s,a} - P_h^{k^i}\right) \overline{V}^{ \mathsf{next},k^i}_{h+1}\\ & \overset{\mathrm{(ii)}}{=} \sum_{i=1}^{N_h^k} \left(\sum_{n= N_h^{(m^i+1,1)}+1}^{N_h^{(m^i+2,1)} \wedge N_h^{k}} \frac{\eta_n^{N_h^k}}{\widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a) \vee 1}\right)\left(P_{h,s,a} - P_h^{k^i}\right) \overline{V}^{ \mathsf{next},k^i}_{h+1}\\ & = \sum_{i=1}^{N_h^k} \left(\sum_{n= N_h^{(m^i+1,1)}+1}^{N_h^{(m^i+2,1)} \wedge N_h^{k}} \frac{\eta_n^{N_h^k}}{\widehat{N}_h^{\mathsf{epo}, m^i} \vee 1}\right)\left(P_{h,s,a} - P_h^{k^i}\right) \overline{V}^{ \mathsf{next},k^i}_{h+1}, \end{align*} where (i) follows from the fact that $ N_h^{(m^n,1)} - N_h^{(m^n-1,1)} = \widehat{N}_h^{\mathsf{epo}, m^n-1}(s,a)$, and (ii) is obtained by rearranging terms with respect to $i$ (the terms with respect to $\overline{V}^{ \mathsf{next},k^i}_{h+1}$ will only be added during the epoch $m^i+1$), and the last equality holds since $m^n -1 = m^i$ for all $n= N_h^{(m^i+1,1)}+1, N_h^{(m^i+1,1)}+2, N_h^{(m^i+2,1)}$. With the above relation in mind, we are ready to invoke Lemma~\ref{lemma:martingale-union-all} to control $U_2$. To continue, for any episode $j\leq k$, let us denote by $m(j)$ the index of the epoch in which episode $j$ happens (with slight abuse of notation). Let us set \begin{align*} W_{h+1}^j \coloneqq \overline{V}_{h+1}^{\mathsf{next},j}, \qquad \text{and} \qquad u_h^j(s,a,N) \coloneqq \sum_{n=N_h^{(m(j)+1,1)}+1}^{N_h^{(m(j)+2,1)} \wedge N} \frac{\eta_n^N}{\widehat{N}_h^{\mathsf{epo}, m(j)}(s,a) \vee 1}. \end{align*} As a result, we see that \begin{align*} \|W_{h+1}^{j}\|_\infty \leq \|\overline{V}^{\mathsf{next},j}_{h+1}\|_\infty \leq H \eqqcolon C_{\mathrm{w}} \end{align*} and the following fact (which will be established in Appendix~\ref{sec:proof:equ:stepsize-bound}) \begin{align} 0 \leq u_h^j(s,a,N) = \sum_{n=N_h^{(m(j)+1,1)}+1}^{N_h^{(m(j)+2,1)} \wedge N} \frac{\eta_n^N}{\widehat{N}_h^{\mathsf{epo}, m(j)}(s,a) \vee 1} \leq \frac{64 e^2 \iota }{N \vee 1} \eqqcolon C_u\label{equ:stepsize-bound} \end{align} holds for all $(j,h,s,a) \in [K]\times [H]\times {\mathcal{S}}\times \mathcal{A}$ with probability at least $1-\delta$. Given that $N = N_h^k(s,a) = N_h^k$, applying Lemma~\ref{lemma:martingale-union-all} with the above quantities, we can show that for any state-action pair $(s,a)\in{\mathcal{S}}\times \mathcal{A}$, \begin{align} \left|U_2\right| &= \left|\sum_{i=1}^{N_h^k} \left(\sum_{n= N_h^{(m^i+1,1)}+1}^{N_h^{(m^i+2,1)} \wedge N_h^{k}} \frac{\eta_n^{N_h^k}}{\widehat{N}_h^{\mathsf{epo},m^i} \vee 1}\right)\left(P_{h,s,a} - P_h^{k^i}\right) \overline{V}^{ \mathsf{next},k^i}_{h+1}\right| = \left|\sum_{j=1}^k X_j\left(s,a, h, N_h^k\right)\right| \nonumber \\ &\lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{i = 1}^{N_h^k(s,a)} u_h^{k_h^i(s,a)}(s,a,N) \mathsf{Var}_{h, s,a} \big(W_{h+1}^{k_h^i(s,a)} \big)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N \vee 1}} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta} \nonumber\\ & \lesssim \sqrt{\frac{\iota^3}{N_h^k \vee 1}}\sqrt{\frac{1}{N_h^k \vee 1}\sum_{i= 1}^{N_h^k} \mathsf{Var}_{h, s,a}\big(\overline{V}^{ \mathsf{next} ,k^i}_{h+1}\big)} + \frac{H \iota^3 }{N_h^k \vee 1}\nonumber\\ & \lesssim \sqrt{\frac{\iota^3}{N_h^k \vee 1}}\sqrt{\sigma^{\mathsf{ref} , k^{N_h^k}+1}_h(s,a) - \big(\mu^{\mathsf{ref} , k^{N_h^k}+1}_h(s,a) \big)^2} + \frac{H \iota^3}{(N_h^k \vee 1)^{3/4}} . \label{lemma1:equ5} \end{align} To streamline the presentation of the analysis, we shall postpone the proof of \eqref{lemma1:equ5} to Appendix~\ref{sec:proof:eq:var-Vref}. \paragraph{Step 3: summing up.} Combining the bounds in \eqref{lemma1:equ4} and \eqref{lemma1:equ5} yields that: for any state-action pair $(s,a)\in{\mathcal{S}}\times \mathcal{A}$, \begin{align} \bigg| \sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \xi_h^{k^n}\bigg| &\leq |U_1| +|U_2| \nonumber\\ & \lesssim~\sqrt{\frac{H\iota^2}{N_h^k \vee 1}}\sqrt{\sigma^{\mathsf{adv}, k^{N_h^k}+1}_h(s,a) - \big(\mu^{\mathsf{adv}, k^{N_h^k}+1}_h(s,a) \big)^2} \nonumber \\ &\quad + \sqrt{\frac{\iota^3}{N_h^k \vee 1}}\sqrt{\sigma^{\mathsf{ref} , k^{N_h^k}+1}_h(s,a) - \big(\mu^{\mathsf{ref} , k^{N_h^k}+1}_h(s,a) \big)^2} + c_{\mathrm{b}} \frac{H^{7/4}\iota^2}{(N_h^k \vee 1)^{3/4}} + c_{\mathrm{b}}\frac{H^2\iota^2}{N_h^k \vee 1} \nonumber\\ & \leq \overline{B}^{k^{N_h^k}+1}_h(s,a) + c_{\mathrm{b}} \frac{H^{7/4}\iota^2}{(N_h^k \vee 1)^{3/4}} + c_{\mathrm{b}}\frac{H^2\iota^2}{N_h^k \vee 1} \label{lemma1:equ6} \end{align} holds for some sufficiently large constant $c_{\mathrm{b}}>0$, where the last line follows from the definition of $\overline{B}^{k^{N_h^k}+1}_h(s,a)$ in line~\ref{eq:line-number-19} of Algorithm~\ref{algo:subroutine}. As a consequence of the inequality~\eqref{lemma1:equ6}, for any $(s,a)\in{\mathcal{S}} \times \mathcal{A}$, one has \begin{align*} \bigg| \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \xi_h^{k^n} \bigg| \le \overline{B}^{k^{N_h^k}+1}_h(s,a) + c_{\mathrm{b}} \frac{H^{7/4}\iota^2}{(N_h^k \vee 1)^{3/4}} + c_{\mathrm{b}}\frac{H^2\iota^2}{N_h^k \vee 1} \leq \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \overline{b}^{k^n+1}_h, \end{align*} where the last inequality holds due to \eqref{lemma1:equ10}. We have thus concluded the proof of Lemma~\ref{lem:lcb-adv-bonus-upper}. \subsubsection{Proof of inequality~\eqref{lemma1:equ4}} \label{sec:proof:lemma1:equ4} To establish the inequality~\eqref{lemma1:equ4}, it is sufficient to consider the difference $$W_1 := \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n\mathsf{Var}_{h, s,a}(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1}) - {\sigma}^{\mathsf{adv}, k^{N_h^k}+1}_h(s,a) + ({\mu}^{\mathsf{adv}, k^{N_h^k}+1}_h(s,a))^2. $$ Before continuing, it is easily verified that if $N_h^k= N_h^k(s,a) = 0$, the basic fact $\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} = 0$ leads to $W_1= 0$, and therefore, \eqref{lemma1:equ4} holds directly. The remainder of the proof is thus dedicated to controlling $W_1$ when $N_h^k= N_h^k(s,a) \geq 1$. Recalling the definition in \eqref{lemma1:equ2} \begin{equation} \mathsf{Var}_{h, s,a}(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n}) = P_{h, s,a}(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n})^{2} - \left(P_{h, s,a}(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n}) \right)^2, \label{eq:variance-nonnegative} \end{equation} we can take this result together with \eqref{eq:recursion_mu_sigma_adv} to yield \begin{align} W_1 & = \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n P_{h, s,a}(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n})^{2} - \sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \left(P_{h, s,a}(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n}) \right)^2 \nonumber \\ &\qquad \qquad+ \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P^{k^n}_{h}(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1})\Big)^2 - \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P_h^{k^n}(V_{h+1}^{k^n} - \overline{V}_{h+1}^{k^n})^2 \nonumber\\ & \le \underbrace{ \Bigg|\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k}(P^{k^n}_{h}-P_{h, s,a})(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})^{ 2} \Bigg| }_{=: W_{1}^1} \nonumber \\ &\qquad \qquad+ \underbrace{ \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P^{k^n}_{h}(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big)^2 - \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \Big(P_{h, s,a}(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big)^2}_{=: W_{1}^2}. \label{equ:lemma4 vr 2} \end{align} It then boils down to control the above two terms in \eqref{equ:lemma4 vr 2} separately when $N_h^k = N_h^k(s,a) \geq 1$. \paragraph{Step 1: controlling $W_1^1$.} To control $W_1^1$, we shall invoke Lemma~\ref{lemma:martingale-union-all} by setting \begin{align*} W_{h+1}^{i} \coloneqq (V_{h+1}^i - \overline{V}_{h+1}^i)^2, \qquad \text{and} \qquad u_h^i(s,a,N) \coloneqq \eta_{N_h^i(s,a)}^N \geq 0, \end{align*} which obey \begin{align*} \|W_{h+1}^{i}\|_\infty \leq \|\overline{V}_{h+1}^i \|_\infty^2 + \|V_{h+1}^i\|_\infty^2 \leq 2H^2 \eqqcolon C_\mathrm{w}. \end{align*} Invoking the facts in \eqref{U1-cu} and \eqref{eq:sum-uh-k-s-a-123}, we arrive at \begin{align*} \frac{2H}{N \vee 1} &\eqqcolon C_{\mathrm{u}} \end{align*} and \begin{align*} 0 &\leq \sum_{n=1}^N u_h^{k_h^n(s,a)}(s,a, N) \leq 1, \qquad \forall (N,s,a) \in [K] \times {\mathcal{S}}\times \mathcal{A}. \end{align*} Therefore, choosing $N = N_h^k(s,a) = N_h^k$ for any $(s,a)$ and applying Lemma~\ref{lemma:martingale-union-all} with the above quantities, we arrive at, with probability at least $1-\delta$, \begin{align} |W_1^1| &= \Bigg|\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k}(P^{k^n}_{h}-P_{h, s,a})(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})^{ 2} \Bigg| = \left|\sum_{i=1}^k X_i\left(s,a, h, N_h^k\right)\right| \nonumber\\ &\lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{n = 1}^{N_h^k} u_h^{k^n}(s,a, N_h^k) \mathsf{Var}_{h,s,a} \big(W_{h+1}^{k^n} \big)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N \vee 1}} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta} \nonumber \\ & \lesssim \sqrt{\frac{H}{N_h^k \vee 1}\iota^2}\sqrt{\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \|W_{h+1}^{k^n}\|_\infty^2 } + \frac{{H^3}\iota^2}{N_h^k \vee 1} \lesssim \sqrt{\frac{H^5}{N_h^k \vee 1}\iota^2} + \frac{H^3\iota^2}{N_h^k \vee 1}.\label{eq:W11-result} \end{align} \paragraph{Step 2: controlling $W_1^2$.} Observe that Jensen's inequality gives \begin{align} \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P_{h, s,a}(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big)^2 &\leq \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \Big(P_{h, s,a}(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big)^2, \label{eq:extra-result1} \end{align} due to the fact $\sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} = 1$ (see \eqref{eq:sum-eta-n-N} and \eqref{equ:learning rate notation}). Plugging the above relation into \eqref{equ:lemma4 vr 2} gives \begin{align} W_1^2 &\le\Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P^{k^n}_{h}(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big)^2 - \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} P_{h, s,a}(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big)^2 \nonumber\\ & = \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} (P^{k^n}_{h}-P_{h, s,a}) (V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big) \cdot \Big(\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} (P^{k^n}_{h}+P_{h, s,a}) (V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big) . \label{equ:lemma4vr4} \end{align} Note that the first term in \eqref{equ:lemma4vr4} is exactly $|U_1|$ defined in \eqref{eq:defn-U1-1}, which can be controlled by invoking \eqref{lemma1:equ4-sub} to achieve that, with probability at least $1-\delta$, \begin{align} & \Big| \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} (P^{k^n}_{h}-P_{h, s,a}) (V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1})\Big| \nonumber \\ & \lesssim \sqrt{\frac{H}{N_h^k \vee 1}\iota^2}\sqrt{\sum_{n = 1}^{N_h^k} \eta^{N_h^k}_n \mathsf{Var}_{h, s,a} \big(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1} \big) } + \frac{H^2\iota^2}{N_h^k \vee 1} \lesssim \sqrt{\frac{H^3 \iota^2}{N_h^k \vee 1}} + \frac{H^2}{N_h^k \vee 1}\iota^2, \end{align} where the final inequality holds since $\mathsf{Var}_{h, s,a} \big(V^{k^n}_{h+1} - \overline{V}^{k^n}_{h+1} \big)\lesssim H^2$ and the fact in \eqref{eq:sum-eta-n-N}. In addition, the second term in \eqref{equ:lemma4vr4} can be controlled straightforwardly by \begin{equation*} \Big|\sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \left(P^{k^n}_{h}+P_{h, s,a}\right) \left(V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1}\right)\Big| \le \sum_{n = 1}^{{N_h^k}} \eta_n^{N_h^k} \left( \big\|P^{k^n}_{h}\big\|_1 +\big\|P_{h, s,a}\big\|_1 \right) \big\|V^{k^n}_{h+1} - \overline{V}^{ k^n}_{h+1} \big\|_{\infty} \leq 2H, \end{equation*} where we have used the fact in \eqref{eq:sum-eta-n-N}, $\big\|V^{k^n}_{h+1} -\overline{V}^{k^n}_{h+1}\big\|_{\infty}\leq H$ and $\big\|P^{k^n}_{h}\big\|_1 =\big\| P_{h, s,a}\big\|_1=1$. Taking the above two facts collectively with \eqref{equ:lemma4vr4} yields \begin{equation} \label{eq:bound_I32} W_1^2 \lesssim \sqrt{\frac{H^5 \iota^2}{N_h^k \vee 1}} + \frac{H^3 \iota^2}{N_h^k \vee 1}. \end{equation} \paragraph{Step 3: summing up.} Plugging the results in \eqref{eq:W11-result} and \eqref{eq:bound_I32} back into \eqref{equ:lemma4 vr 2}, we have \begin{align*} W_1 \leq W_1^1 + W_1^2 \lesssim \sqrt{\frac{H^5 \iota^2}{N_h^k \vee 1}} + \frac{H^3 \iota^2}{N_h^k \vee 1}, \end{align*} which leads to the desired result \eqref{lemma1:equ4} directly. \subsubsection{Proof of inequality~\eqref{equ:stepsize-bound}}\label{sec:proof:equ:stepsize-bound} To begin with, let us recall two pieces of notation that shall be used throughout this proof: \begin{enumerate} \item $m(j)$: the index of the epoch in which the $j$-th episode occurs. \item $\widehat{N}_h^{\mathsf{epo}, m}(s,a)$: the value of $\widehat{N}_h^{(m, L_m+1)}(s,a)$, representing the number of visits to $(s,a)$ in the entire $m$-th epoch with length $L_m = 2^m$. \end{enumerate} Applying \eqref{equ:binomial} and taking the union bound over $\left( m(j), h, s,a\right) \in [M]\times[H]\times{\mathcal{S}}\times\mathcal{A}$ yield \begin{align} \widehat{N}_h^{\mathsf{epo}, m(j)}(s,a) \vee 1 \geq \frac{2^{m(j)} d_h^{\mu}(s,a)}{8\log\left(\frac{SAT}{\delta}\right)} \label{eq:N-hat-mj} \end{align} with probability at least $1-\delta/2$. For any epoch $m$, if we denote by $k_{\mathrm{last}}(m)$ the index of the last episode in the $m$-th epoch, we can immediately see that \begin{align} k_{\mathrm{last}}(m) = \sum_{i=1}^m L_i = \sum_{i=1}^m 2^i = 2^{m+1}-2 \leq 2^{m+1}. \label{eq:k-last-def} \end{align} Applying \eqref{equ:binomial} again and taking the union bound over $\left( m(j), h, s,a\right) \in [M]\times[H]\times{\mathcal{S}}\times\mathcal{A}$, one can guarantee that for every $n \in [N_h^{(m(j)+1,1)}, N_h^{(m(j)+2,1)}]$, with probability at least $1-\delta/2$, \begin{align} N_h^{(m(j)+1,1)} \leq n \leq N_h^{(m(j)+2,1)} &= N_h^{k_{\mathrm{last}}(m(j)+1)} \nonumber\\ &\leq N_h^{2^{m(j)+2}} \leq \begin{cases} e^2 2^{m(j)+2} d_h^{\mu}(s,a) & \text{ if } 2^{m(j)+2} d_h^{\mu}(s,a) \geq \log\left(\frac{SAT}{\delta}\right)\\ 2e^2 \log\left(\frac{SAT}{\delta}\right)& \text{ if } 2^{m(j)+2} d_h^{\mu}(s,a) \leq 2\log\left(\frac{SAT}{\delta}\right) \end{cases} .\label{eq:N-mj-plus-2} \end{align} Combine the above results to yield \begin{align} \begin{cases} \widehat{N}_h^{\mathsf{epo}, m(j)}(s,a) \vee 1 \overset{\mathrm{(i)}}{\geq} \frac{2^{m(j)} d_h^{\mu}(s,a)}{8\log\left(\frac{SAT}{\delta}\right)} \overset{\mathrm{(ii)}}{\geq} \frac{1}{32 e^2 \log\left(\frac{SAT}{\delta}\right)} n, & \text{ if } 2^{m(j)+2} \cdot d_h^{\mu}(s,a) \geq \log\left(\frac{SAT}{\delta}\right),\\ \widehat{N}_h^{\mathsf{epo},m(j)}(s,a) \vee 1 \geq 1 \overset{\mathrm{(iii)}}{\geq} \frac{1}{2e^2 \log\left(\frac{SAT}{\delta}\right)} n & \text{ if } 2^{m(j)+2}\cdot d_h^{\mu}(s,a) \leq 2\log\left(\frac{SAT}{\delta}\right), \end{cases} \end{align} where (i) follows from \eqref{eq:N-hat-mj}, (ii) and (iii) hold due to \eqref{eq:N-mj-plus-2}. As a result, we arrive at \begin{align*} \sum_{n=N_h^{(m(j)+1,1)}+1}^{N_h^{(m(j)+2,1)} \wedge N} \frac{\eta_n^N}{\widehat{N}_h^{\mathsf{epo},m(j)}(s,a) \vee 1} &\leq \sum_{n=N_h^{(m(j)+1,1)}+1}^{N_h^{(m(j)+2,1)} \wedge N} \frac{32e^2 \log\left(\frac{SAT}{\delta}\right) \eta_n^N}{n} \\ &\leq \sum_{n=N_h^{(m(j)+1,1)}+1}^{N} \frac{32e^2 \log\left(\frac{SAT}{\delta}\right) \eta_n^N}{n} \leq \frac{64 e^2 \log\left(\frac{SAT}{\delta}\right) }{N \vee 1}, \end{align*} where the last inequality holds since $\sum_{i = 1}^{N} \frac{\eta^{N}_i}{i} \le \frac{2}{N \vee 1}$ (see Lemma~\ref{lemma:property of learning rate}). \subsubsection{Proof of inequality~\eqref{lemma1:equ5}}\label{sec:proof:eq:var-Vref} In this subsection, we intend to control the following term $$W_2 := \frac{1}{N_h^k \vee 1}\sum_{n = 1}^{{N_h^k}} \mathsf{Var}_{h, s,a}\left(\overline{V}^{\mathsf{next}, k^n}_{h+1}\right) - \left( {\sigma}^{\mathsf{ref}, k^{N_h^k}+1}_h(s,a) -\left({\mu}^{\mathsf{ref}, k^{N_h^k}+1}_h(s,a) \right)^2 \right) $$ for all $(s,a) \in {\mathcal{S}}\times \mathcal{A}$. First, it is easily seen that if $N_h^k= 0$, then we have $W_2 =0$ and thus \eqref{lemma1:equ5} is satisfied. Therefore, the remainder of the proof is devoted to verifying \eqref{lemma1:equ5} when $N_h^k=N_h^k(s,a) \geq 1$. Combining the expression \eqref{eq:recursion_mu_sigma_ref} with the following definition \begin{equation*} \mathsf{Var}_{h, s,a}\left(\overline{V}_{h+1}^{\mathsf{next}, k^n} \right) = P_{h, s,a}\left(\overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^{2} - \left(P_{h, s,a}\overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^2, \end{equation*} we arrive at \begin{align} W_2 &= \frac{1}{{N_h^k} \vee 1}\sum_{n=1}^{N_h^k} \left( P_{h, s,a}\left(\overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^{2} - \left(P_{h, s,a}\overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^2 \right) \nonumber \\ & \qquad\qquad - \frac{1}{N_h^k \vee 1}\sum_{n = 1}^{{N_h^k}} P_h^{k^n}\left(\overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^2 + \left(\frac{1}{N_h^k \vee 1}\sum_{n=1}^{N_h^k} P_h^{k^n} \overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^2 \nonumber \\ & = \underbrace{ \frac{1}{N_h^k \vee 1}\sum_{n = 1}^{{N_h^k}}\left(P_{h, s,a} - P^{k^n}_{h} \right)\left(\overline{V}^{\mathsf{next}, k^n}_{h+1}\right)^2 }_{=: W_2^1} + \underbrace{ \left(\frac{1}{N_h^k \vee 1}\sum_{n=1}^{N_h^k} P_h^{k^n} \overline{V}_{h+1}^{\mathsf{next}, k^n}\right)^2 - \frac{1}{N_h^k \vee 1}\sum_{n = 1}^{{N_h^k}} \left(P_{h, s,a}\overline{V}^{\mathsf{next}, k^n}_{h+1}\right)^2}_{=:W_2^2} . \label{equ:lemma4 vr 6} \end{align} In the sequel, we intend to control the terms in \eqref{equ:lemma4 vr 6} separately. \paragraph{Step 1: controlling $W_2^1$.} The first term $W_2^1$ can be controlled by invoking Lemma~\ref{lemma:martingale-union-all} and set \begin{align*} W_{h+1}^i \coloneqq \left(\overline{V}_{h+1}^{\mathsf{next},i}\right)^2, \qquad \text{and} \qquad u_h^i(s,a,N) \coloneqq \frac{1}{N } \eqqcolon C_u. \end{align*} To proceeding, with the fact \begin{align*} \left\|W_{h+1}^{i}\right\|_\infty \leq \left\|\overline{V}^{\mathsf{next},i}_{h+1}\right\|_\infty^2 \leq H^2 \eqqcolon C_{\mathrm{w}} \end{align*} and $N = N_h^k(s,a) = N_h^k$, applying Lemma~\ref{lemma:martingale-union-all} with the above quantities, we have for all state-action pair $(s,a)\in{\mathcal{S}}\times \mathcal{A}$, \begin{align} \left|W_2^1\right| &= \left|\frac{1}{N_h^k}\sum_{n = 1}^{{N_h^k}}\left(P_{h, s,a} - P^{k^n}_{h} \right)\left(\overline{V}^{\mathsf{next}, k^n}_{h+1}\right)^2 \right| = \left|\sum_{i=1}^k X_i\left(s,a, h, N_h^k\right)\right| \nonumber \\ &\lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{n = 1}^{N_h^k(s,a)} u_h^{k_h^n(s,a)}(s,a,N) \mathsf{Var}_{h, s,a} \left(W_{h+1}^{k_h^n(s,a)} \right)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N }} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta} \nonumber\\ & \lesssim \sqrt{\frac{\iota^2}{N_h^k }}\sqrt{\|W_{h+1}^{i}\|_\infty^2} + \frac{H^2 \iota^2 }{N_h^k } \lesssim \sqrt{\frac{H^4 \iota^2 }{N_h^k}} + \frac{H^2\iota^2}{N_h^k}. \label{eq:W21-final-result} \end{align} \paragraph{Step 2: controlling $W_2^2$.} Towards controlling $W_2^2$ in \eqref{equ:lemma4 vr 6}, we observe that by Jensen's inequality, \begin{align*} \Big(\frac{1}{{N_h^k }}\sum_{n=1}^{N_h^k} P_{h, s,a} \overline{V}_{h+1}^{\mathsf{next}, k^n}\Big)^2 &\leq \frac{1}{N_h^k }\sum_{n = 1}^{{N_h^k}} \left(P_{h, s,a}\overline{V}^{\mathsf{next},k^n}_{h+1}\right)^2. \end{align*} Equipped with this relation, $W_2^2$ satisfies \begin{align} W_2^2&\leq \left(\frac{1}{N_h^k }\sum_{n=1}^{N_h^k} P_h^{k^n} \overline{V}_{h+1}^{\mathsf{next},k^n}\right)^2 - \left(\frac{1}{N_h^k }\sum_{n=1}^{N_h^k} P_{h, s,a} \overline{V}_{h+1}^{\mathsf{next},k^n}\right)^2 \nonumber \\ &= \Big(\frac{1}{N_h^k }\sum_{n=1}^{N_h^k} \left( P_h^{k^n} -P_{h, s,a}\right) \overline{V}_{h+1}^{\mathsf{next},k^n}\Big) \cdot \Big(\frac{1}{N_h^k}\sum_{n=1}^{N_h^k} \left( P_h^{k^n} +P_{h, s,a}\right) \overline{V}_{h+1}^{\mathsf{next},k^n}\Big). \label{equ:lemma4vr5} \end{align} As for the first term in \eqref{equ:lemma4vr5}, let us set \begin{align*} W_{h+1}^i \coloneqq \overline{V}_{h+1}^{\mathsf{next},i}, \qquad \text{and} \qquad u_h^i(s,a,N) \coloneqq \frac{1}{N } \eqqcolon C_u, \end{align*} which satisfy \begin{align*} \big\|W_{h+1}^{i}\big\|_\infty \leq \big\|\overline{V}^{\mathsf{next},i}_{h+1}\big\|_\infty \leq H \eqqcolon C_{\mathrm{w}}. \end{align*} For any $(s,a)$, Lemma~\ref{lemma:martingale-union-all} together with the above quantities and $N = N_h^k = N_h^k(s,a)$ gives \begin{align*} &\left|\frac{1}{N_h^k }\sum_{n=1}^{N_h^k} \left( P_h^{k^n} -P_{h, s,a}\right) \overline{V}_{h+1}^{\mathsf{next},k^n}\right| \\ &\lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{n = 1}^{N_h^k(s,a)} u_h^{k_h^n(s,a)}(s,a,N) \mathsf{Var}_{h, s,a} \big(W_{h+1}^{k_h^n(s,a)} \big)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N }} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta}\\ & \lesssim \sqrt{\frac{\iota^2}{N_h^k }}\sqrt{\left\|W_{h+1}^{k_h^n(s,a)}\right\|_\infty^2} + \frac{H \iota^2 }{N_h^k } \lesssim \sqrt{\frac{H^2 \iota^2 }{N_h^k}} + \frac{H\iota^2}{N_h^k} \end{align*} with probability at least $1-\delta$. In addition, the second term can be bounded straightforwardly by \begin{equation*} \Big|\frac{1}{N_h^k }\sum_{n=1}^{N_h^k} \big( P_h^{k^n} +P_{h, s,a}\big) \overline{V}_{h+1}^{\mathsf{next},k^n}\Big| \le \frac{1}{N_h^k}\sum_{n = 1}^{{N_h^k}} \left( \big\|P^{k^n}_{h}\big\|_1 +\big\|P_{h, s,a}\big\|_1 \right) \big\|\overline{V}_{h+1}^{\mathsf{next},k^n}\big\|_{\infty} \leq 2H, \end{equation*} where the last inequality is valid since $\big\|\overline{V}_{h+1}^{\mathsf{next},k^n}\big\|_{\infty}\leq H$ and $\big\|P^{k^n}_{h}\big\|_1 =\big\| P_{h, s,a}\big\|_1=1$. Substitution of the above two observations back into \eqref{equ:lemma4vr5} yields \begin{equation} \label{eq:bound_I42} W_2^2 \lesssim \sqrt{\frac{H^4}{N_h^k \vee 1}\iota^2} + \frac{H^2}{N_h^k \vee 1} \iota^2. \end{equation} \paragraph{Step 3: combining the above results.} Plugging the results in \eqref{eq:W21-final-result} and \eqref{eq:bound_I42} into \eqref{equ:lemma4 vr 6}, we reach \begin{align*} W_2 \leq W_2^1 + W_2^2 \lesssim \sqrt{\frac{H^4}{N_h^k \vee 1}\iota^2} + \frac{H^2}{N_h^k \vee 1}\iota^2, \end{align*} thus establishing the desired inequality~\eqref{lemma1:equ5}. \section{Discussions} \label{sec:discussions} Focusing on model-free paradigms, this paper has developed near-optimal sample complexities for some variants of pessimistic Q-learning algorithms --- armed with lower confidence bounds and variance reduction --- for offline RL. These sample complexity results, taken together with the analysis framework developed herein, open up a few exciting directions for future research. For example, the pessimistic Q-learning algorithms can be deployed in conjunction with their optimistic counterparts (e.g., \citet{jin2018q,li2021breaking,zhang2020almost}), when additional online data can be acquired to fine-tune the policy \citep{xie2021policy}. In addition, the $\varepsilon$-range for {\sf LCB-Q-Advantage}\xspace to attain sample optimality remains somewhat limited (i.e., $\varepsilon \in (0,1/H])$). Our ongoing work \citet{li2022settling} suggests that a new variant of pessimistic model-based algorithm is sample-optimal for a broader range of $\varepsilon$, which in turn motivates further investigation into whether model-free algorithms can accommodate a broader $\varepsilon$-range too without compromising sample efficiency. Moving beyond the tabular setting, it would be of great importance to extend the algorithmic and theoretical framework to accommodate low-complexity function approximation \citep{nguyen2021sample}. \section{Background and problem formulation} \label{sec:problem-formulation} \subsection{Tabular finite-horizon MDPs} \paragraph{Basics.} This work focuses on an episodic finite-horizon MDP as represented by $$\mathcal{M}= \big(\mathcal{S},\mathcal{A},H, \{P_h\}_{h=1}^H, \{r_h\}_{h=1}^H \big),$$ where $H$ is the horizon length, $\mathcal{S}$ is a finite state space of cardinality $S$, $\mathcal{A}$ is a finite action space of cardinality $A$, and $P_h : {\mathcal{S}} \times \mathcal{A} \rightarrow \Delta ({\mathcal{S}}) $ (resp.~$r_h: {\mathcal{S}} \times \mathcal{A} \rightarrow [0,1]$) represents the probability transition kernel (resp.~reward function) at the $h$-th time step $(1\leq h\leq H)$. Throughout this paper, we shall adopt the following convenient notation \begin{equation} \label{eq:transition_vector} P_{h,s,a} \coloneqq P_h(\cdot \mymid s,a ) \in [0,1]^{1\times S}, \end{equation} which stands for the transition probability vector given the current state-action pair $(s,a)$ at time step $h$. The parameters $S$, $A$ and $H$ can all be quite large, allowing one to capture the challenges arising in MDPs with large state/action space and long horizon. A policy (or action selection rule) of an agent is represented by $\pi =\{\pi_h\}_{h=1}^H$, where $\pi_h: \mathcal{S} \rightarrow \Delta(\mathcal{A})$ specifies the associated selection probability over the action space at time step $h$ (or more precisely, we let $\pi_h(a\mymid s)$ represent the probability of selecting action $a$ in state $s$ at step $h$). When $\pi$ is a deterministic policy, we abuse the notation and let $\pi_h(s)$ denote the action selected by policy $\pi$ in state $s$ at step $h$. In each episode, the agent generates an initial state $s_1\in {\mathcal{S}}$ drawn from an initial state distribution $\rho\in \Delta({\mathcal{S}})$, and rolls out a trajectory over the MDP by executing a policy $\pi$ as follows: \begin{equation}\label{eq:single_trajectory} \{s_h, a_h, r_h\}_{h=1}^H =\{ s_1,\, a_1, \, r_1,\, \ldots, s_H,\, a_H, \, r_H \}, \end{equation} where at time step $h$, $a_h \sim \pi_h(\cdot \mymid s_h)$ indicates the action selected in state $s_h$, $r_h= r_h(s_h,a_h) $ denotes the deterministic immediate reward, and $s_{h+1} $ denotes the next state drawn from the transition probability vector $P_{h,s_h,a_h}\coloneqq P_h(\cdot \mymid s_h,a_h )$. In addition, let $d_h^{\pi}(s)$ and $d_h^{\pi}(s,a)$ denote respectively the occupancy distribution induced by $\pi$ at time step $h\in [H]$, namely, \begin{align} \label{eq:visitation_dist} d_h^{\pi}(s) & \coloneqq \mathbb{P}(s_h = s \mymid s_1 \sim \rho, \pi), \qquad d_h^{\pi}(s, a) \coloneqq \mathbb{P}(s_h = s \mymid s_1 \sim \rho, \pi) \, \pi_h(a \mymid s); \end{align} here and throughout, we denote $[H]\coloneqq \{1,\cdots,H\}$. Given that the initial state $s_1$ is drawn from $\rho$, the above definition gives \begin{align} d_1^{\pi}(s) = \rho(s) \qquad \text{for any policy }\pi. \label{eq:d1-pi-s-deterministic} \end{align} \paragraph{Value function, Q-function, and optimal policy.} The value function $V^{\pi}_{h}(s)$ of policy $\pi$ in state $s$ at step $h$ is defined as the expected cumulative rewards when this policy is executed starting from state $s$ at step $h$, i.e., \begin{align} \label{eq:def_Vh} V^{\pi}_{h}(s) &\coloneqq \mathbb{E} \left[ \sum_{t=h}^{H} r_{t}\big(s_{t},a_t \big) \,\Big|\, s_{h}=s \right], \end{align} where the expectation is taken over the randomness of the trajectory \eqref{eq:single_trajectory} induced by the policy $\pi$ as well as the MDP transitions. Similarly, the Q-function $Q^{\pi}_h(\cdot,\cdot)$ of a policy $\pi$ at step $h$ is defined as \begin{align} \label{eq:def_Qh} Q^{\pi}_{h}(s,a) & \coloneqq r_{h}(s,a)+ \mathbb{E} \left[ \sum_{t=h +1}^{H} r_t (s_t, a_t ) \,\Big|\, s_{h}=s, a_h = a\right] , \end{align} where the expectation is again over the randomness induced by $\pi$ and the MDP except that the state-action pair at step $h$ is now conditioned to be $(s,a)$. By convention, we shall also set \begin{equation}\label{eq:value-H-1-zero} V^{\pi}_{H+1}(s)= Q^{\pi}_{H+1}(s,a)=0 ~~\text{ for any }\pi\text{ and }(s,a)\in {\mathcal{S}}\times \mathcal{A}. \end{equation} A policy $\pi^{\star} =\{\pi_h^{\star}\}_{h=1}^H$ is said to be an optimal policy if it maximizes the value function (resp.~Q-function) {\em simultaneously} for all states (resp.~state-action pairs) among all policies, whose existence is always guaranteed \citep{puterman2014markov}. The resulting optimal value function $V^{\star} =\{ V_h^{\star} \}_{h=1}^H $ and optimal Q-functions $Q^{\star} =\{ Q_h^{\star} \}_{h=1}^H $ are denoted respectively by \begin{align*} V_h^{\star}(s) & \coloneqq V_h^{\pi^{\star}}(s) = \max_{\pi} V_h^{\pi}(s), \qquad Q_h^{\star}(s,a) \coloneqq Q_h^{\pi^{\star}}(s,a) = \max_{\pi} Q_h^{\pi}(s,a) \end{align*} for any $(s,a,h)\in {\mathcal{S}}\times \mathcal{A} \times [H]$. Throughout this paper, we assume that $\pi^{\star}$ is a {\em deterministic optimal policy}, which always exists \citep{puterman2014markov}. Additionally, when the initial state is drawn from a given distribution $\rho$, the expected value of a given policy $\pi$ and that of the optimal policy at the initial step are defined respectively by \begin{align}\label{eq:defn-V-rho} V_1^{\pi}(\rho) \coloneqq \mathop{\mathbb{E}}\limits_{s_1\sim \rho} \big[ V_1^\pi (s_1) \big] \qquad \text{and} \qquad V_1^{\star}(\rho) \coloneqq \mathop{\mathbb{E}}\limits_{s_1\sim \rho} \big[ V_1^\star (s_1) \big]. \end{align} \paragraph{Bellman equations.} The Bellman equations play a fundamental role in dynamic programming \citep{bertsekas2017dynamic}. Specifically, the value function and the Q-function of any policy $\pi$ satisfy the following Bellman consistency equation: \begin{align} \label{eq:bellman} Q^{\pi}_{h}(s,a)=r_{h}(s,a)+ \mathop{\mathbb{E}}\limits_{s'\sim P_{h,s,a}} \big[V^{\pi}_{h+1}(s') \big] \end{align} for all $(s,a,h)\in {\mathcal{S}}\times \mathcal{A}\times [H]$. Moreover, the optimal value function and the optimal Q-function satisfy the Bellman optimality equation: \begin{align} \label{eq:bellman_optimality} Q^{\star}_{h}(s,a)=r_{h}(s,a)+ \mathop{\mathbb{E}}\limits_{s'\sim P_{h,s,a}} \big[V^{\star}_{h+1}(s') \big] \end{align} for all $ (s,a,h)\in {\mathcal{S}}\times \mathcal{A}\times [H]$. \subsection{Offline RL under single-policy concentrability} \label{sec:offline-concentrability} Offline RL assumes the availability of a history dataset $\mathcal{D}_{\mu}$ containing $K$ episodes each of length $H$. These episodes are independently generated based on a certain policy $\mu = \{ \mu_{h} \}_{h=1}^H$ --- called the {\em behavior policy}, resulting in a dataset \[ \mathcal{D}_{\mu} \coloneqq \Big\{ \big( s_1^k,\, a_1^k, \, r_1^k,\, \ldots, s_H^k,\, a_H^k, \, r_H^k \big) \Big\}_{k=0}^{K-1} . \] Here, the initial states $\{s_1^k \}_{k=1}^K$ are independently drawn from $\rho \in \Delta({\mathcal{S}})$ such that $s_1^k \overset{\mathrm{i.i.d.}}{\sim} \rho $, while the remaining states and actions are generated by the MDP induced by the behavior policy $\mu$. The total number of samples is thus given by $$T= KH. $$ With the notation \eqref{eq:defn-V-rho} in place, the goal of offline RL amounts to finding an $\varepsilon$-optimal policy $\widehat{\pi} =\{ \widehat{\pi}_h \}_{h=1}^H$ satisfying \[ V_1^{\star}(\rho) - V_1^{\widehat{\pi}}(\rho) \leq \varepsilon \] with as few samples as possible, and ideally, in a computationally fast and memory-efficient manner. Obviously, efficient offline RL cannot be accomplished without imposing proper assumptions on the behavior policy, which also provide means to gauge the difficulty of the offline RL task through the quality of the history dataset. Following the recent works \citet{rashidinejad2021bridging,xie2021policy}, we assume that the behavior policy $\mu$ satisfies the following property called {\em single-policy concentrability}. \begin{assumption}[single-policy concentrability] \label{assumption} The single-policy concentrability coefficient $C^\star \in [1, \infty)$ of a behavior policy $\mu$ is defined to be the smallest quantity that satisfies \begin{equation}\label{equ:concentrability-assumption} \max_{(h, s, a) \in [H] \times \mathcal{S} \times \mathcal{A}} \frac{d^{\pi^\star}_h(s,a)}{d^{\mu}_h(s,a)} \leq C^\star, \end{equation} where we adopt the convention $0/0=0$. \end{assumption} Intuitively, the single-policy concentrability coefficient measures the discrepancy between the optimal policy $\pi^{\star}$ and the behavior policy $\mu$ in terms of the resulting density ratio of the respective occupancy distributions. It is noteworthy that a finite $C^{\star}$ does not necessarily require $\mu$ to cover the entire state-action space; instead, it can be attainable when its coverage subsumes that of the optimal policy $\pi^{\star}$. This is in stark contrast to, and in fact much weaker than, other assumptions that require either full coverage of the behavior policy (i.e., $\min_{(h, s, a) \in [H] \times \mathcal{S} \times \mathcal{A}} d^{\mu}_h(s,a)>0$ \citep{li2021sample,yin2021near,yin2021near_double}), or uniform concentrability over all possible policies \citep{chen2019information}. Additionally, the single-policy concentrability coefficient is minimized (i.e., $C^{\star}=1$) when the behavior policy $\mu$ coincides with the optimal policy $\pi^{\star}$, a scenario closely related to imitation learning or behavior cloning \citep{rajaraman2020toward}. \section{Introduction} Reinforcement Learning (RL) has achieved remarkable success in recent years, including matching or surpassing human performance in robotics control and strategy games \citep{silver2017mastering,mnih2015human}. Nevertheless, these success stories often come with nearly prohibitive cost, where an astronomical number of samples are required to train the learning algorithm to a satisfactory level. Scaling up and replicating the RL success in many real-world problems face considerable challenges, due to limited access to large-scale simulation data. In applications such as online advertising and clinical trials, real-time data collection could be expensive, time-consuming, or constrained in sample sizes as a result of experimental limitations. On the other hand, it is worth noting that tons of samples might have already been accumulated and stored --- albeit not necessarily with the desired quality --- during previous data acquisition attempts. It is therefore natural to wonder whether such history data can be leveraged to improve performance in future deployments. In reality, the history data was often obtained by executing some (possibly unknown) behavior policy, which is typically not the desired policy. This gives rise to the problem of offline RL or batch RL \citep{lange2012batch,levine2020offline},\footnote{Throughout this paper, we will be using the term offline RL (resp. dataset) or batch RL (resp. dataset) interchangeably.} namely, how to make the best use of history data to learn an improved or even optimal policy, without further exploring the environment. In stark contrast to online RL that relies on active interaction with the environment, the performance of offline RL depends critically not only on the quantity, but also the quality of history data (e.g., coverage over the space-action space), given that the agent is no longer collecting new samples for the purpose of exploring the unknown environment. Recently, the principle of pessimism (or conservatism) --- namely, being conservative in Q-function estimation when there are not enough samples --- has been put forward as an effective way to solve offline RL \citep{buckman2020importance,kumar2020conservative}. This principle has been implemented in, for instance, a model-based offline value iteration algorithm, which modifies classical value iteration \citep{azar2017minimax} by subtracting a penalty term in the estimated Q-values and has been shown to achieve appealing sample efficiency \citep{jin2021pessimism,rashidinejad2021bridging,xie2021policy}. It is noteworthy that the model-based approach is built upon the construction of an empirical transition kernel, and therefore, requires specific representation of the environment (see, e.g.~\cite{agarwal2019optimality,li2020breaking}). It remains unknown whether the pessimism principle can be incorporated into model-free algorithms --- another class of popular algorithms that performs learning without model estimation --- in a provably effective fashion for offline RL. \newcommand{\topsepremove}{\aboverulesep = 0mm \belowrulesep = 0mm} \topsepremove \begin{table}[t] \begin{center} \begin{tabular}{c|c|c} \toprule Algorithm &Type & Sample complexity \tabularnewline \toprule \hline VI-LCB \vphantom{$\frac{1^{7}}{1^{7^{7}}}$} & \multirow{2}{*}{model-based} & \multirow{2}{*}{$\frac{H^6SC^{\star}}{\varepsilon^2} $} \tabularnewline \citep{xie2021policy} & \tabularnewline \hline PEVI-Adv \vphantom{$\frac{1^{7}}{1^{7^{7}}}$} & \multirow{2}{*}{model-based} & \multirow{2}{*}{$ \frac{H^4SC^{\star}}{\varepsilon^2} $ } \tabularnewline \citep{xie2021policy} & \tabularnewline \hline \rowcolor{Gray} Q-LCB \vphantom{$\frac{1^{7}}{1^{7^{7}}}$} & & \tabularnewline \rowcolor{Gray} {\bf (this work)} & \multirow{-2}{*}{\cellcolor{Gray}\textcolor{red}{model-free}} & \multirow{-2}{*}{\cellcolor{Gray} $ \frac{H^6SC^{\star}}{\varepsilon^2} $} \tabularnewline \hline \rowcolor{Gray} Q-LCB-Adv \vphantom{$\frac{1^{7}}{1^{7^{7}}}$} & & \tabularnewline \rowcolor{Gray} {\bf (this work)} & \multirow{-2}{*}{\cellcolor{Gray}\textcolor{red}{model-free}} & \multirow{-2}{*}{\cellcolor{Gray} $ \frac{H^4SC^\star}{\varepsilon^2} $} \tabularnewline \toprule lower bound \vphantom{$\frac{1^{7}}{1^{7^{7}}}$} & \multirow{2}{*}{n/a} & \multirow{2}{*}{$ \frac{H^4SC^{\star}}{\varepsilon^2} $} \tabularnewline \citep{xie2021policy} & & \tabularnewline \toprule \end{tabular} \end{center} \caption{Comparisons between our results and prior art for finding an $\varepsilon$-optimal policy in finite-horizon non-stationary MDPs. The sample complexities included in the table are valid for sufficiently small $\varepsilon$, with all logarithmic factors omitted. \label{tab:prior-work}} \end{table} \subsection{Main contributions} In this paper, we consider finite-horizon non-stationary Markov decision processes (MDPs) with $S$ states, $A$ actions, and horizon length $H$. The focal point is to pin down the sample efficiency for pessimistic variants of model-free algorithms, under the mild single-policy concentrability assumption (cf. Assumption~\ref{assumption}) of the batch dataset introduced in \citet{rashidinejad2021bridging,xie2021policy} (in short, this assumption captures how close the batch dataset is to an expert dataset, and will be formally introduced in Section~\ref{sec:offline-concentrability}). Given $K$ episodes of history data each of length $H$ (which amounts to a total number of $T=KH$ samples), our main contributions are summarized as follows. \begin{itemize} \item We first study a natural pessimistic variant of the Q-learning algorithm, which simply modifies the classical Q-learning update rule by subtracting a penalty term (via certain lower confidence bounds). We prove that pessimistic Q-learning finds an $\varepsilon$-optimal policy as soon as the sample size $T$ exceeds the order of (up to log factor) $$ \frac{H^6SC^{\star}}{\varepsilon^2}, $$ where $C^{\star}$ denotes the single-policy concentrability coefficient of the batch dataset. In comparison to the minimax lower bound $\Omega \big( \frac{H^4SC^{\star}}{\varepsilon^2}\big)$ developed in \citet{xie2021policy}, the sample complexity of pessimistic Q-learning is at most a factor of $H^2$ from optimal (modulo some log factor). \item To further improve the sample efficiency of pessimistic model-free algorithms, we introduce a variance-reduced variant of pessimistic Q-learning. This algorithm is guaranteed to find an $\varepsilon$-optimal policy as long as the sample size $T$ is above the order of $$ \frac{H^4SC^{\star}}{\varepsilon^2} + \frac{H^5SC^{\star}}{\varepsilon} $$ up to some log factor. In particular, this sample complexity is minimax-optimal (namely, as low as $\frac{H^4SC^{\star}}{\varepsilon^2}$ up to log factor) for small enough $\varepsilon$ (namely, $\varepsilon \leq \left(0, 1/H\right]$). The $\varepsilon$-range that enjoys near-optimality is much larger compared to $\varepsilon \leq \left(0, 1/H^{2.5}\right]$ established in \citet{xie2021policy} for model-based algorithms. \end{itemize} Both of the proposed algorithms achieve low computation cost (i.e., $O(T)$) and low memory complexities (i.e., $O(\min\{T, SAH\})$). Additionally, more complete comparisons with prior sample complexities of pessimistic model-based algorithms \citep{xie2021policy} are provided in Table~\ref{tab:prior-work}. In comparison with model-based algorithms, model-free algorithms require drastically different technical tools to handle the complicated statistical dependency between the estimated Q-values at different time steps. \subsection{Related works} In this section, we discuss several lines of works which are related to ours, with an emphasis on value-based algorithms for tabular settings with finite state and action spaces. \paragraph{Offline RL.} One of the key challenges in offline RL lies in the insufficient coverage of the batch dataset, due to lack of interaction with the environment \citep{levine2020offline,liu2020provably}. To address this challenge, most of the recent works can be divided into two lines: 1) regularizing the policy to avoid visiting under-covered state and action pairs \citep{fujimoto2019off,dadashi2021offline}; 2) penalizing the estimated values of the under-covered state-action pairs \citep{buckman2020importance,kumar2020conservative}. Our work follows the latter line (also known as the principle of pessimism), which has garnered significant attention recently. In fact, pessimism has been incorporated into recent development of various offline RL approaches, such as policy-based approaches \citep{rezaeifar2021offline,xie2021bellman,zanette2021provable}, model-based approaches \citep{rashidinejad2021bridging,uehara2021pessimistic,jin2021pessimism,yu2020mopo,kidambi2020morel,xie2021policy,yin2021towards,uehara2021representation,yu2021combo,yinnear}, and model-free approaches \citep{kumar2020conservative,yu2021conservative,yan2022efficacy}. \paragraph{Finite-sample guarantees for pessimistic approaches.} While model-free approaches with pessimism \citep{kumar2020conservative,yu2021conservative} have achieved considerable empirical successes in offline RL, prior theoretical guarantees of pessimistic schemes have been confined almost exclusively to model-based approaches. Under the same single-policy concentrability assumption used in prior analyses of model-based approaches \citep{rashidinejad2021bridging,xie2021policy,yin2021near_double}, the current paper provides the first finite-sample guarantees for model-free approaches with pessimism in the tabular case without explicit model construction. In addition, \citet{yin2021towards} directly employed the occupancy distributions of the behavior policy and the optimal policy in bounding the performance of a model-based approach, rather than the worst-case upper bound of their ratios as done under the single-policy concentrability assumption. \paragraph{Non-asymptotic guarantees for variants of Q-learning.} Q-learning, which is among the most famous model-free RL algorithms \citep{watkins1989learning,jaakkola1994convergence,watkins1992q}, has been adapted in a multitude of ways to deal with different RL settings. Theoretical analyses for Q-learning and its variants have been established in, for example, the online setting via regret analysis \citep{jin2018q,bai2019provably,zhang2020almost,li2021breaking,dong2019q,zhang2020reinforcement,zhang2020model,jafarnia2020model,yang2021q}, and the simulator setting via probably approximately correct (PAC) bounds \citep{chen2020finite,wainwright2019variance,li2021tightening}. The variant that is most closely related to ours is asynchronous Q-learning, which aims to find the optimal Q-function from Markovian trajectories following some behavior policy \citep{even2003learning,beck2012error,qu2020finite,li2021sample,yin2021near,yin2021near_double,yin2021near_double}. Different from ours, these works typically require full coverage of the state-action space by the behavior policy, a much stronger assumption than the single-policy concentrability assumed in our offline RL setting. \paragraph{Variance reduction in RL.} Variance reduction, originally proposed to accelerate stochastic optimization (e.g., the SVRG algorithm proposed by \citet{johnson2013accelerating}), has been successfully leveraged to improve the sample efficiency of various RL algorithms, including but not limited to policy evaluation \citep{du2017stochastic,wai2019variance,xu2019reanalysis,khamaru2020temporal}, planning \citep{sidford2018near,sidford2018variance}, Q-learning and its variants \citep{wainwright2019variance,zhang2020almost,li2021breaking,li2021sample}, and offline RL \citep{xie2021policy,yin2021near_double}. \subsection{Notation and paper organization} Let us introduce a set of notation that will be used throughout. We denote by $\Delta({\mathcal{S}})$ the probability simplex over a set ${\mathcal{S}}$, and introduce the notation $[N]\coloneqq \{1,\cdots,N\}$ for any integer $N>0$. For any vector $x \in \mathbb{R}^{SA}$ (resp.~$x\in \mathbb{R}^S$) that constitutes certain values for each of the state-action pairs (resp.~state), we shall often use $x(s,a)$ (resp.~$x(s)$) to denote the entry associated with the $(s,a)$ pair (resp. state $s$). Similarly, we shall denote by $x \coloneqq \{x_h\}_{h\in [H]}$ the set composed of certain vectors for each of the time step $h\in[H]$. We let $e_i$ represent the $i$-th standard basis vector, with the only non-zero element being in the $i$-th entry. Let $\mathcal{X}\coloneqq ( S, A, H , T )$. The notation $f(\mathcal{X})\lesssim g(\mathcal{X})$ (resp.~$f(\mathcal{X})\gtrsim g(\mathcal{X})$) means that there exists a universal constant $C_{0}>0$ such that $|f(\mathcal{X})|\leq C_{0}|g(\mathcal{X})|$ (resp.~$|f(\mathcal{X})|\geq C_{0}|g(\mathcal{X})|$). In addition, we often overload scalar functions and expressions to take vector-valued arguments, with the interpretation that they are applied in an entrywise manner. For example, for a vector $x=[x_i]_{1\leq i\leq n}$, we have $x^2 =[x_i^2]_{1\leq i\leq n}$. For any two vectors $x=[x_i]_{1\leq i\leq n}$ and $y=[y_i]_{1\leq i\leq n}$, the notation $ {x}\leq {y}$ (resp.~$ {x}\geq {y}$) means $x_{i}\leq y_{i}$ (resp.~$x_{i}\geq y_{i}$) for all $1\leq i\leq n$. \paragraph{Paper organization.} The rest of this paper is organized as follows. Section~\ref{sec:problem-formulation} introduces the backgrounds on finite-horizon MDPs and formulates the offline RL problem. Section~\ref{sec:algorithm-theory-lcbq} starts by introducing a natural pessimistic variant of Q-learning along with its sample complexity bound, and further enhances the sample efficiency via variance reduction in Section~\ref{sec:pessimistic-Q-vr}. Section~\ref{sec:analysis} presents the proof outline and key lemmas. Finally, we conclude in Section~\ref{sec:discussions} with a discussion and defer the proof details to the supplementary material. \section{Analysis} \label{sec:analysis} In this section, we outline the main steps needed to establish the main results in Theorem~\ref{thm:lcb} and Theorem~\ref{thm:lcb-adv}. Before proceeding, let us first recall the following rescaled learning rates \begin{equation} \eta_n = \frac{H+1}{H+n} \label{eq:eta-n-definition} \end{equation} for the $n$-th visit of a given state-action pair at a given time step $h$, which are adopted in both {\sf LCB-Q}\xspace and {\sf LCB-Q-Advantage}\xspace. For notational convenience, we further introduce two sequences of related quantities defined for any integers $N\geq 0$ and $n\geq 1$: \begin{equation} \label{equ:learning rate notation} \eta_0^N \coloneqq \begin{cases} \prod_{i=1}^N(1-\eta_i) =0 , & \text{if }N>0, \\ 1, & \text{if }N=0,\end{cases} \qquad \text{and} \qquad \eta_n^N \coloneqq \begin{cases} \eta_n \prod_{i = n+1}^N(1-\eta_i), & \text{if }N>n, \\ \eta_n, & \text{if }N=n,\\ 0,&\text{if } N<n. \end{cases} \end{equation} The following identity can be easily verified: \begin{align} \sum_{n=0}^N \eta_n^N = 1. \label{eq:sum-eta-n-N} \end{align} \begin{algorithm}[t] \SetKwFunction{FMain}{update-lcb-q} \SetKwProg{Fn}{Function}{:}{} \Fn{\FMain{}}{ $Q_h^{{\sf LCB}\xspace}(s_h, a_h) \leftarrow (1 - \eta_n)Q_h^{{\sf LCB}\xspace}(s_h, a_h) + \eta_n\big(r(s_h, a_h) + V_{h+1}(s_{h+1}) - c_{\mathrm{b}} \sqrt{\frac{H^3\iota^2}{n}} \big)$. \label{line:dadv4} \\ } \SetKwFunction{FMain}{update-lcb-q-ra} \SetKwProg{Fn}{Function}{:}{} \Fn{\FMain{}}{ \small {\color{own_blue}\tcc{update the moment statistics of the interested terms}} \normalsize $[\refmu_h, \sigma^{\mathsf{ref}}_h, \mu^{\mathsf{adv}}_h, \sigma^{\mathsf{adv}}_h](s_h,a_h) \leftarrow \texttt{update-moments()}$; \\ \small {\color{own_blue}\tcc{update the bonus difference and accumulative bonus} }\normalsize $[\overline{\delta}_h , \overline{B}_h](s_h, a_h) \leftarrow \texttt{update-bonus()}$; \label{line:bonus_1} $\overline{b}_h(s_h, a_h) \leftarrow \overline{B}_h(s_h, a_h) + (1-\eta_n) \frac{\overline{\delta}_h(s_h,a_h)}{\eta_n} + c_{\mathrm{b}} \frac{H^{7/4}\iota}{n^{3/4}} + c_{\mathrm{b}}\frac{H^2\iota}{n} $; \label{line:bonus_2}\\ \small {\color{own_blue}\tcc{update the Q-estimate based on reference-advantage} }\normalsize $\overline{Q}_h(s_h, a_h) \leftarrow (1 - \eta_n) \overline{Q}_h(s_h, a_h) + \eta_n\big(r_h(s_h, a_h) + V_{h+1}(s_{h+1}) - \overline{V}_{h+1}(s_{h+1}) + \overline{\mu}_h(s_h, a_h) - \overline{b}_h \big);$ \label{line:ref-q-update} \\ } \SetKwFunction{FMain}{update-moments} \SetKwProg{Fn}{Function}{:}{} \Fn{\FMain{}}{ ${\refmu_h(s_h, a_h) \leftarrow (1-\tfrac{1}{n}) \refmu_h(s_h, a_h) + \tfrac{1}{n} \overline{V}^{\mathsf{next}}_{h+1}(s_{h+1})}$; \label{eq:line-mu-mean} {\small\color{own_blue}\tcp{mean of the reference} }\normalsize \label{line:refmu_h} ${\sigma^{\mathsf{ref}}_h(s_h, a_h) \leftarrow (1-\tfrac{1}{n}) \sigma^{\mathsf{ref}}_h(s_h, a_h) + \tfrac{1}{n}\big(\overline{V}^{\mathsf{next}}_{h+1}(s_{h+1}) \big)^2}$; \small {\color{own_blue}\tcp{$2^{\text{nd}}$ moment of the reference}} \normalsize \label{line:refsigma_h} $\mu^{\mathsf{adv}}_h(s_h, a_h) \leftarrow (1-\eta_n)\mu^{\mathsf{adv}}_h(s_h, a_h) + \eta_n \big( V_{h+1}(s_{h+1}) - \overline{V}_{h+1}(s_{h+1}) \big)$; \small {\color{own_blue}\tcp{mean of the advantage}} \normalsize \label{line:advmu_h} $\sigma^{\mathsf{adv}}_h(s_h, a_h) \leftarrow (1-\eta_n)\sigma^{\mathsf{adv}}_h (s_h, a_h) + \eta_n \big( V_{h+1}(s_{h+1}) - \overline{V}_{h+1}(s_{h+1}) \big)^2$. \small {\color{own_blue}\tcp{$2^{\text{nd}}$ moment of the advantage} }\normalsize \label{line:advsigma_h} } \SetKwFunction{FMain}{update-bonus} \SetKwProg{Fn}{Function}{:}{} \Fn{\FMain{}}{ {$B^{\mathsf{next}}_h(s_h, a_h) \leftarrow c_{\mathrm{b}}\sqrt{\frac{\iota}{n}}\Big(\sqrt{ \sigma^{\mathsf{ref}}_h(s_h, a_h) - \big( \refmu_h(s_h, a_h) \big)^2} + \sqrt{H}\sqrt{\sigma^{\mathsf{adv}}_h(s_h, a_h) - \big( \mu^{\mathsf{adv}}_h(s_h, a_h) \big)^2} \,\Big)$;} \label{eq:line-number-19} \\ $\overline{\delta}_h(s_h,a_h) \leftarrow B^{\mathsf{next}}_h(s_h, a_h) - \overline{B}_h(s_h, a_h) ;$ \label{eq:line-delta} \\ $\overline{B}_h(s_h, a_h) \leftarrow B^{\mathsf{next}}_h(s_h, a_h) .$ } \caption{Auxiliary functions} \label{algo:subroutine} \end{algorithm} \subsection{Analysis of {\sf LCB-Q}\xspace} \label{sec:LCBQ_analysis} \begin{algorithm}[t] \textbf{Parameters:} some constant $c_{\mathrm{b}}>0$, target success probability $1-\delta \in(0,1)$, and $\iota = \log\big(\frac{SAT}{\delta}\big)$. \\ \textbf{Initialize} $Q^1_h(s, a) \leftarrow 0$; $N^1_h(s, a)\leftarrow 0$ for all $(s, a, h) \in {\mathcal{S}}\times \mathcal{A} \times [H]$; $V^1_h(s) \leftarrow 0$ for all $(s,h)\in {\mathcal{S}}\times[H+1]$; $\pi^1$ s.t. $ \pi^1_h(s)= 1$ for all $(s,h)\in {\mathcal{S}}\times [H]$. \\ \For{Episode $ k = 1$ \KwTo $K$}{ Sample the $k$-th trajectory $\{s_h^k, a_h^k, r_h^k\}_{h=1}^H$ from $\mathcal{D}_{\mu}$. {\small\color{own_blue}\tcp{sampling from batch dataset}} \For{Step $ h = 1$ \KwTo $H$ }{ \For{$(s,a)\in{\mathcal{S}}\times \mathcal{A}$}{ {\small\color{own_blue}\tcp{carry over the estimates and policy}} \normalsize $N_h^{k+1}(s, a) \leftarrow N_h^k(s, a)$; ~ $Q_h^{k+1}(s, a) \leftarrow Q_h^k(s, a)$; ~$V_h^{k+1}(s) \leftarrow V_h^k(s)$; $\pi_h^{k+1}(s) \leftarrow \pi_h^{k}(s)$. } $N_h^{k+1}(s_h^k, a_h^k) \leftarrow N_h^k(s_h^k, a_h^k) + 1$. {\small\color{own_blue}\tcp{update the counter} } $n \leftarrow N_h^{k+1}(s_h^k, a_h^k)$; $\eta_n \leftarrow \frac{H + 1}{H + n}$. {\small\color{own_blue}\tcp{update the learning rate}} $b_n \leftarrow c_{\mathrm{b}} \sqrt{\frac{H^3\iota^2}{n}}$. \label{line:2} {\small\color{own_blue}\tcp{update the bonus term}} {\small\color{own_blue}\tcp{update the Q-estimates with LCB} } \normalsize $Q_h^{k+1}(s_h^k, a_h^k) \leftarrow Q_h^k(s_h^k, a_h^k) + \eta_n\Big\{ r_h(s_h^k, a_h^k) + V_{h+1}^k(s_{h+1}^k)-Q_h^k(s_h^k, a_h^k) - b_n \Big\} $. \label{line:lcb-9} \\ {\small\color{own_blue}\tcp{update the value estimates}} \normalsize $V_{h}^{k+1}(s_h^k) \leftarrow \max\Big\{ V_{h}^{k}(s_h^k ), \, \max_a Q_{h}^{k+1}(s_h^k, a) \Big\}$. \label{line:lcb_v_update}\\ {\small\color{own_blue}\tcp{update the policy} } \normalsize If $V_{h}^{k+1}(s_h^k) =\max_a Q_{h}^{k+1}(s_h^k, a)$: update $\pi_h^{k+1}(s_h^k) = \arg\max_a Q_{h}^{k+1}(s_h^k, a)$. \label{line:lcb-policy-update} \\ \label{line:lcb-10} } } \caption{{\sf LCB-Q}\xspace for offline RL (a rewrite of Algorithm~\ref{algo:lcb-index} to specify dependency on $k$)} \label{algo:lcb-index-k} \end{algorithm} To begin with, we intend to derive a recursive formula concerning the update rule of $Q_h^k$ --- the estimate of the Q-function at step $h$ at the beginning of the $k$-th episode. Note that we have omitted the dependency of all quantities on the episode index $k$ in Algorithm~\ref{algo:lcb-index}. For notational convenience and clearness, we rewrite Algorithm~\ref{algo:lcb-index} as Algorithm~\ref{algo:lcb-index-k} by specifying the dependency on the episode index $k$ and shall often use the following set of short-hand notation when it is clear from context. \begin{itemize} \item $N_h^k(s, a)$, or the shorthand $N_h^k$: the number of episodes that has visited $(s,a)$ at step $h$ before the beginning of the $k$-th episode. \item $k_h^n(s,a)$, or the shorthand $k^n$: the index of the episode in which the state-action pair $(s,a)$ is visited at step $h$ for the $n$-th times. We also adopt the convention that $k^0 = 0$. \item $P_h^k\in\{0,1\}^{1\times S}$: a row vector corresponding to the empirical transition at step $h$ of the $k$-th episode, namely, % \begin{align} \label{eq:Phk_def} P_h^k(s) = \ind\big( s= s_{h+1}^k \big) \qquad \text{for all }s\in {\mathcal{S}}. \end{align} \item $\pi^{k} = \{\pi_h^{k}\}_{h=1}^H$ with $\pi_h^{k}(s) \coloneqq \arg\max_a Q_h^{k}(s,a), \forall (h,s)\in [H] \times {\mathcal{S}}$: the deterministic greedy policy at the beginning of the $k$-th episode. \item $\widehat{\pi}$: the final output $\widehat{\pi}$ of Algorithms~\ref{algo:lcb-index} corresponds to $\pi^{K+1}$ defined above; for notational simplicity, we shall treat $\widehat{\pi}$ as $\pi^{K}$ in our analysis, which does not affect our result at all. \end{itemize} Consider any state-action pair $(s,a)$. According to the update rule in line~\ref{line:lcb-9} of Algorithm~\ref{algo:lcb-index-k}, we can express (with the assistance of the above notation) \begin{equation} Q_h^k(s, a) = Q_h^{k^{N_h^k} + 1} (s, a) = \big(1-\eta_{N_h^k} \big)Q_{h}^{k^{N_h^k}}(s, a) + \eta_{N_h^k} \Big\{ r_h(s,a) + V_{h+1}^{k^{N_h^k}}\big( s_{h+1}^{k^{N_h^k}} \big) -b_{N_h^k} \Big\}, \label{eq:Qhk-sa-expansion-135} \end{equation} where the first identity holds since $k^{N_h^k}$ denotes the latest episode prior to $k$ that visits $(s,a)$ at step $h$, and the learning rate is defined in \eqref{eq:eta-n-definition}. Note that it always holds that $k>k^{N_h^k}$. Applying the above relation \eqref{eq:Qhk-sa-expansion-135} recursively and using the notation \eqref{equ:learning rate notation} lead to \begin{equation}\label{equ:Q-update} Q_h^k(s,a) = \eta_0^{N_h^k} Q_h^1(s, a) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left(r_h(s,a) + V_{h+1}^{k^n}\big(s_{h+1}^{k^n} \big) -b_n \right). \end{equation} As another important fact, the value estimate $V_h^k$ is monotonically non-decreasing in $k$, i.e., \begin{equation}\label{equ:monotone-lcb} V_h^{k +1}(s) \ge V_h^{k}(s)\qquad\text{for all }( s,k,h)\in {\mathcal{S}} \times [K] \times [H], \end{equation} which is an immediate consequence of the update rule in line~\ref{line:lcb_v_update} of Algorithm~\ref{algo:lcb-index-k}. Crucially, we observe that the iterate $V^{k}_h$ forms a ``pessimistic view'' of $V^{\pi^k}_h$ --- and in turn $V^{\star}_h$ --- resulting from suitable design of the penalty term. This observation is formally stated in the following lemma, with the proof postponed to Section~\ref{sec:proof-lem:vk-lower}. \begin{lemma} \label{lem:Vk-lower} Consider any $\delta \in (0, 1)$, and suppose that $c_{\mathrm{b}} >0$ is some sufficiently large constant. Then with probability at least $1-\delta$, \begin{align} \label{equ:lcb-concentration-main} \Bigg|\sum_{n = 1}^{N_h^k(s,a)} \eta^{N_h^k(s,a)}_n \Big(P_{h, s,a} - P_h^{k^n(s,a)} \Big) V^{k^n(s,a)}_{h+1} \Bigg| \leq \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n \end{align} holds simultaneously for all $(k, h, s,a) \in [K] \times [H] \times {\mathcal{S}}\times \mathcal{A}$, and \begin{equation} \label{eq:Vk-lower} V_{h}^{k}(s) \leq V_{h}^{\pi^k}(s) \leq V_h^{\star}(s) \end{equation} holds simultaneously for all $(k, h, s) \in [K] \times [H] \times {\mathcal{S}}$. \end{lemma} In a nutshell, the result \eqref{eq:Vk-lower} in Lemma~\ref{lem:Vk-lower} reveals that $V_h^k$ is a pointwise lower bound on $V_h^{\pi^k}$ and $ V_h^{\star}$, thereby forming a pessimistic estimate of the optimal value function. In addition, the property \eqref{equ:lcb-concentration-main} in Lemma~\ref{lem:Vk-lower} essentially tells us that the weighted sum of the penalty terms dominates the weighted sum of the uncertainty terms, which plays a crucial role in ensuring the aforementioned pessimism property. As we shall see momentarily, Lemma~\ref{lem:Vk-lower} forms the basis of the subsequent proof. We are now ready to embark on the analysis for {\sf LCB-Q}\xspace, which is divided into multiple steps as follows. \paragraph{Step 1: decomposing estimation errors.} With the aid of Lemma~\ref{lem:Vk-lower}, we can develop an upper bound on the performance difference of interest in \eqref{equ:lcb-result} as follows \begin{align} V_1^\star(\rho) - V_1^{\widehat{\pi}}(\rho) &= \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^\star(s_1) \big] - \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^{\pi^{K}}(s_1) \big] \nonumber\\ & \overset{\mathrm{(i)}}{\leq} \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^\star(s_1) \big] - \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^{K}(s_1) \big]\nonumber \\ & \overset{\mathrm{(ii)}}{\leq} \frac{1}{K}\sum_{k=1}^K \left(\mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^\star(s_1) \big] - \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^{k}(s_1) \big] \right) \nonumber\\ & = \frac{1}{K}\sum_{k=1}^K\sum_{s\in {\mathcal{S}}} d_1^{\pi^\star}(s) \left(V_1^\star(s) - V_1^{k}(s)\right),\label{equ:regret2pac} \end{align} where (i) results from Lemma~\ref{lem:Vk-lower} (i.e., $V_1^{\pi^{K}}(s) \geq V_1^{K}(s) $ for all $s\in {\mathcal{S}}$), (ii) follows from the monotonicity property in \eqref{equ:monotone-lcb}, and the last equality holds since $d_1^{\pi^{\star}}(s) = \rho(s)$ (cf.~\eqref{eq:d1-pi-s-deterministic}). We then attempt to bound the quantity on the right-hand side of \eqref{equ:regret2pac}. Given that $\pi^{\star}$ is assumed to be a deterministic policy, we have $d_h^{\pi^\star}(s) = d_h^{\pi^\star}(s, \pi^{\star}(s))$. Taking this together with the relations $V_h^{k}(s) \geq \max_a Q_h^k(s,a) \geq Q_h^k(s, \pi_h^\star(s))$ (see line~\ref{line:lcb_v_update} of Algorithm~\ref{algo:lcb-index-k}) and $V_h^\star(s)=Q_h^\star(s, \pi_h^\star(s))$, we obtain \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) & = \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s, \pi_h^\star(s)) \left(V_h^\star(s) - V_h^{k}(s)\right) \nonumber\\ &\leq \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s, \pi_h^\star(s)) \Big(Q_h^\star\big(s, \pi_h^\star(s)\big) - Q_h^k\big(s, \pi_h^\star(s)\big)\Big) \nonumber\\ &= \sum_{k=1}^K \sum_{(s, a)\in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \left(Q_h^\star(s, a) - Q_h^{k}(s, a)\right) \label{eq:llama} \end{align} for any $h\in [H]$, where the last identity holds since $\pi^\star$ is deterministic and hence \begin{equation} \label{eq:d_h_pi_star} d_h^{\pi^\star}(s,a) = 0 \qquad \text{for any }a\neq \pi^\star_h(s). \end{equation} In view of \eqref{eq:llama}, we need to properly control $Q_h^\star(s, a) - Q_h^{k}(s, a)$. By virtue of \eqref{eq:sum-eta-n-N}, we can rewrite $Q_h^\star(s, a)$ as follows \begin{align} Q_h^\star(s, a) & = \sum_{n=0}^{N_h^k}\eta_n^{N_h^k} Q_h^\star(s, a) = \eta_0^{N_h^k} Q_h^{\star}(s, a) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} Q_h^{\star}(s, a) \nonumber \\ & = \eta_0^{N_h^k} Q_h^{\star}(s, a) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k} \left(r_h(s,a) + P_{h,s, a} V_{h+1}^\star \right), \label{eq:Q_opt_decom} \end{align} where the second line follows from Bellman's optimality equation \eqref{eq:bellman_optimality}. Combining \eqref{equ:Q-update} and \eqref{eq:Q_opt_decom} leads to \begin{align} &Q_h^\star(s, a) - Q_h^k(s, a) \nonumber\\ & = \eta_0^{N_h^k}\left(Q_h^\star(s,a) - Q_h^1(s, a)\right) + \sum_{n=1}^{N_h^k}\eta_n^{N_h^k}\left( P_{h,s, a} V_{h+1}^\star - V_{h+1}^{k^n}(s_{h+1}^{k^n}) + b_n \right) \nonumber\\ & = \eta_0^{N_h^k}\left(Q_h^\star(s,a) - Q_h^1(s, a)\right) + \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} b_n + \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} P_{h,s, a}\big( V_{h+1}^\star - V_{h+1}^{k^n}\big) + \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} \big(P_{h,s, a} - P_h^{k^n}\big)V_{h+1}^{k^n} \label{eq:Qstar-Qk-decomposition-1}\\ &\leq \eta_0^{N_h^k}H + 2\sum_{n=1}^{N_h^k} \eta_n^{N_h^k} b_n + \sum_{n=1}^{N_h^k} \eta_n^{N_h^k} P_{h,s,a}\big( V_{h+1}^\star - V_{h+1}^{k^n}\big), \label{eq:Qstar-Qk-decomposition-2} \end{align} where we have made use of the definition in \eqref{eq:Phk_def} by recognizing $P_h^{k^n}V_{h+1}^{k^n} = V_{h+1}^{k^n}(s_{h+1}^{k^n}) $ in \eqref{eq:Qstar-Qk-decomposition-1}, and the last inequality follows from the fact $Q_h^\star(s,a) - Q_h^1(s, a) = Q_h^\star(s,a) - 0\leq H$ and the bound \eqref{equ:lcb-concentration-main} in Lemma~\ref{lem:Vk-lower}. Substituting the above bound into \eqref{eq:llama}, we arrive at \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) & \leq \underbrace{\sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\eta_0^{N_h^k(s,a)}H + 2\sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} b_n}_{\eqqcolon\, I_h} \nonumber\\ & \qquad + \sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)}\big(V_{h+1}^\star - V_{h+1}^{k_h^n(s,a)}\big). \label{equ:lcb-decompose-terms} \end{align} \paragraph{Step 2: establishing a crucial recursion.} As it turns out, the last term on the right-hand side of \eqref{equ:lcb-decompose-terms} can be used to derive a recursive relation that connects step $h$ with step $h+1$, as summarized in the next lemma. \begin{lemma} \label{lemma:recursion} With probability at least $1-\delta$, the following recursion holds: \begin{align} &\sum_{k=1}^K \sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)}\big(V_{h+1}^\star - V_{h+1}^{k_h^n(s,a)}\big) \nonumber\\ &\leq \left(1+\frac{1}{H}\right)\sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}. \label{equ:lcb-recursion} \end{align} \end{lemma} Lemma~\ref{lemma:recursion} taken together with \eqref{equ:lcb-decompose-terms} implies that \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) & \leq \left(1+\frac{1}{H}\right)\sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) \notag \\ & \qquad + I_h + 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta} . \label{equ:lcb-decompose-terms-123} \end{align} Invoking \eqref{equ:lcb-decompose-terms-123} recursively over the time steps $h=H, H-1,\cdots, 1$ with the terminal condition $V^{k}_{H+1} = V_{H+1}^{\star} = 0$, we reach \begin{align}\label{equ:summary_of_terms} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_1^{\pi^\star}(s) \left(V_1^\star(s) - V_1^{k}(s)\right) &\leq \max_{h\in[H]} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \nonumber \\ &\leq \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1}\left( I_h + 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}\right) , \end{align} which captures the estimation error resulting from the use of pessimism principle. \paragraph{Step 3: controlling the right-hand side of \eqref{equ:summary_of_terms}.} The right-hand side of \eqref{equ:summary_of_terms} can be bounded through the following lemma, which will be proved in Appendix~\ref{proof:lemma:lemma:lcb-bound-terms}. \begin{lemma}\label{lemma:lcb-bound-terms} Consider any $\delta \in (0,1)$. With probability at least $1-\delta$, we have \begin{align} \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h - 1}\left( I_h + 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}\right) & \lesssim H^2 SC^\star \iota + \sqrt{H^5SC^\star K \iota^3}, \label{equ:lcb-final-a} \end{align} where we recall that $\iota \coloneqq \log\big(\frac{SAT}{\delta}\big)$. \end{lemma} Combining Lemma~\ref{lemma:lcb-bound-terms} with \eqref{equ:summary_of_terms} and \eqref{equ:regret2pac} yields \begin{align} V_1^\star(\rho) - V_1^{\widehat{\pi}}(\rho) &\leq \frac{1}{K}\sum_{k=1}^K\sum_{s\in {\mathcal{S}}} d_1^{\pi^\star}(s) \left(V_1^\star(s) - V_1^{k}(s)\right) \nonumber \\ &\leq \frac{1}{K}\max_{h\in[H]} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \notag \\ & \leq \frac{c_\mathrm{a}}{2} \sqrt{\frac{H^5SC^\star \iota^3}{K}} + \frac{c_\mathrm{a}}{2} \frac{H^2 SC^\star \iota}{K} = \frac{c_\mathrm{a}}{2} \sqrt{\frac{H^6SC^\star \iota^3}{T}} + \frac{c_\mathrm{a}}{2}\frac{H^3 SC^\star \iota}{T} \notag\\ & \leq c_\mathrm{a} \sqrt{\frac{H^6SC^\star \iota^3}{T}} \label{eq:lcb-final-result-H-layers} \end{align} for some sufficiently large constant $c_{\mathrm{a}}>0$, where the last inequality is valid as long as $T> SC^{\star} \iota$. This concludes the proof of Theorem~\ref{thm:lcb}. \subsection{Analysis of {\sf LCB-Q-Advantage}\xspace} \begin{algorithm}[!t] \textbf{Parameters:} number of epochs $M$, universal constant $c_{\mathrm{b}}>0$, target success probability $1-\delta \in(0,1)$, and $\iota = \log\big(\frac{SAT}{\delta}\big)$. \\ \textbf{Initialize:} \\ $Q_h^{1}(s, a), Q_h^{{\sf LCB}\xspace,1}(s, a), \overline{Q}^{1}_h(s, a), \overline{\mu}^{1}_h(s,a), \overline{\mu}^{\mathsf{next},1}_h(s,a), N_h^1(s, a) \leftarrow 0$ for all $(s,a,h) \in {\mathcal{S}}\times\mathcal{A} \times [H]$;\\ $V^{1}_h(s), \overline{V}^{1}_h(s), \overline{V}_h^{\mathsf{next},1}(s) \leftarrow 0$ for all $(s,h) \in {\mathcal{S}} \times [H+1]$;\\ $\mu^{\mathsf{ref}, 1}_h(s, a), \sigma^{\mathsf{ref}, 1}_h(s, a), \mu^{\mathsf{adv}, 1}_h(s, a)$, $\sigma^{\mathsf{adv}, 1}_h(s, a)$, $\overline{\delta}^{1}_h(s, a), \overline{B}^{1}_h(s, a) \leftarrow 0$ for all $(s, a, h) \in {\mathcal{S}}\times \mathcal{A} \times [H]$.\\[0.4em] \For{Epoch $ m = 1$ \KwTo $M$}{ $L_m= 2^m$. \small {\color{own_blue}\tcp{specify the number of episodes in the current epoch} }\normalsize $\widehat{N}^{(m,1)}_h(s,a) = 0$ for all $(h, s,a) \in [H] \times {\mathcal{S}}\times \mathcal{A}.$ \small {\color{own_blue}\tcp{reset the epoch-wise counter} }\normalsize \small {\color{own_blue}\tcc{Inner-loop: update value-estimates $V_h(s,a)$ and Q-estimates $Q_h(s,a)$ }} \normalsize \For{In-epoch Episode $ t = 1$ \KwTo $L_m$}{ Set $k \leftarrow \sum_{i=1}^{m-1} L_i + t.$ {\small\color{own_blue}\tcp{set the episode index}} Sample the $k$-th trajectory $\{s_h^k, a_h^k, r_h^k\}_{h=1}^H$. {\small\color{own_blue}\tcp{sampling from batch dataset}} Compute $\pi^k$ s.t.~$\pi_h^k(s) = \arg\max_a Q^{k}_h(s,a)$ for all $(s,h)\in {\mathcal{S}}\times [H]$. \small {\color{own_blue}\tcp{update the policy}}\normalsize \For{Step $ h = 1$ \KwTo $H$}{ \For{$(s,a)\in{\mathcal{S}}\times \mathcal{A}$}{ {\small\color{own_blue}\tcp{carry over the estimates}} \normalsize $N_h^{k+1}(s, a) \leftarrow N_h^k(s, a)$; $\widehat{N}_h^{k+1}(s, a) \leftarrow \widehat{N}_h^k(s, a)$; ~$V_h^{k+1}(s) \leftarrow V_h^k(s)$;\\ $Q_h^{{\sf LCB}\xspace, k+1}(s,a) \leftarrow Q_h^{{\sf LCB}\xspace, k}(s,a)$ ~$\overline{Q}^{k+1}_h(s,a) \leftarrow \overline{Q}^{k}_h (s,a)$; ~$Q_h^{k+1}(s, a) \leftarrow Q_h^k(s, a)$; $\overline{V}^{k+1}_h(s) \leftarrow \overline{V}^{k}_h(s)$ ~$\overline{V}^{\mathsf{next}, k+1}_h(s) \leftarrow \overline{V}^{\mathsf{next}, k}_h(s)$; ~$\overline{\mu}^{k+1}(s,a) \leftarrow \overline{\mu}^{k}(s,a)$. } $N_h^{k+1}(s_h^k, a_h^k) \leftarrow N^k_h(s_h^k, a_h^k) + 1$; $n \leftarrow N^{k+1}_h(s_h^k, a_h^k)$. {\small\color{own_blue}\tcp{update the overall counter} } $\eta_n \leftarrow \frac{H + 1}{H + n}$. \small {\color{own_blue}\tcp{update the learning rate}} \normalsize {\small\color{own_blue}\tcp{update the Q-estimate with LCB}} \normalsize $Q_h^{{\sf LCB}\xspace, k+1}(s_h^k, a_h^k) \leftarrow \texttt{update-lcb-q()}$. \\ {\small\color{own_blue}\tcp{update the Q-estimate with LCB and reference-advantage}} \normalsize $\overline{Q}^{k+1}_h(s_h^k, a_h^k) \leftarrow \texttt{update-lcb-q-ra()}$. \small {\color{own_blue}\tcp{update the Q-estimate $Q_h$ and value estimate $V_h$}} \normalsize $Q^{k+1}_h(s_h^k, a_h^k) \leftarrow \max \big\{Q_h^{{\sf LCB}\xspace,k+1}(s_h^k, a_h^k), \overline{Q}^{k+1}_h(s_h^k, a_h^k), Q^k_h(s_h^k, a_h^k) \big\}.$ \label{eq:line-q-update-k}\\ $V^{k+1}_{h}(s_h^k) \leftarrow \max_a Q^{k+1}_h(s_h^k, a)$. \label{eq:line-v-update-k}\\ \small {\color{own_blue}\tcp{update epoch-wise counter and $\overline{\mu}^{\mathsf{next}}_h(s,a)$ for the next epoch}} \normalsize $\widehat{N}^{(m,t+1)}_h(s_h^k, a_h^k) \leftarrow \widehat{N}^{(m,t)}_h(s_h^k, a_h^k) + 1$.\\ $\overline{\mu}_h^{\mathsf{next}, k+1}(s_h^k, a_h^k) \leftarrow \left(1-\frac{1}{\widehat{N}^{(m,t+1)}_h(s_h^k, a_h^k)}\right)\overline{\mu}_h^{\mathsf{next},k}(s_h, a_h) + \frac{1}{\widehat{N}^{(m,t+1)}_h(s_h^k, a_h^k)} \overline{V}^{\mathsf{next},k}_{h+1}(s_{h+1})$. \label{line:ref-mean-update-k} } } \small {\color{own_blue}\tcc{Update the reference ($\overline{V}_h$, $\overline{V}^\mathsf{next}_h$) and ($\overline{\mu}_h$, $\overline{\mu}^\mathsf{next}_h$)} } \normalsize \For{$(s,a,h) \in {\mathcal{S}}\times\mathcal{A}\times [H+1]$}{ $\overline{V}^{k+1}_h(s) \leftarrow \overline{V}_h^{\mathsf{next}, k+1}(s)$; $\overline{\mu}^{k+1}_h(s,a)\leftarrow \overline{\mu}_h^{\mathsf{next}, k+1}(s,a)$. \label{eq:update-mu-reference-v-k} {\small\color{own_blue}\tcp{set $\overline{V}_h$ and $\overline{\mu}_h$ for the next epoch} } $\overline{V}_h^{\mathsf{next}, k+1}(s) \leftarrow V^{k+1}_h(s)$; $\overline{\mu}_h^{\mathsf{next}, k+1}(s,a) \leftarrow 0$. {\small\color{own_blue}\tcp{set $\overline{\mu}_h^\mathsf{next}$ and $\overline{V}_h^\mathsf{next}$ for the next epoch} } \label{eq:update-mu-reference-v-next-k} } } \KwOut{the policy $\widehat{\pi} = \pi^{K}$ with $K=\sum_{m=1}^{M} L_m$.} \caption{{\sf LCB-Q-Advantage}\xspace (a rewrite of Algorithm~\ref{alg:lcb-advantage-per-epoch} that specifies dependency on $k$ or $(m,t)$.)} \label{alg:lcb-advantage-per-epoch-k} \end{algorithm} We now turn to the analysis of {\sf LCB-Q-Advantage}\xspace. Thus far, we have omitted the dependency of all quantities on the epoch number $m$ and the in-epoch episode number $t$ in Algorithms~\ref{alg:lcb-advantage-per-epoch} and \ref{algo:subroutine}. While it allows for a more concise description of our algorithm, it might hamper the clarity of our proofs. In the following, we introduce the notation $k$ to denote the current episode as follows: \begin{align} \label{eqn:k-to-m-t} k \coloneqq \sum_{i=1}^{m-1} L_i + t, \end{align} which corresponds to the $t$-th in-epoch episode in the $m$-th epoch; here, $L_m=2^m $ stands for the total number of in-epoch episodes in the $m$-th epoch. With this notation in place, we can rewrite Algorithm~\ref{alg:lcb-advantage-per-epoch} as Algorithm~\ref{alg:lcb-advantage-per-epoch-k} in order to make clear the dependency on the episode index $k$, epoch number $m$, and in-epoch episode index $t$. Before embarking on our main proof, we make two crucial observations which play important roles in our subsequent analysis. First, similar to the property \eqref{equ:monotone-lcb} for {\sf LCB-Q}\xspace, the update rule (cf.~lines~\ref{eq:line-q-update}-\ref{eq:line-v-update} of Algorithm~\ref{alg:lcb-advantage-per-epoch-k}) ensures the monotonic non-decreasing property of $V_h(s)$ such that for all $k\in[K]$, \begin{equation}\label{equ:monotone-lcb-adv} V_h^{k +1}(s) \ge V_h^{k}(s),\qquad\text{for all } (k,s,h)\in[K] \times {\mathcal{S}} \times [H]. \end{equation} Secondly, $V^{k}_h$ forms a ``pessimistic view'' of $V^{\star}_h$, which is formalized in the lemma below; the proof is deferred to Appendix~\ref{proof:lemma-mono-lcb-adv}. \begin{lemma} \label{lem:lcb-adv-lower} Let $\delta \in (0, 1)$. Suppose that $c_{\mathrm{b}} >0$ is some sufficiently large constant. Then with probability at least $1-\delta$, the value estimates produced by Algorithm~\ref{alg:lcb-advantage-per-epoch} satisfy \begin{equation} \label{eq:lcb-adv-lower} V_{h}^{k}(s) \leq V_{h}^{\pi^{k}}(s) \leq V^{\star}(s) \end{equation} for all $(k,h,s) \in [K] \times [H+1] \times {\mathcal{S}}$. \end{lemma} With these two observations in place, we can proceed to present the analysis for {\sf LCB-Q-Advantage}\xspace. To begin with, the performance difference of interest can be controlled similar to \eqref{equ:regret2pac} as follows: \begin{align} V_1^\star(\rho) - V_1^{\widehat{\pi}}(\rho) &= \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^\star(s_1) \big] - \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^{\pi^{K}}(s_1) \big] \notag\\ & \overset{\mathrm{(i)}}{\leq} \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^\star(s_1) \big] - \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^{K}(s_1) \big]\nonumber \\ & \overset{\mathrm{(ii)}}{\leq} \frac{1}{K}\sum_{k=1}^K \left(\mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^\star(s_1) \big] - \mathop{\mathbb{E}}\limits _{s_{1}\sim\rho}\big[ V_1^{k}(s_1) \big] \right) \nonumber\\ & = \frac{1}{K}\sum_{k=1}^K\sum_{s\in {\mathcal{S}}} d_1^{\pi^\star}(s) \left(V_1^\star(s) - V_1^{k}(s)\right), \label{equ:regret2pac-2} \end{align} where (i) follows from Lemma~\ref{lem:lcb-adv-lower} (i.e., $V_1^{\pi^{K}}(s) \geq V_1^{K}(s)$ for all $s\in{\mathcal{S}}$), (ii) holds due to the monotonicity in \eqref{equ:monotone-lcb-adv} and the last equality holds since $d_1^{\pi^{\star}}(s) = \rho(s)$ (cf.~\eqref{eq:d1-pi-s-deterministic}). It then boils down to controlling the right-hand side of \eqref{equ:regret2pac-2}. Towards this end, it turns out that one can control a more general counterpart, i.e., \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \end{align} for any $h\in [H]$. This is accomplished via the following lemma, whose proof is postponed to Appendix~\ref{proof:lem:lcb-adv-decompose}. \begin{lemma}\label{lem:lcb-adv-each-h} Let $\delta \in (0, 1)$, and recall that $\iota \coloneqq \log\big(\frac{SAT}{\delta}\big)$. Suppose that $c_\mathrm{a}, c_{\mathrm{b}} >0$ are some sufficiently large constants. Then with probability at least $1-\delta$, one has \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \leq J_h^1 + J_h^2 + J_h^3, \end{align} where \begin{align} J_h^1 &:=\sum_{k=1}^K \sum_{s, a \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\left[\eta_0^{N_h^k(s,a)}H + \frac{4c_{\mathrm{b}} H^{7/4} \iota}{\left(N_h^k(s,a) \vee 1 \right)^{3/4} } + \frac{4c_{\mathrm{b}} H^{2} \iota}{N_h^k(s,a) \vee 1 }\right], \nonumber\\ J_h^2 &:= 2\sum_{k=1}^K \sum_{s, a \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a)\overline{B}_h^{k}(s,a), \nonumber \\ J_h^3 &\coloneqq \left(1+\frac{1}{H}\right)\sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + 48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2. \label{eq:Jh123} \end{align} \end{lemma} As a direct consequence of Lemma~\ref{lem:lcb-adv-each-h}, one arrives at a recursive relationship between time steps $h$ and $h+1$ as follows: \begin{align} &\sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \nonumber \\ &\leq \left(1+\frac{1}{H}\right)\sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right) + 48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2 + J_h^1 + J_h^2. \label{eq:lcb-adv-recursive-equ} \end{align} Recursing over time steps $h=H, H-1,\cdots,1$ with the terminal condition $V^{k}_{H+1} = V^{\star}_{H+1} = 0$, we can upper bound the performance difference at $h=1$ as follows \begin{align} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_1^{\pi^\star}(s) \left(V_1^\star(s) - V_1^{k}(s)\right) &\leq \max_{h\in[H]} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \nonumber \\ & \leq \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \left(48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2 + J_h^1 + J_h^2 \right). \label{lem:lcb-adv-decompose} \end{align} To finish up, it suffices to upper bound each term in \eqref{lem:lcb-adv-decompose} separately. We summarize their respective upper bounds as follows; the proof is provided in Appendix~\ref{proof:lemma:lcb-adv-bound-terms}. \begin{lemma}\label{lemma:lcb-adv-bound-terms} Fix $\delta \in (0,1)$, and recall that $\iota \coloneqq \log\big(\frac{SAT}{\delta}\big)$. With probability at least $1-\delta$, we have \begin{subequations} \label{eq:lemma6} \begin{align} & \sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} J_h^1 \lesssim H^{2.75}(SC^\star)^{\frac{3}{4}} K^{\frac{1}{4}}\iota^2 + H^3 SC^\star \iota^3 , \label{eq:lemma6-a}\\ &\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} J_h^2 \lesssim \sqrt{H^4SC^\star \iota^3 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) } + \sqrt{H^3S C^\star K \iota^5} + H^{4} S C^\star \iota^4, \label{eq:lemma6-b}\\ &\sum_{h=1}^H \left(1+\frac{1}{H}\right)^{h-1} \left(48\sqrt{HC^\star K \log\frac{2H}{\delta} } + 28 c_\mathrm{a} H^{3} C^\star \sqrt{S} \iota^2 \right) \lesssim \sqrt{H^3C^\star K \log\frac{2H}{\delta}} + H^{4}C^\star \sqrt{S} \iota^2 .\label{eq:lemma6-c} \end{align} \end{subequations} \end{lemma} Substituting the above upper bounds into \eqref{equ:regret2pac-2} and \eqref{lem:lcb-adv-decompose} and recalling that $T=HK$, we arrive at \begin{align} &V_{1}^{\star}(\rho)-V_{1}^{\widehat{\pi}}(\rho) \lesssim \frac{1}{K}\max_{h\in[H]} \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_h^{\pi^\star}(s) \left(V_h^\star(s) - V_h^{k}(s)\right) \notag \\ & \lesssim \frac{1}{K} \left(\sqrt{H^4SC^\star \iota^3 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) } + \left(\sqrt{H^{3}SC^{\star}K\iota^{5}}+H^{4}SC^{\star}\iota^{4}+H^{2.75}(SC^{\star})^{\frac{3}{4}}K^{\frac{1}{4}}\iota^{2}\right) \right) \notag\\ & \overset{\mathrm{(i)}}{\asymp}\frac{1}{K}\left(\sqrt{H^4SC^\star \iota^3 \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right) } + \sqrt{H^{3}SC^{\star}K\iota^{5}}+H^{4}SC^{\star}\iota^{4}\right) \nonumber\\ & \overset{\mathrm{(ii)}}{\lesssim} \frac{1}{K}\left(\sqrt{H^{3}SC^{\star}K\iota^{5}}+H^{4}SC^{\star}\iota^{4}\right) \nonumber\\ & \asymp\sqrt{\frac{H^{4}SC^{\star}\iota^{5}}{T}}+\frac{H^{5}SC^{\star}\iota^{4}}{T}, \nonumber \end{align} where (i) has made use of the AM-GM inequality: \[ 2H^{2.75}(SC^{\star})^{\frac{3}{4}}K^{\frac{1}{4}}\leq\left(H^{0.75}(SC^{\star})^{\frac{1}{4}}K^{\frac{1}{4}}\right)^{2}+\left(H^{2}(SC^{\star})^{\frac{1}{2}}\right)^{2}=\sqrt{H^{3}SC^{\star}K}+H^{4}SC^{\star}, \] and (ii) holds by letting $x \coloneqq \max_{h\in [H] } \sum_{k=1}^K \sum_{s\in {\mathcal{S}}} d_{h}^{\pi^\star}(s) \left(V^{\star}_{h}(s) - V^{k}_{h}(s)\right)$ and solving the inequality $x \lesssim \sqrt{H^4SC^\star \iota^3 x} + \sqrt{H^{3}SC^{\star}K\iota^{5}}+H^{4}SC^{\star}\iota^{4}$. This concludes the proof. \subsection{{\sf LCB-Q-Advantage}\xspace for near-optimal offline RL} \label{sec:pessimistic-Q-vr} \begin{algorithm}[t] \textbf{Parameters:} number of epochs $M$, universal constant $c_{\mathrm{b}}>0$, probability of failure $\delta \in(0,1)$, and $\iota = \log\big(\frac{SAT}{\delta}\big)$;\\ \textbf{Initialize:} \\ $Q_h(s, a), Q_h^{{\sf LCB}\xspace}(s, a), \overline{Q}_h(s, a), \overline{\mu}_h(s,a), \overline{\mu}^{\mathsf{next}}_h(s,a), N_h(s, a) \leftarrow 0$ for all $(s,a,h) \in {\mathcal{S}}\times\mathcal{A} \times [H]$;\\ $V_h(s), \overline{V}_h(s), \overline{V}_h^{\mathsf{next}}(s) \leftarrow 0$ for all $(s,h) \in {\mathcal{S}} \times [H+1]$;\\ $\refmu_h(s, a), \sigma^{\mathsf{ref}}_h(s, a), \mu^{\mathsf{adv}}_h(s, a)$, $\sigma^{\mathsf{adv}}_h(s, a)$, $\overline{\delta}_h(s, a), \overline{B}_h(s, a) \leftarrow 0$ for all $(s, a, h) \in {\mathcal{S}}\times \mathcal{A} \times [H]$.\\[0.4em] \For{Epoch $ m = 1$ \KwTo $M$}{ $L_m= 2^m$; \small {\color{own_blue}\tcp{specify the number of episodes in the current epoch} }\normalsize $\widehat{N}_h(s,a) = 0$ for all $(h, s,a) \in [H] \times {\mathcal{S}}\times \mathcal{A}.$ \small {\color{own_blue}\tcp{reset the epoch-wise counter} }\normalsize \small {\color{own_blue}\tcc{Inner-loop: update value-estimates $V_h(s,a)$ and Q-estimates $Q_h(s,a)$ }} \normalsize \For{In-epoch Episode $ t = 1$ \KwTo $L_m$}{ Sample a new trajectory $\{s_h, a_h,r_h\}_{h=1}^H$. {\small\color{own_blue}\tcp{sampling from batch dataset}} \For{Step $ h = 1$ \KwTo $H$}{ $N_h(s_h, a_h) \leftarrow N_h(s_h, a_h) + 1$; $n \leftarrow N_h(s_h,a_h)$. {\small\color{own_blue}\tcp{update the overall counter} } $\eta_n \leftarrow \frac{H + 1}{H + n}$; \small {\color{own_blue}\tcp{update the learning rate}} \normalsize {\small\color{own_blue}\tcp{run the Q-learning update rule with LCB}} \normalsize $Q_h^{{\sf LCB}\xspace}(s_h, a_h) \leftarrow \texttt{update-lcb-q()}$. {\small\color{own_blue}\tcp{update the Q-estimate with LCB and reference-advantage}} \normalsize $\overline{Q}_h(s_h, a_h) \leftarrow \texttt{update-lcb-q-ra()}$. \small {\color{own_blue}\tcp{update the Q-estimate $Q_h$ and value estimate $V_h$}} \normalsize $Q_h(s_h,a_h) \leftarrow \max \big\{Q_h^{{\sf LCB}\xspace}(s_h, a_h), \overline{Q}_h(s_h, a_h), Q_h(s_h, a_h) \big\}.$ \label{eq:line-q-update}\\ $V_{h}(s_h) \leftarrow \max_a Q_h(s_h, a)$. \label{eq:line-v-update}\\ \small {\color{own_blue}\tcp{update the epoch-wise counter and $\overline{\mu}^{\mathsf{next}}_h$ for the next epoch}} \normalsize $\widehat{N}_h(s_h, a_h) \leftarrow \widehat{N}_h(s_h, a_h) + 1$;\\ $\overline{\mu}_h^{\mathsf{next}}(s_h, a_h) \leftarrow \left(1-\frac{1}{\widehat{N}_h(s_h,a_h)}\right)\overline{\mu}_h^{\mathsf{next}}(s_h, a_h) + \frac{1}{\widehat{N}_h(s_h,a_h)} \overline{V}^{\mathsf{next}}_{h+1}(s_{h+1})$; \label{line:ref-mean-update} } } \small {\color{own_blue}\tcc{Update the reference ($\overline{V}_h$, $\overline{V}^\mathsf{next}_h$) and ($\overline{\mu}_h$, $\overline{\mu}^\mathsf{next}_h$)} } \normalsize \For{$(s,a,h) \in {\mathcal{S}}\times\mathcal{A}\times [H+1]$}{ $\overline{V}_h(s) \leftarrow \overline{V}_h^{\mathsf{next}}(s)$; $\overline{\mu}_h(s,a)\leftarrow \overline{\mu}_h^{\mathsf{next}}(s,a)$. \label{eq:update-mu-reference-v} {\small\color{own_blue}\tcp{set $\overline{V}_h$ and $\overline{\mu}_h$ for the next epoch} } $\overline{V}_h^\mathsf{next}(s) \leftarrow V_h(s)$; $\overline{\mu}_h^\mathsf{next}(s,a) \leftarrow {0}$. {\small\color{own_blue}\tcp{restart $\overline{\mu}_h^\mathsf{next}$ and set $\overline{V}_h^\mathsf{next}$ for the next epoch} } } } \KwOut{the policy $\widehat{\pi}$ s.t.~$\widehat{\pi}_h(s) = \arg\max_a Q_{h}(s, a)$ for any $(s,h)\in {\mathcal{S}}\times[H]$.} \caption{Offline {\sf LCB-Q-Advantage}\xspace RL} \label{alg:lcb-advantage-per-epoch} \end{algorithm} \begin{figure}[t] \begin{center} \includegraphics[width=0.8\linewidth]{./figures/epoch-illu6.pdf} \end{center} \caption{An illustration of the epoch-based {\sf LCB-Q-Advantage}\xspace algorithm.} \label{alg:illu} \end{figure} The careful reader might notice that the sample complexity \eqref{eq:lcb-sample-complexity} derived for {\sf LCB-Q}\xspace remains a factor of $H^2$ away from the minimax lower bound (see Table~\ref{tab:prior-work}). To further close the gap and improve the sample complexity, we propose a new variant called {\sf LCB-Q-Advantage}\xspace, which leverages the idea of variance reduction to accelerate convergence \citep{johnson2013accelerating,sidford2018variance,wainwright2019variance,zhang2020almost,xie2021policy,li2021sample,li2021breaking}. Inspired by the reference-advantage decomposition adopted in \citep{zhang2020almost,li2021breaking} for online Q-learning, {\sf LCB-Q-Advantage}\xspace maintains a collection of reference values $\{\overline{V}_h\}_{h=1}^H$, which serve as running proxy for the optimal values $\{V^\star_h\}_{h=1}^H$ and allow for reduced variability in each iteration. To be more specific, the {\sf LCB-Q-Advantage}\xspace algorithm (cf.~Algorithm~\ref{alg:lcb-advantage-per-epoch} as well as the subroutines in Algorithm~\ref{algo:subroutine} that closely resemble \citet{li2021breaking}) proceeds in an epoch-based style (the $m$-th epoch consists of $L_{m}=2^m$ episodes of samples), where the reference values are updated at the end of each epoch to be used in the next epoch, and the Q-estimates are iteratively updated during the remaining time of each epoch. By maintaining two auxiliary sequences of {\em pessimistic} Q-estimates --- that is, $Q^{{\sf LCB}\xspace}$ constructed by the pessimistic Q-learning update, and $\overline{Q}$ constructed by the pessimistic Q-learning update based on the reference-advantage decomposition --- the Q-estimate is updated by taking the maximum over the three candidates (cf.~line~\ref{eq:line-q-update} of Algorithm~\ref{alg:lcb-advantage-per-epoch}) \begin{equation} Q_h(s,a) \leftarrow \max \{Q_h^{{\sf LCB}\xspace}(s, a),\, \overline{Q}_h(s, a),\, Q_h(s, a)\} \end{equation} when the state-action pair $(s,a)$ is visited at the step $h$. We now take a moment to discuss the key ingredients of the proposed algorithm in further detail. \paragraph{Updating the references $\overline{V}_h$ and $\overline{\mu}_h$.} At the end of each epoch, the reference values $\{\overline{V}_h\}_{h=1}^H$, as well as the associated running average $\{\overline{\mu}_h\}_{h=1}^H$, are determined using what happens during the current epoch. More specifically, the following update rules for $\overline{V}_h$ and $\overline{\mu}_h$ are carried out at the end of the $m$-th epoch: \begin{subequations} \begin{align} \overline{V}_h(s) &\leftarrow \overline{V}^{\mathsf{next}}_h(s) , \\ \overline{\mu}_h(s,a) &\leftarrow \frac{\sum_{t=1}^{L_{m}} \ind(s_h^t = s, a_h^t = a) \overline{V}_{h+1}(s_{h+1}^t)}{ \max\Big\{ \big\{ \sum_{t=1}^{L_{m}} \ind(s_h^t = s, a_h^t = a) \big\} , 1 \Big\} } \label{eq:update-mu-principle} \end{align} \end{subequations} \normalsize for all $(h,s,a)\in [H]\times {\mathcal{S}}\times\mathcal{A}$. Here, $\overline{V}_h(s)$ is assigned by $\overline{V}^{\mathsf{next}}_h(s)$, which is maintained as the value estimate $V_h(s)$ at the end of the $(m-1)$-th epoch, and the update of $\overline{\mu}_h(s,a) $ is implemented in a recursive manner in the current $m$-th epoch. See also line~\ref{eq:update-mu-reference-v} and line~\ref{line:ref-mean-update} of Algorithm~\ref{alg:lcb-advantage-per-epoch}. \paragraph{Learning Q-estimate $\overline{Q}_h$ based on the reference-advantage decomposition.} Armed with the references $\overline{V}_h$ and $\overline{\mu}_h$ updated at the end of the previous $(m-1)$-th epoch, {\sf LCB-Q-Advantage}\xspace iteratively updates the Q-estimate $\overline{Q}_h$ in all episodes during the $m$-th epoch. At each time step $h$ in any episode, whenever $(s,a)$ is visited, {\sf LCB-Q-Advantage}\xspace updates the reference Q-value as follows: \begin{align} &\overline{Q}_h(s, a) \leftarrow (1-\eta)\overline{Q}_h(s, a) + \eta\Big\{ r_h(s,a) + \underset{\text{estimate of } P_{h,s,a} (V_{h+1} - \overline{V}_{h+1})}{\underbrace{\widehat{P}_{h,s,a} \big(V_{h+1}- \overline{V}_{h+1}\big)}} \hspace{-0.3em} + \hspace{-0.3em} \underset{\text{estimate of } P_{h,s,a}\overline{V}_{h+1}}{\underbrace{\overline{\mu}_h}} \hspace{-1.0em} - \overline{b}_h(s, a) \Big\}. \label{eq:lcb-adv-principle-rule} \end{align} Intuitively, we decompose the target $P_{h,s,a} V_{h+1}$ into a reference part $P_{h,s,a}\overline{V}_{h+1}$ and an advantage part $P_{h,s,a} (V_{h+1} - \overline{V}_{h+1})$, and cope with the two parts separately. In the sequel, let us take a moment to discuss three essential ingredients of the update rule \eqref{eq:lcb-adv-principle-rule}, which shed light on the design rationale of our algorithm. \begin{itemize} \item Akin to {\sf LCB-Q}\xspace, the term $\widehat{P}_{h,s,a} \big(V_{h+1}- \overline{V}_{h+1}\big)$ serves as an unbiased stochastic estimate of $P_{h,s,a} \left(V_{h+1}- \overline{V}_{h+1}\right)$ if a sample transition $(s,a,s_{h+1})$ at time step $h$ is observed. If $V_{h+1}$ stays close to the reference $\overline{V}_{h+1}$ as the algorithm proceeds, the variance of this stochastic term can be lower than that of the stochastic term $\widehat{P}_{h,s,a} V_{h+1}$ in \eqref{equ:lcb-q-update}. \item The auxiliary estimate $\overline{\mu}_h$ introduced in \eqref{eq:update-mu-principle} serves as a running estimate of the reference part $P_{h,s,a} \overline{V}_{h+1}$. Based on the update rule \eqref{eq:update-mu-principle}, we design $\overline{\mu}_h(s,a)$ to estimate the running mean of the reference part $\big[P_{h,s,a} \overline{V}_{h+1}\big]$ using a number of previous samples. As a result, we expect the variability of this term to be well-controlled, particularly as the number of samples in each epoch grows exponentially (recall that $L_m=2^m$). \item In each episode, the term $\overline{b}_h(s,a)$ serves as the additional confidence bound on the error between the estimates of the reference/advantage and the ground truth. More specifically, $\refmu_h(s, a)$ and $\sigma^{\mathsf{ref}}_h(s, a)$ are respectively the running mean and 2nd moment of the reference part $\big[P_{h,s,a} \overline{V}_{h+1}\big]$ (cf.~lines~\ref{line:refmu_h}-\ref{line:refsigma_h} of Algorithm~\ref{algo:subroutine}); $\mu^{\mathsf{adv}}_h(s, a)$ and $\sigma^{\mathsf{adv}}_h(s, a)$ represent respectively the running mean and 2nd moment of the advantage part $\big[P_{h,s,a}(V_{h+1} - \overline{V}_{h+1})\big]$ (cf.~lines~\ref{line:advmu_h}-\ref{line:advsigma_h} of Algorithm~\ref{algo:subroutine}); $\overline{B}_h(s, a)$ aggregates the empirical standard deviations of the reference and the advantage parts. The LCB penalty term $ \overline{b}_h(s, a)$ is updated using $ \overline{B}_h(s, a)$ and $\overline{\delta}_h(s_h, a_h)$ (cf.~lines~\ref{line:bonus_1}-\ref{line:bonus_2} of Algorithm~\ref{algo:subroutine}), taking into account the confidence bounds for both the reference and the advantage. \end{itemize} In a nutshell, the auxiliary sequences of the reference values are designed to help reduce the variance of the stochastic Q-learning updates, which taken together with the principle of pessimism play a crucial role in the improvement of sample complexity for offline RL. \subsection{Theoretical guarantees for {\sf LCB-Q-Advantage}\xspace} Encouragingly, the proposed {\sf LCB-Q-Advantage}\xspace algorithm provably achieves near-optimal sample complexity for sufficiently small $\varepsilon$, as demonstrated by the following theorem. \begin{theorem}\label{thm:lcb-adv} Consider any $\delta \in (0,1)$, and recall that $\iota=\log\big( \frac{SAT}{\delta} \big)$ and $T=KH$. Suppose that $c_{\mathrm{b}}>0$ is chosen to be a sufficiently large constant, and that the behavior policy $\mu$ satisfies Assumption~\ref{assumption}. Then there exists some universal constant $c_{\mathrm{g}}>0$ such that with probability at least $1-\delta$, the policy $\widehat{\pi}$ output by Algorithm~\ref{alg:lcb-advantage-per-epoch} satisfies \begin{align}\label{equ:lcb-result} V_1^\star(\rho) - V_1^{\widehat{\pi}}(\rho) &\leq c_{\mathrm{g}} \bigg(\sqrt{ \frac{H^4SC^\star \iota^5}{T}} + \frac{H^5 SC^\star \iota^4}{T} \bigg). \end{align} \end{theorem} As a consequence, Theorem~\ref{thm:lcb-adv} reveals that the {\sf LCB-Q-Advantage}\xspace algorithm is guaranteed to find an $\varepsilon$-optimal policy (i.e., $V_1^\star(\rho) - V_1^{\widehat{\pi}}(\rho)\leq \varepsilon$) as long as the total sample size $T$ exceeds \begin{equation} \widetilde{O}\left(\frac{H^4 S C^\star}{\varepsilon^2} + \frac{H^5 S C^\star}{\varepsilon}\right). \label{eq:sample-complexity-LCB-ADV-full} \end{equation} For sufficiently small accuracy level $\varepsilon$ (i.e., $\varepsilon\leq 1/H$), this results in a sample complexity of \small \begin{equation} \widetilde{O}\left(\frac{H^4 S C^\star}{\varepsilon^2} \right), \label{eq:sample-complexity-LCB-ADV} \end{equation} \normalsize thereby matching the minimax lower bound developed in \citet{xie2021policy} up to logarithmic factor. Compared with the minimax lower bound $\Omega \big( \frac{H^4SA}{\varepsilon^2}\big)$ in the online RL setting \citep{domingues2021episodic}, this suggests that offline RL can be fairly sample-efficient when the behavior policy closely mimics the optimal policy in terms of the resulting state-action occupancy distribution (a scenario where $C^{\star}$ is potentially much smaller than the size of the action space). \paragraph{Comparison with offline model-based approaches.} In the same offline finite-horizon setting, the state-of-art model-based approach called {\sf PEVI-Adv} has been proposed by \citet{xie2021policy}, which also leverage the idea of reference-advantage decomposition. In comparison with {\sf PEVI-Adv}, {\sf LCB-Q-Advantage}\xspace not only enjoys the flexibility of model-free approaches, but also achieves optimal sample complexity for a broader range of target accuracy level $\varepsilon$. More precisely, the $\varepsilon$-range for which the algorithm achieves sample optimality can be compared as follows: \begin{align} \underbrace{\varepsilon \leq \left(0, H^{-1}\right]}_{\text{ (Our {\sf LCB-Q-Advantage}\xspace)}} \quad \text{vs.} \quad \underbrace{\varepsilon \leq \left(0, H^{-2.5}\right]}_{\text{ ({\sf PEVI-Adv})}}, \end{align} offering an improvement by a factor of $H^{1.5}$. \section{Pessimistic Q-learning: algorithms and theory} \label{sec:algorithm-theory-lcbq} In the current paper, we present two model-free algorithms --- namely, {\sf LCB-Q}\xspace and {{\sf LCB-Q-Advantage}\xspace} --- for offline RL, along with their respective theoretical guarantees. The first algorithm can be viewed as a pessimistic variant of the classical Q-learning algorithm, while the second one further leverages the idea of variance reduction to boost the sample efficiency. In this section, we begin by introducing {\sf LCB-Q}\xspace. \subsection{{\sf LCB-Q}\xspace: a natural pessimistic variant of Q-learning} Before proceeding, we find it convenient to first review the classical Q-learning algorithm \citep{watkins1989learning,watkins1992q}, which can be regarded as a stochastic approximation scheme to solve the Bellman optimality equation \eqref{eq:bellman_optimality}. Upon receiving a sample transition $(s_h,a_h,r_h,s_{h+1})$ at time step $h$, Q-learning updates the corresponding entry in the Q-estimate as follows \begin{align} \label{eq:classical-Q-update} Q_h(s_h,a_h) ~\leftarrow~ & (1-\eta )Q_h(s_h,a_h) + \eta \Big \{ r_h(s_h,a_h) + V_{h+1}(s_{h+1}) \Big \} , \end{align} where $Q_h$ (resp.~$V_h$) indicates the running estimate of $Q_h^{\star}$ (resp.~$V_h^{\star}$), and $0<\eta<1$ is the learning rate. In comparison to model-based algorithms that require estimating the probability transition kernel based on all the samples, Q-learning, as a popular kind of model-free algorithms, is simpler and enjoys more flexibility without explicitly constructing the model of the environment. The wide applicability of Q-learning motivates one to adapt it to accommodate offline RL. Inspired by recent advances in incorporating the pessimism principle for offline RL \citep{rashidinejad2021bridging,jin2021pessimism}, we study a pessimistic variant of Q-learning called {\sf LCB-Q}\xspace, which modifies the Q-learning update rule as follows \begin{align} \label{equ:lcb-q-update} Q_h(s_h, a_h) \leftarrow & (1-\eta_n )Q_h(s_h, a_h) + \eta_n \Big\{ r_h(s_h,a_h) + V_{h+1}(s_{h+1}) - b_n \Big\}, \end{align} where $\eta_n$ is the learning rate depending on the number of times $n$ that the state-action pair $(s_h,a_h)$ has been visited at step $h$, and the penalty term $b_n>0$ (cf.~line~\ref{line:2} of Algorithm~\ref{algo:lcb-index}) reflects the uncertainty of the corresponding Q-estimate and implements pessimism in the face of uncertainty. The entire algorithm, which is a {\em single-pass} algorithm that only requires reading the offline dataset once, is summarized in Algorithm~\ref{algo:lcb-index}. \begin{algorithm}[h] \textbf{Parameters:} some constant $c_{\mathrm{b}}>0$, target success probability $1-\delta \in(0,1)$, and $\iota = \log\big(\frac{SAT}{\delta}\big)$. \\ \textbf{Initialize} $Q_h(s, a) \leftarrow 0$, $N_h(s, a)\leftarrow 0$, and $V_h(s) \leftarrow 0$ for all $(s,a,h)\in {\mathcal{S}}\times \mathcal{A}\times[H+1]$; $\widehat{\pi}$ s.t. $\widehat{\pi}_h(s) = 1$ for all $(h,s)\in [H]\times{\mathcal{S}}$. \\ \For{Episode $ k = 1$ \KwTo $K$}{ Sample a new trajectory $\{s_h, a_h, r_h\}_{h=1}^H$ from $\mathcal{D}_{\mu}$. {\small\color{own_blue}\tcp{sampling from batch dataset}} {\small\color{own_blue}\tcp{update the policy} } \normalsize \For{Step $ h = 1$ \KwTo $H$}{ $N_h(s_h, a_h) \leftarrow N_h(s_h, a_h) + 1$. {\small\color{own_blue}\tcp{update the counter} } $n \leftarrow N_h(s_h, a_h)$; $\eta_n \leftarrow \frac{H + 1}{H + n}$. {\small\color{own_blue}\tcp{update the learning rate}} $b_n \leftarrow c_{\mathrm{b}} \sqrt{\frac{H^3\iota^2}{n}}$. \label{line:2-nok} {\small\color{own_blue}\tcp{update the bonus term}} {\small\color{own_blue}\tcp{run the Q-learning update with LCB} } \normalsize $Q_h(s_h, a_h) \leftarrow Q_h(s_h, a_h) + \eta_n\Big\{ r_h(s_h, a_h) + V_{h+1}(s_{h+1})-Q_h(s_h, a_h) - b_n \Big\} $. \label{line:lcb-9-nok} \\ {\small\color{own_blue}\tcp{update the value estimates}} \normalsize $V_{h}(s_h) \leftarrow \max\Big\{ V_{h}(s_h), \, \max_a Q_{h}(s_h, a) \Big\}$. \label{line:lcb_v_update}\\ \label{line:lcb-10} If $V_{h}(s_h) = \max_a Q_{h}(s_h, a)$: update $\widehat{\pi}_h(s) \leftarrow \arg\max_a Q_{h}(s, a)$. } } \textbf{Output:} the policy $\widehat{\pi}$. \caption{{\sf LCB-Q}\xspace for offline RL} \label{algo:lcb-index} \end{algorithm} \subsection{Theoretical guarantees for {\sf LCB-Q}\xspace{}} The proposed {{\sf LCB-Q}\xspace{}} algorithm manages to achieve an appealing sample complexity as formalized by the following theorem. \begin{theorem}\label{thm:lcb} Consider any $\delta \in (0,1)$. Suppose that the behavior policy $\mu$ satisfies Assumption~\ref{assumption} with single-policy concentrability coefficient $C^{\star}\geq 1$. Let $c_{\mathrm{b}}>0$ be some sufficiently large constant, and take $\iota \coloneqq \log\big(\frac{SAT}{\delta}\big)$. Assume that $T>SC^\star \iota$, then the policy $\widehat{\pi}$ returned by Algorithm~\ref{algo:lcb-index} satisfies \begin{align}\label{equ:lcb-result} V_1^\star(\rho) - V_1^{\widehat{\pi}}(\rho) &\leq c_\mathrm{a} \sqrt{\frac{H^6 SC^\star \iota^3}{T}} \end{align} with probability at least $1-\delta$, where $c_\mathrm{a}>0$ is some universal constant. \end{theorem} As asserted by Theorem~\ref{thm:lcb}, the {{\sf LCB-Q}\xspace{}} algorithm is guaranteed to find an $\varepsilon$-optimal policy with high probability, as long as the total sample size $T=KH$ exceeds % \begin{equation} \widetilde{O}\left( \frac{H^6 S C^\star}{\varepsilon^2} \right), \label{eq:lcb-sample-complexity} \end{equation} where $\widetilde{O}(\cdot)$ hides logarithmic dependencies. When the behavior policy is close to the optimal policy, the single-policy concentrability coefficient $C^{\star}$ is closer to 1; if this is the case, then our bound indicates that the sample complexity does not depend on the size $A$ of the action space, which can be a huge saving when the action space is enormous. \paragraph{Comparison with model-based pessimistic approaches.} A model-based approach --- called Value Iteration with Lower Confidence Bounds ({\sf VI-LCB}\xspace) --- has been recently proposed for offline RL \citep{rashidinejad2021bridging,xie2021policy}. In the finite-horizon case, {\sf VI-LCB}\xspace{} incorporates an additional LCB penalty into the classical value iteration algorithm, and updates {\em all} the entries in the Q-estimate simultaneously as follows \begin{align} Q_h(s,a) ~\leftarrow~ r_h(s,a) + \widehat{P}_{h,s,a}V_{h+1} - b_h(s,a), \label{equ:VI-UCB} \end{align} with the aim of tuning down the confidence on those state-action pairs that have only been visited infrequently. Here, $\widehat{P}_{h,s,a}$ represents the empirical estimation of the transition kernel $P_{h,s,a}$, and $b_h(s,a) >0$ is chosen to capture the uncertainty level of $(\widehat{P}_{h,s,a} -P_{h,s,a})V_{h+1}$. Working backward, the algorithm estimates the Q-value $Q_h$ recursively over the time steps $h = H, H-1, \cdots, 1$. In comparison with {\sf VI-LCB}\xspace, our sample complexity bound for {{\sf LCB-Q}\xspace{}} matches the bound developed for {\sf VI-LCB}\xspace{} by \citet{xie2021policy}, while enjoying enhanced flexibility without the need of specifying the transition kernel of the environment (as model estimation might potentially incur a higher memory burden). \section{Technical lemmas} \subsection{Preliminary facts} Our results rely heavily on proper choices of the learning rates. In what follows, we make note of several useful properties concerning the learning rates, which have been established in \cite{jin2018q,li2021breaking}. \begin{lemma}[Lemma 1 in \citep{li2021breaking}] \label{lemma:property of learning rate} For any integer $N>0$, the following properties hold: \begin{subequations} \label{eq:properties-learning-rates} \begin{align} & \frac{1}{N^a} \le\sum_{n=1}^{N}\frac{\eta_{n}^{N}}{n^a}\le\frac{2}{N^a} \qquad \mbox{for all}\quad \frac{1}{2} \leq a \leq 1, \label{eq:properties-learning-rates-12}\\ \max_{1\le n\le N} & \eta_{n}^{N}\le\frac{2H}{N},\qquad\sum_{n=1}^{N}(\eta_{n}^{N})^{2}\le\frac{2H}{N}, \qquad \sum_{N=n}^{\infty}\eta_{n}^{N}\le1+\frac{1}{H}. \label{eq:properties-learning-rates-345} \end{align} \end{subequations} \end{lemma} In addition, we gather a few elementary properties about the Binomial distribution, which will be useful throughout the proof. The lemma below is adapted from \citet[Lemma A.1]{xie2021policy}. \begin{lemma}\label{lem:binomial} Suppose $N\sim \mathsf{Binomial}(n,p)$, where $n\geq 1$ and $p\in [0,1]$. For any $\delta\in (0,1)$, we have \begin{align} \frac{p}{N\vee 1} &\leq \frac{8\log\left(\frac{1}{\delta}\right)}{n}, \label{equ:binomial} \end{align} and \begin{subequations} \label{equ:binomial-all} \begin{align} N&\geq \frac{np}{8\log\left(\frac{1}{\delta}\right)} \qquad \text{ if } np \geq 8\log\left(\frac{1}{\delta}\right), \label{equ:binomial2}\\ N &\leq \begin{cases} e^2np & \text{ if } np \geq \log\left(\frac{1}{\delta}\right), \\ 2e^2 \log\left(\frac{1}{\delta}\right) & \text{ if } np \leq 2\log\left(\frac{1}{\delta}\right). \end{cases} \label{equ:binomial3} \end{align} \end{subequations} with probability at least $1 - 4\delta$. \end{lemma} \begin{proof} To begin with, we directly invoke \citet[Lemma A.1]{xie2021policy} which yields the results in \eqref{equ:binomial} and \eqref{equ:binomial2}. Regarding \eqref{equ:binomial3}, invoking the Chernoff bound \citep[Theorem 2.3.1]{vershynin2018high} with $\mathbb{E}[N] = np$, when $np \geq \log\left(\frac{1}{\delta}\right)$, it satisfies \begin{align*} \mathbb{P}(N \geq e^2np) &\leq e^{-np}\left(\frac{enp}{e^2np}\right)^{ e^2np} \leq e^{-np} \leq \delta. \end{align*} Similarly, when $ np \leq 2\log\left(\frac{1}{\delta}\right)$, we have \begin{align*} \mathbb{P}\left(N \geq 2e^2\log\left(\frac{1}{\delta}\right)\right)& \overset{\mathrm{(i)}}{\leq} e^{-np}\left(\frac{enp}{2e^2\log\left(\frac{1}{\delta}\right)}\right)^{ 2e^2\log(\frac{1}{\delta})} \\ &\overset{\mathrm{(ii)}}{\leq} e^{-np}\left(\frac{enp}{e^2np}\right)^{ 2e^2\log(\frac{1}{\delta})} \leq e^{-2e^2 \log\left(\frac{1}{\delta}\right)} \leq \delta, \end{align*} where (i) results from \citet[Theorem 2.3.1]{vershynin2018high}, and (ii) follows from the basic fact $e^2\log\left(\frac{1}{\delta}\right) \geq 2\log\left(\frac{1}{\delta}\right) \geq np$. Taking the union bound thus completes the proof. \end{proof} \subsection{Freedman's inequality and its consequences} Both the samples collected within each episode and the algorithms analyzed herein exhibit certain Markovian structure. As a result, concentration inequalities tailored to martingales become particularly effective for our analysis. In this subsection, we collect a few useful concentration results that will be applied multiple times in the current paper. These results might be of independent interest. To begin with, the following theorem provides a user-friendly version of Freedman's inequality \citep{freedman1975tail}; see \citet[Section C]{li2021tightening} for more details. \begin{theorem}[Freedman's inequality]\label{thm:Freedman} Consider a filtration $\mathcal{F}_0\subset \mathcal{F}_1 \subset \mathcal{F}_2 \subset \cdots$, and let $\mathbb{E}_{k}$ stand for the expectation conditioned on $\mathcal{F}_k$. Suppose that $Y_{n}=\sum_{k=1}^{n}X_{k}\in\mathbb{R}$, where $\{X_{k}\}$ is a real-valued scalar sequence obeying \[ \left|X_{k}\right|\leq R\qquad\text{and}\qquad\mathbb{E}_{k-1} \big[X_{k}\big]=0\quad\quad\quad\text{for all }k\geq1 \] for some quantity $R<\infty$. We also define \[ W_{n}\coloneqq\sum_{k=1}^{n}\mathbb{E}_{k-1}\left[X_{k}^{2}\right]. \] In addition, suppose that $W_{n}\leq\sigma^{2}$ holds deterministically for some given quantity $\sigma^2<\infty$. Then for any positive integer $m \geq1$, with probability at least $1-\delta$ one has \begin{equation} \left|Y_{n}\right|\leq\sqrt{8\max\Big\{ W_{n},\frac{\sigma^{2}}{2^{m}}\Big\}\log\frac{2m}{\delta}}+\frac{4}{3}R\log\frac{2m}{\delta}.\label{eq:Freedman-random} \end{equation} \end{theorem} We shall also record some immediate consequence of Freedman's inequality tailored to our problem. Recall that $N_h^i(s,a)$ denotes the number of times that $(s,a)$ has been visited at step $h$ before the beginning of the $i$-th episode, and $k^n(s,a)$ stands for the index of the episode in which $(s,a)$ is visited for the $n$-th time. The following concentration bound has been established in \citet[Lemma 7]{li2021breaking}. \begin{lemma} \label{lemma:martingale-union-all} Let $\big\{ W_{h}^{i} \in \mathbb{R}^S \mid 1\leq i\leq K, 1\leq h \leq H+1 \big\}$ and $\big\{u_h^i(s,a,N)\in \mathbb{R} \mid 1\leq i\leq K, 1\leq h \leq H+1 \big\}$ be a collections of vectors and scalars, respectively, and suppose that they obey the following properties: % \begin{itemize} \item $W_{h}^{i}$ is fully determined by the samples collected up to the end of the $(h-1)$-th step of the $i$-th episode; \item $\|W_h^i\|_{\infty}\leq C_\mathrm{w}$; \item $u_h^i(s,a, N)$ is fully determined by the samples collected up to the end of the $(h-1)$-th step of the $i$-th episode, and a given positive integer $N\in[K]$; \item $0\leq u_h^i(s,a, N) \leq C_{\mathrm{u}}$; \item $0\leq \sum_{n=1}^{N_h^k(s,a)} u_h^{k_h^n(s,a)}(s,a, N) \leq 2$. \end{itemize} % In addition, consider the following sequence \begin{align} X_i (s,a,h,N) &\coloneqq u_h^i(s,a, N) \big(P_h^{i} - P_{h,s,a}\big) W_{h+1}^{i} \ind\big\{ (s_h^i, a_h^i) = (s,a)\big\}, \qquad 1\leq i\leq K, \end{align} with $P_h^{i}$ defined in \eqref{eq:Phk_def}. Consider any $\delta \in (0,1)$. Then with probability at least $1-\delta$, % \begin{align} & \left|\sum_{i=1}^k X_i(s,a,h,N) \right| \notag\\ & \quad \lesssim \sqrt{C_{\mathrm{u}} \log^2\frac{SAT}{\delta}}\sqrt{\sum_{n = 1}^{N_h^k(s,a)} u_h^{k_h^n(s,a)}(s,a,N) \mathsf{Var}_{h, s,a} \big(W_{h+1}^{k_h^n(s,a)} \big)} + \left(C_{\mathrm{u}} C_{\mathrm{w}} + \sqrt{\frac{C_{\mathrm{u}}}{N}} C_{\mathrm{w}}\right) \log^2\frac{SAT}{\delta} \end{align} % holds simultaneously for all $(k, h, s, a, N) \in [K] \times [H] \times {\mathcal{S}} \times \mathcal{A} \times [K]$. \end{lemma} Next, we make note of an immediate consequence of Lemma~\ref{lemma:martingale-union-all} as follows. \begin{lemma}\label{lemma:azuma-hoeffding} Let $\big\{ W_{h}^{i} \in \mathbb{R}^S \mid 1\leq i\leq K, 1\leq h \leq H+1 \big\}$ be a collection of vectors satisfying the following properties: \begin{itemize} \item $W_{h}^{i}$ is fully determined by the samples collected up to the end of the $(h-1)$-th step of the $i$-th episode; \item $\|W_h^i\|_{\infty}\leq C_\mathrm{w}$. \end{itemize} For any positive $N \geq H$, we consider the following sequence \begin{align} X_i(s,a,h,N) &\coloneqq \eta_{N_h^i(s,a)}^N \big(P_h^{i} - P_{h,s,a}\big) W_{h+1}^{i} \ind\big\{ (s_h^i, a_h^i) = (s,a)\big\}, \qquad 1\leq i\leq K, \end{align} with $P_h^{i}$ defined in \eqref{eq:Phk_def}. Consider any $\delta\in (0,1)$. With probability at least $1-\delta$, \begin{align} & \left|\sum_{i=1}^k X_i(s,a,h,N) \right| \lesssim \sqrt{\frac{H}{N} C_{\mathrm{w}}^2 }\log^2\frac{SAT}{\delta} \end{align} holds simultaneously for all $(k, h, s, a, N) \in [K] \times [H] \times {\mathcal{S}} \times \mathcal{A} \times [K]$. \end{lemma} \begin{proof} Taking $u_{h}^{i}(s,a,N)=\eta_{N_{h}^{i}(s,a)}^{N}$, one can see from \eqref{eq:properties-learning-rates-345} in Lemma~\ref{lemma:property of learning rate} that \[ \big|u_{h}^{i}(s,a,N)\big|\leq\frac{2H}{N}\eqqcolon C_{\mathrm{u}}. \] Recognizing the trivial bound $\mathsf{Var}_{h,s,a}\big(W_{h+1}^{k_{h}^{n}(s,a)}\big)\leq C_{\mathrm{w}}^{2}$, we can invoke Lemma~\ref{lemma:martingale-union-all} to obtain that, with probability at least $1-\delta$, \begin{align*} \Bigg|\sum_{i=1}^{k}X_{i}(s,a,h,N)\Bigg| & \lesssim\sqrt{C_{\mathrm{u}}\log^{2}\frac{SAT}{\delta}}\sqrt{\sum_{n=1}^{N_{h}^{k}(s,a)}\eta_{n}^{N}C_{\mathrm{w}}^{2}}+\left(C_{\mathrm{u}}C_{\mathrm{w}}+\sqrt{\frac{C_{\mathrm{u}}}{N}}C_{\mathrm{w}}\right)\log^{2}\frac{SAT}{\delta}\\ & \lesssim\sqrt{\frac{H}{N}\log^{2}\frac{SAT}{\delta}}\cdot C_{\mathrm{w}}+\frac{HC_{\mathrm{w}}}{N}\log^{2}\frac{SAT}{\delta}\lesssim\sqrt{\frac{HC_{\mathrm{w}}^{2}}{N}}\log^{2}\frac{SAT}{\delta} \end{align*} holds simultaneously for all $(k, h, s, a, N) \in [K] \times [H] \times {\mathcal{S}} \times \mathcal{A} \times [K]$, where the last line applies \eqref{eq:properties-learning-rates-345} in Lemma~\ref{lemma:property of learning rate} once again. \end{proof} Finally, we introduce another lemma by invoking Freedman's inequality in Theorem~\ref{thm:Freedman}. \begin{lemma} \label{lemma:martingale-union-recursion} Let $\big\{ W_{h}^{k}(s,a) \in \mathbb{R}^S \mid (s,a)\in{\mathcal{S}}\times \mathcal{A}, 1\leq k\leq K, 1\leq h \leq H+1 \big\}$ be a collection of vectors satisfying the following properties: \begin{itemize} \item $W_{h}^{k}(s,a)$ is fully determined by the given state-action pair $(s,a)$ and the samples collected up to the end of the $(k-1)$-th episode; \item $\|W_h^k(s,a)\|_{\infty}\leq C_\mathrm{w}$. \end{itemize} For any positive $ C_{\mathrm{d}} \geq 0$, we consider the following sequences \begin{align} X_{h,k} &\coloneqq C_{\mathrm{d}} \left[\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} P_{h,s_h^k,a_h^k}W_{h+1}^{k}(s_h^k,a_h^k) - \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}W_{h+1}^{k}(s,a)\right], \qquad 1\leq k\leq K,\\ \overline{X}_{h,k} &\coloneqq C_{\mathrm{d}} \left[\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} P_{h}^k W_{h+1}^{k}(s_h^k,a_h^k) - \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}W_{h+1}^{k}(s,a)\right], \qquad 1\leq k\leq K. \end{align} Consider any $\delta \in (0,1)$. Then with probability at least $1-\delta$, % \begin{align} & \left|\sum_{k=1}^K X_{h,k}\right| \leq \sqrt{\sum_{k=1}^K 8 C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \\ &\left|\sum_{k=1}^K \overline{X}_{h,k}\right| \leq \sqrt{\sum_{k=1}^K 8 C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \end{align} % hold simultaneously for all $h\in[H]$. \end{lemma} \begin{proof} We intend to apply Freedman's inequality (cf.~Theorem~\ref{thm:Freedman}) to control $\sum_{k=1}^K X_{h,k}$. Considering any given time step $h$, it is easily verified that \begin{align*} \mathbb{E}_{k-1}[X_{h,k}] =0, \qquad \mathbb{E}_{k-1}[\overline{X}_{h,k}] =0, \end{align*} where $\mathbb{E}_{k-1}$ denotes the expectation conditioned on everything happening up to the end of the $(k-1)$-th episode. To continue, we observe that \begin{align} |X_{h,k}| \leq C_{\mathrm{d}}\left(\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} + 1\right) \left\|W_{h+1}^k(s,a)\right\|_\infty \leq 2C_{\mathrm{d}} C^\star C_\mathrm{w}, \label{eq:X-R}\\ |\overline{X}_{h,k}| \leq C_{\mathrm{d}}\left(\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} + 1\right) \left\|W_{h+1}^k(s,a)\right\|_\infty \leq 2C_{\mathrm{d}} C^\star C_\mathrm{w}, \label{eq:X-R-2} \end{align} where we use the assumptions $\frac{d_{h}^{\pi_{\star}}(s,a)}{d_{h}^{\mu}(s,a)} \leq C^\star$ for all $(h,s,a)\in[H]\times {\mathcal{S}}\times \mathcal{A}$ (cf.~Assumption~\ref{assumption}) and $\left\|W_{h+1}^k(s_h^k,a_h^k)\right\|_\infty \leq C_{\mathrm{w}}$. Recall that $\Delta({\mathcal{S}} \times \mathcal{A})$ is the probability simplex over the set ${\mathcal{S}}\times \mathcal{A}$ of all state-action pairs, and we denote by $d_h^{\mu} \in \Delta({\mathcal{S}} \times \mathcal{A})$ the state-action visitation distribution induced by the behavior policy $\mu$ at time step $h\in[H]$. With this in hand, we obtain \begin{align} \sum_{k=1}^K \mathbb{E}_{k-1}[|X_{h,k}|^2] &\leq \sum_{k=1}^K C_{\mathrm{d}}^2 \mathbb{E}_{k-1}\left[\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} P_{h,s_h^k,a_h^k}W_{h+1}^{k}(s_h^k,a_h^k) - \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \nonumber\\ & \leq \sum_{k=1}^K C_{\mathrm{d}}^2 \mathbb{E}_{(s_h^k,a_h^k) \sim d_h^\mu}\left[\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} P_{h,s_h^k,a_h^k}W_{h+1}^{k}(s_h^k,a_h^k)\right]^2 \nonumber\\ & = \sum_{k=1}^K C_{\mathrm{d}}^2 \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} \frac{d_{h}^{\pi_{\star}}(s,a)}{d_{h}^{\mu}(s,a)}d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \nonumber\\ & \overset{\mathrm{(i)}}{\leq} \sum_{k=1}^K C_{\mathrm{d}}^2 C^\star\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \label{eq:var-of-w} \\ &\leq \sum_{k=1}^K C_{\mathrm{d}}^2 \sum_{(s,a)\in {\mathcal{S}}\times\mathcal{A}}C^\star d_{h}^{\pi_{\star}}(s,a) \left\|W_{h+1}^k(s_h^k,a_h^k)\right\|_\infty^2 \leq C_{\mathrm{d}}^2 C^\star C_{\mathrm{w}}^2 K, \label{eq:var-of-w-crude} \end{align} where (i) follows from $\frac{d_{h}^{\pi_{\star}}(s,a)}{d_{h}^{\mu}(s,a)} \leq C^\star$ (see Assumption~\ref{assumption}) and the assumption $\left\|W_{h+1}^k(s_h^k,a_h^k)\right\|_\infty \leq C_{\mathrm{w}}$. Similarly, we can derive \begin{align} \sum_{k=1}^K \mathbb{E}_{k-1}[|\overline{X}_{h,k}|^2] &\leq \sum_{k=1}^K C_{\mathrm{d}}^2 \mathbb{E}_{k-1}\left[\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} P_h^k W_{h+1}^{k}(s_h^k,a_h^k) - \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \nonumber\\ & \leq \sum_{k=1}^K C_{\mathrm{d}}^2 \mathbb{E}_{(s_h^k,a_h^k) \sim d_h^\mu} \left[ \mathbb{E}_{P_h^k \sim P_{h,s_h^k,a_h^k}} \left[\frac{d_{h}^{\pi_{\star}}(s_h^k,a_h^k)}{d_{h}^{\mu}(s_h^k,a_h^k)} P_h^k W_{h+1}^{k}(s_h^k,a_h^k)\right]^2 \right] \nonumber\\ & = \sum_{k=1}^K C_{\mathrm{d}}^2 \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} \frac{d_{h}^{\pi_{\star}}(s,a)}{d_{h}^{\mu}(s,a)}d_{h}^{\pi_{\star}}(s,a) \mathbb{E}_{P_h^k \sim P_{h,s,a}}\left[P_h^k W_{h+1}^{k}(s,a)\right]^2 \nonumber\\ & \overset{\mathrm{(i)}}{\leq} \sum_{k=1}^K C_{\mathrm{d}}^2 C^\star\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \mathbb{E}_{P_h^k \sim P_{h,s,a}}\left[P_h^k W_{h+1}^{k}(s,a)\right]^2 \label{eq:var-of-w-2}\\ & = \sum_{k=1}^K C_{\mathrm{d}}^2 C^\star\sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2 \label{eq:var-of-w-2}\\ &\leq \sum_{k=1}^K C_{\mathrm{d}}^2 \sum_{(s,a)\in {\mathcal{S}}\times\mathcal{A}}C^\star d_{h}^{\pi_{\star}}(s,a) \left\|W_{h+1}^k(s,a)\right\|_\infty^2 \leq C_{\mathrm{d}}^2 C^\star C_{\mathrm{w}}^2 K, \label{eq:var-of-w-crude-2} \end{align} where (i) follows from $\frac{d_{h}^{\pi_{\star}}(s,a)}{d_{h}^{\mu}(s,a)} \leq C^\star$ (see Assumption~\ref{assumption}) and the assumption $\left\|W_{h+1}^k(s_h^k,a_h^k)\right\|_\infty \leq C_{\mathrm{w}}$. Plugging in the results in \eqref{eq:X-R} and \eqref{eq:var-of-w} (resps.~\eqref{eq:X-R-2} and \eqref{eq:var-of-w-2}) to control $\sum_{k=1}^K \left|X_{h,k}\right|$ (resps.~$\sum_{k=1}^K \left|\overline{X}_{h,k}\right|$), we invoke Theorem~\ref{thm:Freedman} with $m=\lceil \log_2 K \rceil$ and take the union bound over $h\in[H]$ to show that with probability at least $1-\delta$, \begin{align} \left|\sum_{k=1}^K X_{h,k}\right|& \leq\sqrt{8\max\left\{\sum_{k=1}^K C_{\mathrm{d}}^2C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2, \frac{C_{\mathrm{d}}^2 C^\star C_{\mathrm{w}}^2 K}{2^m}\right\} \log\frac{2H}{\delta}} \nonumber \\ &\qquad + \frac{8}{3}C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ &\leq \sqrt{\sum_{k=1}^K 8 C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 6C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \end{align} and \begin{align} \left|\sum_{k=1}^K \overline{X}_{h,k}\right|& \leq\sqrt{8\max\left\{\sum_{k=1}^K C_{\mathrm{d}}^2C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}}d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2, \frac{C_{\mathrm{d}}^2 C^\star C_{\mathrm{w}}^2 K}{2^m}\right\} \log\frac{2H}{\delta}} \nonumber \\ &\qquad + \frac{8}{3}C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ &\leq \sqrt{\sum_{k=1}^K 8 C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi_{\star}}(s,a) P_{h,s,a}\left[W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 6C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \end{align} holds simultaneously for all $h\in[H]$. \end{proof} \subsection{Proof of Lemma~\ref{lemma:recursion}}\label{proof:lemma-lcb-revursion} We make the observation that Lemma~\ref{lemma:recursion} would follow immediately if we could establish the following relation: \begin{align} A_h & \coloneqq \sum_{k=1}^K \underbrace{\sum_{(s, a) \in {\mathcal{S}} \times \mathcal{A}} d_h^{\pi^\star}(s, a) P_{h, s, a}\sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right)}_{\eqqcolon A_{h,k}} \nonumber \\ & \leq \sum_{k=1}^K \underbrace{\left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right)}_{\eqqcolon B_{h,k}} + 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}. \label{equ:lcb-final-b} \end{align} The remainder of the proof is thus dedicated to proving \eqref{equ:lcb-final-b}. To continue, let us first consider two auxiliary sequences $\{Y_{h,k}\}_{k=1}^K$ and $\{Z_{h,k}\}_{k=1}^K$ which are the empirical estimates of $A_{h,k}$ and $B_{h,k}$, respectively. For any time step $h$ in episode $k$, $Y_{h,k}$ and $Z_{h,k}$ are defined as follows \begin{align*} Y_{h,k} &:= \frac{d_{h}^{\pi^{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \sum_{n=1}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\eta_{n}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\left(V_{h+1}^{\star}-V_{h+1}^{k^{n}(s_{h}^{k},a_{h}^{k})}\right),\nonumber \\ Z_{h,k} &:= \left(1+\frac{1}{H}\right) \frac{d_{h}^{\pi^{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \left(V_{h+1}^{\star}-V_{h+1}^{k}\right). \end{align*} To begin with, let us establish the relationship between $\{Y_{h,k}\}_{k=1}^K$ and $\{Z_{h,k}\}_{k=1}^K$: \begin{align} \sum_{k=1}^K Y_{h,k} & =\sum_{k=1}^{K}\frac{d_{h}^{\pi^{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \sum_{n=1}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\eta_{n}^{N_{h}^{k}(s_{h}^{k},a_{h}^{k})}\left(V_{h+1}^{\star}-V_{h+1}^{k^{n}(s_{h}^{k},a_{h}^{k})}\right)\nonumber\\ & \stackrel{(\mathrm{i})}{=}\sum_{l=1}^{K}\frac{d_{h}^{\pi^{\star}}(s_{h}^{l},a_{h}^{l})}{d_{h}^{\mu}(s_{h}^{l},a_{h}^{l})} P_{h,s_{h}^{l},a_{h}^{l}} \left\{ \sum_{N=N_h^{l}(s_{h}^{l},a_{h}^{l})}^{N_h^{K}(s_{h}^{l},a_{h}^{l})}\eta_{N_h^{l}(s_{h}^{l},a_{h}^{l})}^{N}\right\} \left(V_{h+1}^{\star}-V_{h+1}^{l}\right)\\ % & \leq\left(1+\frac{1}{H}\right)\sum_{k=1}^{K}\frac{d_{h}^{\pi^{\star}}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \left(V_{h+1}^{\star}-V_{h+1}^{k}\right)= \sum_{k=1}^K Z_{h,k}. \label{lcb-C-1} \end{align} Here, (i) holds by replacing $k^{n}(s_{h}^{k},a_{h}^{k})$ with $l$ and gathering all terms that involve $V_{h+1}^{\star}-V_{h+1}^{l}$; in the last line, we have invoked the property $\sum_{N=n}^{N_h^K(s,a)} \eta_n^N \leq \sum_{N=n}^{\infty} \eta_n^N = 1 + 1/H$ (see \eqref{eq:properties-learning-rates-345}) together with the fact $V_{h+1}^\star - V_{h+1}^{l}\geq 0$ (see Lemma~\ref{lem:Vk-lower}), and have further replaced $l$ with $k$. With the above relation in hand, in order to verify \eqref{equ:lcb-final-b}, we further decompose $A_h$ into several terms \begin{align} A_h &= \sum_{k=1}^K A_{h,k} = \sum_{k=1}^K Y_{h,k} + \sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right) \overset{\mathrm{(i)}}{\leq} \sum_{k=1}^K Z_{h,k} + \sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right) \nonumber \\ &= \sum_{k=1}^K B_{h,k} + \sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right) + \sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right) \label{eq:recursion-extra-error} \end{align} where (i) follows from \eqref{lcb-C-1}. As a result, it remains to control $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$ and $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$ separately in the following. \paragraph{Step 1: controlling $\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)$.} We shall first control this term by means of Lemma~\ref{lemma:martingale-union-recursion}. Specifically, consider \begin{align} W_{h+1}^{k}(s,a) \coloneqq \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(V_{h+1}^\star - V_{h+1}^{k^n(s,a)}\right), \qquad C_{\mathrm{d}} \coloneqq 1 \label{eq:Y-defn-w} \end{align} which satisfies \begin{align} \left\|W_{h+1}^{k}(s,a)\right\|_\infty \leq \sum_{n=1}^{N_h^k(s,a)} \eta_n^{N_h^k(s,a)} \left(\left\|V_{h+1}^\star\right\|_\infty + \left\|V_{h+1}^{k^n(s,a)}\right\|_\infty \right) \leq 2H \eqqcolon C_{\mathrm{w}}. \label{eq:Y-cw} \end{align} Here we use the fact that $\eta_0^{N_h^k} + \sum_{n = 1}^{N_h^k} \eta_n^{N_h^k} = 1$ (see \eqref{equ:learning rate notation} and \eqref{eq:sum-eta-n-N}). Then, applying Lemma~\ref{lemma:martingale-union-recursion} with \eqref{eq:Y-defn-w}, we have with probability at least $1-\delta$, the following inequality holds true \begin{align} \left|\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)\right| &\eqqcolon \left|\sum_{k=1}^K X_{h,k}\right| \nonumber \\ & \leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi^\star}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ &\overset{\mathrm{(i)}}{\leq} \sqrt{8C^\star\sum_{k=1}^K \left\|W_{h+1}^{k}(s,a)\right\|_\infty^2 \log\frac{2H}{\delta}} + 4HC^\star\log\frac{2H}{\delta} \nonumber \\ &\leq 8\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 4HC^\star\log\frac{2H}{\delta}, \label{eq:bound-of-Y} \end{align} where (i) holds since $\big| P_{h,s,a}W_{h+1}^{k}(s,a)\big| \leq \big\| P_{h, s,a}\big\|_1 \|W_{h+1}^{k}(s,a) \|_{\infty} =\|W_{h+1}^{k}(s,a) \|_{\infty}$. \paragraph{Step 2: controlling $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$.} Similarly, we shall control $\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)$ by invoking Lemma~\ref{lemma:martingale-union-recursion}. Recall that \begin{align} Z_{h,k} - B_{h,k} = \left(1+\frac{1}{H}\right) \frac{d_{h}^{\pi^\star}(s_{h}^{k},a_{h}^{k})}{d_{h}^{\mu}(s_{h}^{k},a_{h}^{k})} P_{h,s_{h}^{k},a_{h}^{k}} \left(V_{h+1}^{\star}-V_{h+1}^{k}\right) - \left(1+\frac{1}{H}\right) \sum_{s\in {\mathcal{S}}} d_{h+1}^{\pi^\star}(s) \left(V_{h+1}^\star(s) - V_{h+1}^{k}(s)\right), \end{align} and let us consider \begin{align} W_{h+1}^{k}(s,a) \coloneqq V_{h+1}^\star - V_{h+1}^{k}, \qquad C_{\mathrm{d}} \coloneqq \left(1+\frac{1}{H}\right)\leq 2\label{eq:Z-defn-w} \end{align} which satisfies \begin{align} \left\|W_{h+1}^{k}(s,a)\right\|_\infty \leq \left\|V_{h+1}^\star\right\|_\infty + \left\|V_{h+1}^{k}\right\|_\infty \leq 2H \eqqcolon C_{\mathrm{w}} . \end{align} Again, in view of Lemma~\ref{lemma:martingale-union-recursion}, we can show that with probability at least $1-\delta$, \begin{align} \left|\sum_{k=1}^K \left(B_{h,k} - Z_{h,k}\right)\right| &= \left|\sum_{k=1}^K X_{h,k}\right| \nonumber \\ & \leq \sqrt{\sum_{k=1}^K 8C_{\mathrm{d}}^2 C^\star \sum_{(s,a)\in{\mathcal{S}}\times\mathcal{A}} d_{h}^{\pi^\star}(s,a) \left[P_{h,s,a}W_{h+1}^{k}(s,a)\right]^2 \log\frac{2H}{\delta}} + 2C_{\mathrm{d}} C^\star C_\mathrm{w}\log\frac{2H}{\delta} \nonumber \\ &\stackrel{(\mathrm{i})}{\leq} \sqrt{32C^\star\sum_{k=1}^K \left\|W_{h+1}^{k}(s,a)\right\|_\infty^2 \log\frac{2H}{\delta}} + 8HC^\star\log\frac{2H}{\delta} \nonumber\\ &\leq 16\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 8HC^\star\log\frac{2H}{\delta}, \label{eq:bound-of-Z} \end{align} where (i) holds due to the fact $\big\| P_{h, s,a}\big\|_1=1$. \paragraph{Step 3: putting all this together.} Substitution results in \eqref{eq:bound-of-Y} and \eqref{eq:bound-of-Z} back into \eqref{eq:recursion-extra-error} completes the proof of \eqref{equ:lcb-final-b} as follows \begin{align*} A_h &\leq \sum_{k=1}^K B_{h,k} + \bigg|\sum_{k=1}^K \left(Z_{h,k} - B_{h,k}\right)\bigg| + \bigg|\sum_{k=1}^K \left(A_{h,k} - Y_{h,k}\right)\bigg| \\ &\leq \sum_{k=1}^K B_{h,k} + 24\sqrt{H^2C^\star K \log\frac{2H}{\delta}} + 12HC^\star\log\frac{2H}{\delta}. \end{align*} This in turn concludes the proof of Lemma \ref{lemma:recursion}.
{'timestamp': '2022-03-01T02:52:36', 'yymm': '2202', 'arxiv_id': '2202.13890', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13890'}
arxiv
\section{StyleGAN Architectures} \label{sec:architecture} This report addresses the benefits hidden in Generative Adversarial Networks (GANs). First introduced by Goodfellow~{{et al}. }~\shortcite{Goodfellow2014GenerativeAN}, GANs pose an interesting and unique approach. Two networks are interlocked in a perpetual game during training. One network, the Generator, seeks to generate images that are from the target distribution, while the other network, the Discriminator, seeks to distinguish between actual images from the training set and those created by the generator. The two networks start the training without any knowledge of the domain and spend the entire training process learning from each other. Conceptually, this could be thought of as a repetitive process where the generator finds a way to fool the discriminator, and the discriminator, in turn, finds a way to detect this "attack". This approach allows self-supervision, and hence these networks can be trained without explicit labeling. StyleGAN, however, seems to do much more than reproduce samples from the target distribution. While following the adversarial learning process, it turns out that StyleGAN, more than other GANs, constructs a remarkably well-behaved latent space. Without any supervision, StyleGAN arranges examples it sees in a smooth, highly disentangled order, driven by powerful semantic understanding. In this Section, we portray how StyleGAN's architecture is built, try to understand why this architecture induces such cutting-edge emerging disentanglement, and how the architecture can be improved to match specific needs, according to relevant literature. \paragraph*{StyleGAN1} The style-based generator architecture for generative adversarial networks, or StyleGAN for short, was first proposed by Karras~{{et al}. }~\shortcite{karras2019style}. At the core of StyleGAN's architecture lie the style modulation layers, from which StyleGAN draws its name. Borrowing from style-transfer literature, these layers are designed to enable control over the ``style" of generated images by adjusting the statistics of the feature maps along the generative path. The generative path starts from a learned constant $C$, representing the epicenter of the distribution, and all the information and generative power of the network is injected through the style and an additional random noise vector $n$. In the first version of the architecture, \cite{karras2019style}, the style injection layers utilized the Adaptive Instance Normalization (AdaIN) mechanism~\cite{huang2017arbitrary}; each channel of the feature maps is first normalized to zero mean and unit variance, followed by re-scaling using new means and variances predicted from a given latent code. However, the use of AdaIN layers was not the only major change proposed. Rather than injecting the network with a latent code $z$ sampled directly from some Gaussian prior $\mathcal{Z}$, StyleGAN introduces a novel mapping network which converts these \input{Figures/architectures/mapping_network} normal-distributed codes into vectors in an intermediate latent space $\mathcal{W}$. The authors propose an intuitive argument for adding such a network: the probability for sampling a particular combination of image attributes in the latent space should eventually match the probability for that combination to appear in the real dataset. For those cases where the data is not uniform with respect to these attributes, it follows that the mapping from $\mathcal{Z}$ to the image features must become curved in order to diminish the incidence rate of rare attribute combinations. A learned mapping network, however, could learn to ``unwrap" the latent space back to a flat form, and simply account for probability densities by mapping fewer codes to regions that would otherwise portray a rare combination of attributes (see inset figure, from Karras~{{et al}. }~\shortcite{karras2019style}). Karras~{{et al}. } postulate that this linearly-disentangled space is a more natural representation for the network, allowing it to more easily recreate a wide range of variations. As Karras~{{et al}. } and follow-up works demonstrate, the learned latent spaces of StyleGAN offer considerable disentanglement. These innovations give rise to a network that, at the time, was unrivaled in quality, invertibility, and support for a wide range of generative and discriminative tasks. \input{Figures/architectures/sg1_arch} \paragraph*{StyleGAN2} With StyleGAN being quickly adopted into widespread use, it was inevitable that artifacts inherent to the model would come to light. These included characteristic water-droplet-shaped blobs which consistently appeared in all images. Additionally, a ``texture-sticking" effect was observed, where certain attributes of the generated image, such as the teeth or eyes, would display strong spatial bias, remaining fixed to specific image coordinates even through latent space interpolations. In a follow-up work, Karras {{et al}. } \shortcite{karras2019analyzing} identify the source of these artifacts, and re-design key aspects of the network to correct them. They first identify that the water-droplets are a manifestation of a flaw in StyleGAN's normalization scheme - by normalizing each feature map separately, any information found in their relative magnitudes is destroyed. The generator would then hide information about the signal strength through localized spikes that dominate the statistics. They overcome this hurdle by shifting normalization from the feature maps, where the adaptive layer normalization forces new statistics, and onto a modulation of the convolutional kernels themselves. By doing so, they apply weaker normalization, based on the expected feature statistics rather than exact signal strength, and the network no longer needs to hide signal strength information - which in turn makes the blob-shaped artifacts disappear. This technique has also been shown to promote disentanglement between geometry and appearance in other scenarios~\cite{yang2020iorthopredictor}. The ``texture sticking" effect, meanwhile, was hypothesized to be an artifact of the progressive growth scheme. Karras {{et al}. } suggest that in such a setup, every resolution block serves as an output block for some stage of the training process. In such a scenario, the network attempts to create excessive high-frequency detail in these intermediate resolutions, which leads to aliasing along the generative path and in turn breaks shift-invariance \cite{zhang2019making}. They address this issue by revisiting progressive growing and replacing it with a skip-connection-based architecture, where each resolution block outputs a residual, which is summed up and up-scaled. These modifications, coupled with a novel path-length regularization loss and in-depth analysis of network capacity, lead to improvements both in standard quality metrics such as FID, but also in the ability to invert images into the latent space of the GAN. \input{Figures/architectures/texture_sticking} \paragraph*{StyleGAN3} At first, StyleGAN2 appeared to address the ``texture-sticking" problem. However, more careful analysis revealed that, while the issue was resolved for large-scale objects such as the mouth or the eyes, it remained present when examining finer details such as hair or beards. To resolve this issue, Karras {{et al}. } sought out the various sources through which spatial information could leak into the convolutional operations, with the aim of fully restoring translational invariance to the network. These sources include the image borders, per-pixel noise inputs, positional encoding, and the aliasing caused by careless treatment of upsampling filters and non-linearities such as ReLUs. Through a series of small architectural changes coupled with a rigorous signal processing approach, these sources of unwanted information were removed, and translation and rotational equivariance was restored. The novel architecture of StyleGAN3~\cite{karras2021alias} brought with it remarkable improvements, leading to considerably smoother interpolations. However, the new approach brought with it new challenges. Karras {{et al}. } observe that when conducting layer mixing experiments, some properties were not cleanly inherited from just one of the codes. Preliminary investigations of the network also revealed newly introduced artifacts, from the tendency of generated faces to have a single frontal tooth, to the appearance of a faint ``grid" to which background features and fine details such as hair would often get stuck. These phenomena suggest degraded disentangled properties, however, as of writing these words, the novel alias-free architecture is still in its infancy, and it remains to be seen what unique uses, improvements or challenges arise from it. Parallel to these improvements, various works sought to identify areas in which StyleGAN could be improved. Lin {{et al}. }~\shortcite{lin2021anycost} note that the high computational cost of full-resolution image generation makes it impractical to utilize the network for interactive editing on edge devices. They proposed an elastic generator architecture that could produce previews at lower resolutions while retaining the same latent semantics. A user could then edit these previews with a fraction of the computational budget, restoring the output to its full resolution only as a final step. \cite{swagan2021gal} followed prior observations which revealed a flaw in the generator's ability to produce high-frequency details. They demonstrated that some patterns are beyond the network's ability to recreate and linked the flaw to the inherent spectral bias of neural networks. They proposed to tackle this by shifting the generation to the frequency domain, realized by a first-level wavelet decomposition. By doing so, they reduced the network's need to learn high-frequency functions and achieved a more faithful generation of high-frequency patterns. \input{Figures/architectures/sg3_arch} In an alternative approach to synthesis, Anokhin {{et al}. }~\shortcite{anokhin2020image} forgo convolutions and instead design a style-based network which, given the coordinates of a pixel and a style code, predicts the color of that pixel. This conditionally-independent pixel synthesis approach (CIPS) was able to rival the quality of images produced by traditional convolutional methods while enabling novel synthesis applications such as the creation of cylindrical panoramas. Sendik {{et al}. }~\shortcite{sendik2020unsupervised} hypothesize that the single learned constant at the root of the generative path is a limiting factor when training on sets that contain multiple modalities. They hence develop a multi-constant model, where the generator could better represent the dataset modalities by assigning them different mixtures of constants. Kwon {{et al}. }~\shortcite{kwon2021diagonal} propose augmenting the network with Diagonal Spatial Attention (DAT) layers, which modulate the network's feature maps along the spatial directions. These modulations are in turn controlled through an additional latent code. Through this addition and an appropriate loss term, the authors disentangle ``content" from ``style", allowing a user to control spatial features such as pose or expression, without affecting style traits such as color or makeup. Casanova {{et al}. }~\shortcite{casanova2021instanceconditioned} suggest training a GAN conditioned on a single input. Their intuition is that unconditional GANs face difficulties in reproducing complex distributions \cite{luvcic2019high,liu2020diverse} such as ImageNet \cite{russakovsky2015imagenet}. Typical conditional models seek to resolve this challenge \cite{brock2018large} by conditioning the synthesis process on class labels, thereby partitioning the data into multiple clusters which are more easily modeled. However, acquiring such labels is labor intensive. Instead, they suggest partitioning the data into overlapping neighborhoods by clustering the data in some pre-trained feature space. The ``label" associated with an image is then the feature vector in this space, and real images observed by the discriminator when conditioned on such a vector are sampled from the group of images with representations most similar to the given vector. In this way, the network learns to generate images sharing visual and semantic traits with a given sample. While not strictly extensions of StyleGAN itself, a large body of work nevertheless draws inspiration from its novel architecture. These works typically repurpose the style-based modulation layers or mapping network and incorporate them into new generative frameworks. One line of work aims to merge the growing Transformer~\cite{vaswani2017attention} literature with image synthesis. Hudson {{et al}. }~\shortcite{hudson2021generative} proposed the Generative Adversarial Transformer, which utilizes a bipartite mechanism through which the latent codes and image features attend and influence each other. Others have proposed to entirely replace the convolutional blocks with transformer-based modules such as ViT~\cite{lee2021vitgan,dosovitskiy2020image}, Linformer~\cite{park2021styleformer,wang2020linformer}, or the Swin Transformer~\cite{liu2021swin,zhang2021styleswin}. While these have yet to achieve the same fidelity or widespread use as their progenitor, they have already shown considerable progress in layout control and convergence times. Moving towards 3D representations, a set of recent works propose to marry the style-based architecture with implicit models, such as Signed Distance Functions~\cite{park2019deepsdf} or Neural Radiance Fields~\cite{mildenhall2020nerf}. These models leverage weight and feature modulations~\cite{gu2021stylenerf,orel2021stylesdf,zhou2021cips,xu2021volumegan} or directly employ a StyleGAN network to predict a set of feature planes that serve as inputs to a small implicit network~\cite{Chan2021eg3d}. These works achieve impressive visual quality, enable explicit control over pose, and can be used to predict detailed surface representations. However, their increased memory requirements have so far prevented them from reaching the resolution and quality of StyleGAN itself. \paragraph*{Training Data} "An open secret in contemporary machine learning is that many models work beautifully on standard benchmarks but fail to generalize outside the lab"~\cite{jahanian2019steerability}. Indeed, StyleGAN is no different. It is recognized in the literature that unsupervised training is more difficult when learning a complex domain~\cite{casanova2021instanceconditioned}. In the case of StyleGAN, the learned domain seems to require strict structure. The data domain should be almost convex, i.e., between every two points there should be valid samples that interpolate them on the data manifold. For this reason, for example, it is difficult to construct a full human body model. For the same reasons, StyleGAN does not handle multi-modal distributions well and behaves poorly for scenes where objects do not have specific potential locations. In recent work, Sauer~{{et al}. }~\shortcite{sauer2022styleganxl} demonstrate that some of these challenges may be overcome through careful model scaling, though whether or not StyleGAN's unique latent-space properties persist through this modification remains an open question. In the future, we will likely witness additional works that address explicit data issues, i.e., works that try to apply StyleGAN to other types of data, perhaps by dropping or adding examples during training to make the data's landscape more smooth, by transfer learning between datasets (see Section~\ref{sec:fine-tuning}), by more directly addressing multi-modalities in the data, or by incorporating more elaborate attention mechanisms into the architecture. \section{Conclusions} \label{sec:conc} StyleGAN has revolutionized the field of image synthesis, bringing with it consistent, high-quality results with exceptional photo-realism across multiple domains. More interestingly, through a combination of layer-wise style modulations and a novel mapping network, StyleGAN is capable of mapping out a smooth, semantic, and highly-disentangled latent space in an entirely unsupervised manner. This enables latent-based editing, yielding effects such as photo-realistic and plausible alterations to age, hairstyles, or body poses, and even transformations into celebrities or magical beings. However, StyleGAN struggles with domains that do not exhibit strong structure. An in-depth look over the diverse set of works covered by this report will reveal that they all demonstrate their abilities on a rather limited collection of domains, and with no regard to the temporal axis. To address these limitations, there is yet much development that the generative field must undergo. While many works focused on re-using a pre-trained generator for downstream tasks, a recent trend has shown that some of these domain-related limitations can be overcome if one adapts the generator to their specific needs. In essence, such approaches build upon the extensive knowledge that StyleGAN can glean from a rich source domain, and transfer it to new realms such as 3D rendering, paintings, or wildlife. Another noteworthy direction resides in extracting knowledge from StyleGAN for non-generative needs. StyleGAN has already been leveraged for regression, segmentation, and explainability, but there is doubtless more that could be learned from exploring its structured latent space. On the quest to self-supervision and learning representations that naturally disentangle and understand the elements comprising data distributions, StyleGAN is an important milestone. \bibliographystyle{ACM-Reference-Format} \section{Discriminative Applications} \label{sec:discriminative} While the generative capabilities of GANs, and StyleGAN in particular, are indeed groundbreaking, one may ask what \textit{non-generative} tasks can potentially be tackled using GANs. In its most basic form, the GAN's capability to generate a large number of images, all essentially re-sampled from the same target distribution, can be used for data enrichment and augmentations for downstream training tasks. Indeed, many early works proposed using a GAN as an augmentation tool to generate more training data \cite{antoniou2017data,zhu2018emotion,tanaka2019data}, possibly also through the use of latent-space editing \cite{hochberg2021style}. Leveraging the GAN's editing capabilities, Chai {{et al}. }~\shortcite{chai2021ensembling} propose an ensembling method for image classification, by augmenting the input image at test-time. The input is projected into the pre-trained generator's latent space, and editing operations such as style mixing are applied to it, generating different views. The generated images are then fed into a classification network, and the final prediction of the model is based on an ensemble of the network predictions on all of the images. Unlike conventional ensembles in deep learning, where predictions of several models are combined to yield the final result, this method proposes using different views of the same image (while preserving its identity) and ensemble the classifier predictions on the images at test-time. \input{Figures/discriminative} Aiming to leverage the semantic understanding of StyleGAN in new ways, Peebles~{{et al}. }~\shortcite{peebles2021gansupervised} present a novel framework to approach the task of dense visual alignment. Using sampled latent codes and their corresponding images, the authors jointly learn a latent representation used for latent-space editing, and a Spatial Transformer Network to align the generated images according to the edit, as illustrated in Figure~\ref{fig:discriminative_applications}c. Once both manipulations converge to a single viewpoint, the authors can employ the STN to align real images. Abdal {{et al}. }~\shortcite{abdal2021labels4free} present an unsupervised segmentation method based on a pre-trained GAN. The authors recognize that nullifying some of the activations actually causes the GAN to erase the foreground object, producing an image with only a background. Hence, they form two networks, one that generates only the background for an image, and another which generates only the foreground, naturally leveraging the GAN's internal semantic understanding. They then use the two networks to train a segmentation mask generation network in an unsupervised manner. This notion, of extracting a segmentation map with the help of StyleGAN's structure, has been employed similarly by others \cite{zhang2021datasetgan,li2021semantic,ling2021editgan,Lewis2021TryOnGANBT}. However, StyleGAN's well-behaved latent space offers more opportunities. In a fine example of taking full leverage of the latent space, Xu~{{et al}. }~\shortcite{xu2021generative} show how to exploit pre-trained generative models for a wide variety of analysis and generation tasks. In essence, they propose an adversarial feature learning technique~\cite{donahue2016adversarial}; they extract meaningful feature maps through StyleGAN inversion and use them for a wide variety of tasks. The authors show that the channel-level modulations performed by a style code can be used as descriptive features for downstream tasks. Hence, by simply training an encoder, high-quality feature vectors can be produced in an unsupervised manner. The authors evaluate the quality of the features on different generative and discriminate downstream tasks, including image editing, image recognition, landmark detection, and more (see Figure~\ref{fig:discriminative_applications}b). Nitzan {{et al}. }~\shortcite{nitzan2021large} further observe that the linear nature of semantic directions in StyleGAN's latent space, \emph{i.e}.} \def\Ie{\emph{I.e}. the same linearity exploited by the editing literature (see Section~\ref{sec:editing}), can be leveraged as a tool for few-shot regression. Their basic premise is that if the space is indeed linear, then given two labeled points along a disentangled axis, any interpolated point between them should produce an interpolation of their labels as well. In other words, they show that linear editing directions are not only global, in the sense that they cause a similar effect for all inputs, but also that the magnitude of these effects is linear in the size of the traversal step. Through this realization, they achieve state-of-the-art few-shot regression performance on various properties, such as yaw angle and age estimation for human faces. Continuing this line of thought, several papers leverage StyleGAN's intermediate representation to perform semantic segmentation. As previously discussed (see Section \ref{sec:endcoding}), a simple function, $f$, may be learned between the up-sampled concatenated per-layer features and a semantic segmentation of the image. As illustrated in Figure~\ref{fig:discriminative_applications}a, Zhang~{{et al}. }~\shortcite{zhang2021datasetgan} propose to use StyleGAN together with $f$ to generate a virtually infinite paired synthetic training set for semantic segmentation. Alternatively, Tritong~{{et al}. }~\shortcite{tritrong2021repurposing} directly use StyleGAN and $f$ for segmentation by first inverting a real image into latent space. In the context of local editing, Collins~{{et al}. }~\shortcite{collins2020editing} and Kafri~{{et al}. }~\shortcite{kafri2021stylefusion} perform a simple clustering procedure over StyleGAN's internal representations to obtain a semantic segmentation of an input image. This semantic map can then be used to perform local editing over an image, guided by a target reference image. Lang~{{et al}. }~\shortcite{lang2021explaining} propose to not only exploit the emerging disentanglement properties of a pretrained StyleGAN, but to train a StyleGAN model for a specific disentangled axis. Through a clever training scheme, combining training StyleGAN along with a classifier for binary or multi-class recognition (e.g., a cat vs. dog classifier), they drive the latent space to capture classifier-specific attributes. As they demonstrate, through this joint training process, the linear editing directions that emerge from this model correspond to specific properties that the classifier searches for. For example, in the cat vs. dog case, the emerging editing directions include the shape of the eye, and the pointedness of the ears. This means that the image can be augmented to be more or less suitable for a specific label (e.g., a cat could be turned to be more dog-like), thus providing explainable examples of how the classifier makes its decision. As can be seen, StyleGAN's unsupervised arrangement of its latent space in disentangled directions is an exciting property that could potentially be leveraged for various applications. In the near future, it is likely that more works along these directions would be introduced, maybe establishing GANs as a method useful for many downstream tasks in machine learning in general, reaching beyond data augmentation or entertainment. Furthermore, it stands to reason that future generations of GANs may be designed with more consideration to discriminative tasks. \section{Latent Space Editing} \label{sec:editing} Perhaps the most exciting aspect of GAN learning is the way the latent space is arranged in a well-trained GAN. Traditionally, GANs in general, and StyleGAN specifically, can be used to simply generate a wide variety of images of the same kind. These can serve as a form of data augmentation for downstream training (see Section~\ref{sec:discriminative}). However, it has been shown that GANs tend to arrange their latent space smoothly, \emph{i.e}.} \def\Ie{\emph{I.e}.{} such that close regions in the latent space depict similar images. This, combined with the notion that GANs produce images that are within the distribution of the target domain gives rise to \textit{latent-based editing}. In other words, the two concepts suggest that traversing the latent space yields a path of smoothly changing images, each of them on their own belonging to the target domain (\emph{e.g}.} \def\Eg{\emph{E.g}.{} realistic human faces). This could be thought of as geodesic traversal on the manifold of all valid images. Even the first works in generative modeling already demonstrated how latent code interpolation between two examples yields a natural morphing between them \cite{Goodfellow2014GenerativeAN}. As it turns out, careful traversal in the latent space can also produce desirable semantic changes in the resulting image that would otherwise be very difficult to perform. These include changes in viewpoint, lighting conditions, and domain-specific attributes such as expressions for faces, colors for cars, or widths of buildings. Of course, the most desirable edits are the disentangled ones --- those that change one attribute without affecting any other. Applications of such powerful editing tools are endless, from automatically adding smiles to facial images, through interior design explorations, to rapid car design. In this aspect, StyleGAN shines. As previously discussed (Section~\ref{sec:architecture}), StyleGAN operates best on well-structured data. When trained on such data, StyleGAN constructs a highly disentangled latent space in an unsupervised manner, simply by virtue of inductive bias. Many techniques have been proposed to traverse this latent space and facilitate semantically disentangled latent-based editing. Of all sections in this report, the editing art is the most diverse, presenting creative approaches borrowed from different fields. Early approaches to this task pointed out that StyleGAN's latent space is so well behaved and disentangled, that it even supports linear latent space arithmetics. These linear editing works demonstrate, for example, that to make a face older, one can traverse in a specific, pre-computed, direction. These works come in two main flavors --- supervised and unsupervised. The first works in the field have presented a thorough analysis of GAN behavior \cite{jahanian2019steerability,liu2020style} (including StyleGAN), and showed how one can identify linear traversal directions that present high disentangled qualities. Using edits that are easily attainable in image space (e.g. 2D rotation or zoom, and pan), they look for directions in the $\mathcal{W}$ space (Section~\ref{sec:spaces}) that produce the same effect. Changing the magnitude of traversal along these directions induces a disentangled edit that is weaker or stronger according to the step size. This early work also drew conclusions regarding the extent of the space's linearization. That is, they show that going too far along a direction will eventually break the disentanglement, and affect other crucial factors of the image. They also offer an analysis on, and a way to improve, the extent of the linearization. \vspace{-0.2cm} \paragraph*{Supervised Linear Approaches} The most natural approach to finding editing directions is to do so explicitly, through full supervision. Perhaps one of the most noteworthy works in linear editing is InterFaceGAN~\cite{shen2019interpreting,shen2020interfacegan}. % This work leverages per-image binary annotations to identify hyper-planes in the latent space that separate the two binary attribute values. These planes can be found using Support Vector Machines (SVMs). Then, to edit one attribute without affecting others, one finds a direction that is orthogonal to one plane and parallel to the others. Figure~\ref{fig:edits}a depicts some of the typical editing directions extracted by this method. Yang~{{et al}. }~\shortcite{yang2020semantic} further propose a way to evaluate how well the activations of specific layers are correlated with semantic attributes, based on 105 pretrained attribute classifiers. Recently, Wu~{{et al}. }~\shortcite{wu2020stylespace} employ a pretrained classifier, or use a few images for direction identification. Their key idea is to identify correspondence between the most active channels and the semantics corresponding generated images depict (termed \textit{semantic consistency}). The authors show that this correspondence indicates specific channels in the generator's activations that control very disentangled image characteristics. This offers a fine-grained approach to latent editing that is different from the popular latent-editing approaches which modify all activations of a layer (or more). Editing in $\mathcal{S}$ space (see Section~\ref{sec:spaces}) is shown to provide highly disentangled, spatially adaptive directions for editing. \paragraph*{Unsupervised Linear Approaches} In many cases, collecting the data required for supervised editing can be difficult or prohibitively expensive. To expand the range of available editing directions, despite these limitations, unsupervised editing methods have been proposed. Perhaps the first was proposed by Voynov {{et al}. }~\shortcite{voynov2020unsupervised}. The core idea is to predict a set of traversal directions and concurrently try to infer their meaning from the images corresponding to the code before and after the edit. They propose to jointly learn a set of directions and a model to identify the corresponding image transformations. Under this paradigm, the assumption is that directions that are easy to identify with high accuracy are likely candidates for disentangled editing directions. GANSpace \cite{harkonen2020ganspace}, take a more natural approach, and simply search for the dominant directions in the latent codes of a dataset, using Principal Component Analysis (PCA). Alharbi~{{et al}. }~\shortcite{Alharbi_2020_CVPR} propose editing through adding random noise to the input learned constant, rather than augmenting the style input. They show that by enforcing a spatial structure to the noise, spatial disentanglement can be encouraged, and can be paired with the semantic disentanglement StyleGAN already offers. In all three cases, manual inspection is used to identify whether these directions indeed produce valuable edits, and infer their semantic meaning. SeFa~\cite{shen2020closedform} takes a different approach to the unsupervised editing problem. They propose analyzing the weights of the pretrained generator and identifying principle directions that are most affected by these weights. To do so, they perform an eigenanalysis of the matrix representing the latent-to-image space projection. This analysis is closed-form, meaning it is fast and does not require even sampling the network. This approach is still valuable and has been used for other domains and GAN architectures as well ~\cite{spingarn2020gan}. \paragraph*{Non-linear Approaches} As may be expected, non-linear approaches can present higher quality editing at the cost of simplicity. Hou~{{et al}. }~\shortcite{hou2020guidedstyle}, operate similarly to Yang {{et al}. }~\shortcite{yang2020semantic} by using classifiers. However, they propose to move beyond global, linear directions and towards a non-linear traversal paradigm. In their case, a different direction is generated per example for the same editing operation. The editing is then performed by changing the latent code of only one layer at a time, in a style-mixing manner (see Section~\ref{sec:architecture}), thereby improving disentanglement. StyleFlow~\cite{abdal2020styleflow} is a seminal work in the realm of facial editing, presenting one of the most versatile and stable editing approaches, disentangled enough to produce a realistic result even when performing several editing operations serially, as can be seen in Figure~\ref{fig:edits}b. The core idea for this work is the clever employment of normalizing flows --- a method through which a bi-directional mapping can be obtained between the latent space and an input code, conditioned on specific attributes. This mapping is trained in a supervised manner through an elaborate multi-attribute classifier. This promising normalizing flow-based approach has also seen follow-up work in an unsupervised setting~\cite{liang2021ssflow}. Alaluf {{et al}. }~\shortcite{alaluf2021matter} use an age regression network to provide control over age in human faces. Looking towards more recent works along this line~\cite{wang2021hijack}, perhaps the state-of-the-art lies with DyStyle~\cite{li2021dystyle}. The main contribution of this supervised approach is a dynamic network, trained to handle multiple edits at the same time. Here, a different network is trained for each attribute, producing its own latent editing direction. For every training example, consisting of a different composition of desired edits, only the relevant networks are applied, with their outputted codes fused into one using a self-attention mechanism. This approach enables high-quality editing in flexible domains, especially when composing several edits together. The combined dynamic approach seems not only to improve sequential editing, but also provide enough regularization to improve the state-of-the-art for a single edit as well (see Figure~\ref{fig:edits}c). Aiming for video editing, Yao {{et al}. }~\shortcite{yao2021latent} train a dedicated latent-code transformer to achieve more disentangled edits. \paragraph*{Different Supervision Modalities} Other approaches have been proposed that leverage supervision, but differ in nature from explicit attribute supervision or classification-based techniques. StyleRig~\cite{tewari2020stylerig} suggests employing synthetic data to guide the editing process. They acquire a roughly 200-parameter 3D Morphable Face Model (3DMM) using traditional PCA over 200 input faces. This model can be used in a self-supervised manner to train a network to perform the editing over $\mathcal{W}$\xspace{}. Through a plethora of synthetically generated paired examples, the method finds high-quality edits. This is because perfect labeling can be assigned to images that are rendered by specific parameter changes in the 3DMM model. This approach, however, was only able to find high-quality editing directions for a subset of the face model parameters. Perhaps unsurprisingly, the successfully found directions do not enable more diverse edits compared to less supervised methods. A similar approach has also been proposed~\cite{zhang2020image}, using general meshes instead of 3DMM, for more diverse objects. Through differentiable rendering, parameters like camera position and object shape can be self-supervised easily. Taking this line of work a step further, Ghosh~{{et al}. }~\shortcite{ghosh2020gif} propose generating the parameters of a 3D facial model learned from 4D scans. In this paradigm, the geometry is constructed through a learned 3D model (FLAME~\cite{li2017learning}), and StyleGAN generates appearance and texture. Combining the two models offers more expressive facial variations in shape and expression, and an inherent disentanglement between geometry and appearance. FreeStyleGAN~\cite{leimkuhler2021freestylegan} use standard calibration tools to construct pairs of facial images and associated camera parameters. These pairs are used to learn explicit control over image views within the GAN's aligned image manifold. Taking this approach a step further, the authors use a flow-based model to learn an image mapping module that can transform the generated images beyond StyleGAN's aligned domain. HistoGAN~\cite{afifi2021histogan} employs color histograms to recolor images and paintings. Several works employ the power of language. They guide edits by using textual descriptions, which are more global and abstract in nature. Patashnik~{{et al}. }~\shortcite{patashnik2021styleclip}, one of the first works to propose this approach, employs CLIP~\cite{radford2021learning}, a powerful pre-trained model that embeds text and imagery to a joint latent space. By finding traversal directions that bring the produced image and the desired text description closer together, this method demonstrated new and exciting semantic editing operations, such as makeup removal and specific hairstyles for human faces (see Figure~\ref{fig:edits}e). TediGAN~\cite{xia2021tedigan} employ a novel architecture and training process for the language model to be trained along with the generator. While potentially powerful, the resulting networks are not as expressive as language models pre-trained on web-scale data. Hence, they fail to achieve the same quality. Chefer {{et al}. }~\shortcite{chefer2021image} utilize CLIP to blend two facial images, demonstrating better preservation of the original identity while successfully transferring meaningful semantic features from the desired target images. Abdal~{{et al}. }~\shortcite{abdal2021clip2stylegan} find meaningful directions in CLIP-space in an unsupervised manner, map them to latent-space directions, and use CLIP to automatically generate natural language descriptions for these directions. \paragraph*{Finer Control} Several of the latest works propose operating in a more disentangled latent space --- the $S$ space~ \cite{wu2020stylespace,liu2020style,xu2021generative} (see Section~\ref{sec:spaces}). However, it is significantly larger, posing a computational challenge. Furthermore, augmenting the generator activations themselves after the AdaIN (StyleGAN~\cite{karras2019style}) or Modulation (StyleGAN2~\cite{karras2019analyzing}) layers, provides even finer control. This allows applying local changes in the image maps, rather than a global change. For example, Bau~{{et al}. }~\shortcite{bau2021paint} offers users the ability to paint a mask in a given image and to describe in free text what this region of the image should depict. They do this by feeding the same modulation layer different style codes, according to the spatial location in the resulting map: one code for regions inside the painted mask, and one for the rest. Albahar {{et al}. }~\shortcite{albahar2021pose} suggest spatial control through the initial input constant, while leveraging the inherent semantic understanding StyleGAN naturally develops, reinforced by human pose labeling. Unlike most editing works, which manipulate the behavior of a pretrained StyleGAN, this work proposes architectural changes to the generator, to adapt it to human pose inputs. Through full supervision~\cite{cao2019openpose}, they train StyleGAN to change the pose of human clothing models. Through pose labeling and paired UV coordinates, the clothes are warped in UV space to better match the new pose (see Figure~\ref{fig:edits}c). Similarly, Abdal {{et al}. }~\shortcite{abdal2020image2styleganpp} change the spatial activations to allow scribble-level control for the user (see Section~\ref{sec:encoding} for more details). StyleFusion~\cite{kafri2021stylefusion} propose a new mapping architecture for StyleGAN to better disentangle a target attribute. This results in a learned blending between style codes, resulting in fine-grained local control of the edited images. They also introduce an additional latent code for controlling global aspects of the images (\emph{e.g}.} \def\Eg{\emph{E.g}.{} pose, lighting, background). Finally, StyleMapGAN~\cite{kim2021stylemapgan} suggest an architectural change where the global $\mathcal{W}$\xspace{} latent code is replaced with a spatial map, and the global style infusion layer (\emph{i.e}.} \def\Ie{\emph{I.e}.{} AdaIN or weight modulation) is replaced with a spatially adaptive one. This allows blending two images very naturally, with a high level of detail and finer local control (See Figure~\ref{fig:edits}f). \begin{figure}[!t] \centering \includegraphics[width=\columnwidth,keepaspectratio]{Figures/styleGANEdits.pdf} \caption{Examples of prominent editing works. (a) InterfaceGAN~\cite{shen2020interfacegan} extracts linear editing directions through attribute level supervision. (b) StyleFlow~\cite{abdal2020styleflow} is the first to present editing that is stable enough to be composed, through employing normalizing flows and attribute-level supervision. (c) DyStyle~\cite{li2021dystyle} addresses compositional editing directly, producing more accurate, elborate, and diverse editing. (d) StyleCLIP~\cite{patashnik2021styleclip} employs free textual editing, through a visual-linguistic pretrained model \cite{radford2021learning}. (e) Pose with Style~\cite{albahar2021pose} employs human pose supervision to edit body poses and clothing. (f) StyleMapGAN~\cite{kim2021stylemapgan} provides localized editing by augmenting StyleGAN's architecture with spatially adaptive modulation. Zoomed-in viewing recommended. } \label{fig:edits} \vspace{-2pt} \end{figure} Studying the wide and versatile editing works, it is clear that latent-based editing holds great potential and sparks the curiosity of many. Some of the most recent works present unprecedented quality, showcasing the expressive powers of GANs in general and of StyleGAN in particular. However, all of these works still operate in lab conditions. They present a handful of novel editing operations. These, however, are still restricted (\emph{e.g}.} \def\Eg{\emph{E.g}.{} only specific expressions can be altered and the degree of possible changes in pose is limited). These restrictions pose practical challenges when employing StyleGAN for industrial or in-the-wild use. Furthermore, they bear the burden of the generator's limited capabilities regarding the versatility and structure of the training data (see Section~\ref{sec:architecture}). In the future, we will probably witness more works that adapt to new data on the fly, possibly using techniques such as fine-tuning (Section~\ref{sec:fine-tuning}), or layer mixing, where several different models are trained, and their layers are mixed according to specific applications \cite{pinkney2020resolution,park2020swapping}. In any case, it seems that a core challenge editing works face is the evaluation of their quality, as discussed in Section~\ref{sec:metrics}. \section{Encoding and Inversion} \label{sec:encoding} The success of the aforementioned latent space editing techniques results in a natural question of how to apply such techniques to edit real images (i.e., images not necessarily residing within the GAN's domain). To do so, we need to find the latent representation of a given image, a task commonly referred to as \textit{GAN Inversion}. First introduced by Zhu~{{et al}. }~\shortcite{zhu2016generative}, the inversion task aims to find a latent vector from which a pre-trained GAN can most accurately reconstruct the given image. Formally, given an input image $x$, we want to minimize the distortion of the reconstructed image obtained from the inverted latent code $w$ using a well-trained generator $G$: \begin{align}~\label{eq:opt} w^* = \underset{w}{\arg\min} \mathcal{L} \left ( {x, G(w)} \right ), \end{align} where $\mathcal{L}$ is some reconstruction loss (e.g., the LPIPS perceptual loss~\cite{zhang2018unreasonable} and/or the pixel-wise L2 loss). In the following, we explore the various core approaches for performing this inversion process, outlined in Figure~\ref{fig:inversion_schemes}. \subsection{GAN Inversion}~\label{sec:inversion} Existing optimization-based GAN inversion methods search for the desired latent vector via a per-image latent vector optimization by solving Equation~\ref{eq:opt}~\cite{lipton2017precise,creswell2018inverting,abdal2019image2stylegan,abdal2020image2styleganpp,semantic2019bau,zhu2020improved,zhu2016generative,yeh2017semantic,gu2020image,wulff2020improving}. Early works performing optimization attempted to invert into StyleGAN's learned latent space $\mathcal{W}$. However, it has been shown that inverting a real image into a $512$-dimensional vector $w\in \mathcal{W}$ is not expressive enough to accurately encode and reconstruct real images. As such, it has become common practice to invert images into an extended latent space $\mathcal{W}+$~\cite{abdal2020image2styleganpp} defined by a concatenation of multiple $w$ vectors, one for each input of StyleGAN. While optimization techniques often result in near-perfect reconstructions of the input, they typically require several minutes to do so for a single image. To accelerate this optimization process, some works trained an encoder over a large collection of images to learn a direct mapping from an image to its latent representation~\cite{perarnau2016invertible,luo2017learning}. Here, the training objective can be defined by, \begin{align} \theta_E^* = \underset{\theta_{E}}{\arg\min} \sum_{i} \mathcal{L} ( \textbf{x}_i, G( E_{\theta_E}(\textbf{x}_i) ) ), \end{align} where the weights $\theta_E^*$ of the encoder are sought. Pidhorskyi~{{et al}. }~\shortcite{pidhorskyi2020adversarial} propose a StyleGAN-based autoencoder, where the encoder network $E$ is trained alongside the generator. \input{Figures/inversion_schemes} Many works have explored various avenues for improving the performance of encoder-based inversion methods in an attempt to close the gap in performance with optimization techniques. Some have explored various encoder architectures for improving the inversion quality. Richardson~{{et al}. }~\shortcite{richardson2020encoding} and Xu~{{et al}. }~\shortcite{xu2021generative} explore a hierarchical encoder based on a feature pyramid network (FPN) to better match the coarse, medium, and fine-level details of StyleGAN's hierarchical structure. For extracting the learned styles from the encoder's feature maps, Richardson~{{et al}. }~\shortcite{richardson2020encoding} introduce $18$ separate map2style modules, one for each input layer of StyleGAN. Wei~{{et al}. }~\shortcite{wei2021simple} and Alaluf~{{et al}. }~\shortcite{alaluf2021restyle} find that a complex hierarchical encoder is unnecessary, especially in unstructured domains (e.g., cars, churches, horses) and instead propose simpler backbones. Wei~{{et al}. }~\shortcite{wei2021simple} further replace the $18$ map2style blocks with a simple block comprised of a single average pooling layer and fully connected layer. Rather than encoding an image into a set of \textit{style vectors}, Kim~{{et al}. }~\shortcite{kim2021stylemapgan} instead invert images into an intermediate latent space with a spatial dimension, resulting in more accurate reconstructions compared to other encoder networks. They also demonstrate that this extended latent space enables reference-guided local edits of real images. More recently, Wang~{{et al}. }~\shortcite{wang2021high} explored inverting into multiple latent spaces to achieve higher-fidelity inversions. They first invert an image into $\mathcal{W}$, to capture low-frequency details. A second encoder is then trained to map the distortion map --- the difference between the given image and its initial inversion --- into a set of spatial feature modulation maps that capture the remaining high-frequency image information. \setlength{\tabcolsep}{1pt} \begin{figure} {\small \begin{tabular}{lccccc} \rotatebox[origin=t]{90}{Optimization} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_input.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_w_optimization.png}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_optimization.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_hybrid.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_pti.jpg}} \\ \noalign{\vskip 1mm} & Input & Optim. $\mathcal{W}$ & Optim. $\mathcal{W}+$ & Hybrid & PTI \\ \rotatebox[origin=t]{90}{Encoder} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_input.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_idinvert.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_psp.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_e4e.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/1721_restyle.jpg}} \\ \noalign{\vskip 1mm} & Input & IDInvert & pSp & e$4$e & ReStyle \\ \rotatebox[origin=t]{90}{Editability} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/edit_input.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/edit_w.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/edit_w_plus.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/edit_e4e.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/edit_hyperstyle.jpg}} \\ \noalign{\vskip 1mm} & Input & Optim. $\mathcal{W}$ & Optim. $\mathcal{W}+$ & e$4$e & HyperStyle \\ \rotatebox[origin=t]{90}{Out-Of-Domain} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/ood_input.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/ood_restyle.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/ood_w_plus.png}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/ood_pti.jpg}} & \raisebox{-.4\totalheight}{\includegraphics[width=0.185\columnwidth]{Figures/inversion/ood_hyperstyle.jpg}} \\ & Input & ReStyle & Optim. $\mathcal{W}+$ & PTI & HyperStyle \\ \end{tabular} } \vspace{-0.1cm} \caption{StyleGAN inversion. Upper row presents inversion results of optimization methods: optimization to $\mathcal{W}+$ as proposed by Karras {{et al}. }~\shortcite{karras2019analyzing}, Hybrid approach where pSp ~\cite{richardson2020encoding} and optimization to $\mathcal{W}+$ are employed, and PTI~\cite{roich2021pivotal}. Second raw demonstrates the inversion using encoders, IDInvert ~\cite{zhu2020domain}, pSp ~\cite{richardson2020encoding}, e$4$e ~\cite{tov2021designing} and ReStyle ~\cite{alaluf2021restyle}, over the same input image. The third row illustrates the editability of different regions in the latent space. The same smile editing was applied over inversion to $\mathcal{W}+$ space, $\mathcal{W}$ space and well-behaved regions of $\mathcal{W}+$ using the e$4$e ~\cite{tov2021designing} encoder. As can be seen, optimization to $\mathcal{W}+$ achieves high-quality reconstruction but poor editability. PTI mitigates this tradeoff by using $\mathcal{W}$ space and tuning the generator weights, but suffer from extensive time consumption. Like PTI, HyperStyle~\cite{alaluf2021hyperstyle} uses the $\mathcal{W}$ space for editing, but efficiently learn to modify the generator weights rather than perform time-intensive optimization. Lastly, the ability of PTI and HyperStyle to handle out-of-domain attributes, such as face painting, is presented at the bottom row. Zoom-in is recommended.} \label{fig:inv} \vspace{-7pt} \end{figure} Another direction for improving the inversion of encoders is the improvement of the loss objectives used to learn the direct mapping from an image to its latent representation. Zhu~{{et al}. }~\shortcite{zhu2020domain} employ a discriminator for an adversarial-based training of the encoder network and use the discriminator as an additional loss to the encoder. To improve the inversion on the human facial domain, Richardson~{{et al}. }~\shortcite{richardson2020encoding} introduce a dedicated identity loss using a pre-trained facial recognition network. Tov~{{et al}. }~\shortcite{tov2021designing} extend this to additional domains by employing a similarity loss based on a MoCo~\cite{chen2020improved} feature extractor pre-trained on ImageNet. Wei~{{et al}. }~\shortcite{wei2021simple} utilize a pre-trained face parsing network to achieve more localized supervision during the encoder training. While encoder-based techniques result in an efficient inference scheme, taking a fraction of a second per image, the reconstructions are typically less accurate than optimization-based approaches. In an attempt to close the gap between the two methodologies, Alaluf~{{et al}. }~\shortcite{alaluf2021restyle} introduce an iterative refinement scheme over standard encoder-based inversion techniques. Instead of directly outputting the inferred latent code using a single forward pass through the network, the encoder outputs a sequence of residuals used to iteratively improve the inverted latent code and corresponding reconstruction. Others~\cite{zhu2016generative,zhu2020domain} exploit the advantages of both of the above approaches and employ a hybrid technique combining the two. First, an initial approximate latent code $w_{initial}$ is inferred via a trained encoder. This latent code is then used to initialize the optimization procedure. In~\cite{guan2020collaborative}, the encoder network is used to initialize an optimization process, which in turn supervises the training of the encoder network via a set of reconstruction losses. We refer the reader to Figure~\ref{fig:inv} for a comparison of various optimization-based and encoder-based inversion techniques. Xia {{et al}. }~\shortcite{xia2021gan} provide a comprehensive survey and analysis of recent inversion methods, exploring the three aforementioned methodologies and their use in various editing applications. While the inversion process is a well-studied problem, it remains an open challenge. Numerous works~\cite{abdal2020image2styleganpp,zhu2020improved,tov2021designing,zhu2020domain,wulff2020improving} demonstrate the existence of a reconstruction-editability trade-off. Whereas $\mathcal{W}+$ has been shown to be more expressive than $\mathcal{W}$~\cite{abdal2020image2styleganpp}, supporting more accurate reconstructions, its use leads to latent codes which lie in regions of the latent space that were unobserved during the generator training. In these regions, the semantic structure of the latent space deteriorates, resulting in degraded performance of latent space traversal editing methods, as demonstrated in Figure.~\ref{fig:inv}. Some works searched for a good point on this trade-off curve. Tov~{{et al}. }~\shortcite{tov2021designing} design an encoder to embed images into $\mathcal{W}+$ that are close to $\mathcal{W}$, resulting in a good balance between reconstruction quality and editability. Zhu~{{et al}. }~\shortcite{zhu2020improved} analyze various latent spaces to achieve more control over the reconstruction-editability trade-off. In an attempt to side-step this trade-off, Roich~{{et al}. }~\shortcite{roich2021pivotal} propose a pivotal tuning method to inject new identities into well-behaved, editable regions of StyleGAN's latent space. They first use a standard optimization procedure to find a latent code $w\in\mathcal{W}$ approximating the input image. This is followed by a per-image fine-tuning session where the generator weights are modified to improve the reconstruction quality. Other generator tuning approaches have also been proposed for achieving high fidelity reconstructions (see Section~\ref{sec:fine-tuning}). While most generator tuning approaches improve the image inversion via a per-image optimization of the generator weights, such an approach is costly in terms of inference time. To reduce this inference overhead, Alaluf~{{et al}. }~\shortcite{alaluf2021hyperstyle} and Dinh~{{et al}. }~\shortcite{dinh2021hyperinverter} propose a hypernetwork-based encoder that \textit{learns} how to modify the pre-trained generator weights to best reconstruct a given image. Such a learned approach results in high-fidelity reconstructions and edits, at a fraction of the time compared to optimization-based tuning approaches. Finally, while most works studying inversion focus on encoding and editing still images, when it comes to video editing new challenges arise. Specifically, video inversion should be temporally consistent. Tzaban~{{et al}. }~\shortcite{tzaban2022stitch} demonstrate that by combining encoders~\cite{tov2021designing} with generator tuning techniques~\cite{roich2021pivotal}, the consistency of the original video can be maintained. Another challenge can be found in the texture-sticking phenomenon observed in StyleGAN1 and StyleGAN2~\cite{karras2021alias}, which hinders the realism of generated and manipulated videos. To overcome this, Alaluf~{{et al}. }~\shortcite{alaluf2022times} combine the PTI~\cite{roich2021pivotal} and ReStyle~\cite{alaluf2021restyle} encoding techniques for encoding and editing videos with the StyleGAN3~\cite{karras2021alias} generator. Further leveraging the equivariance of StyleGAN3, they demonstrate the ability to expand the field of view when working on a video with a cropped subject resulting in more uniform video editing. \subsection{Latent Space Embedding} \label{sec:endcoding} Image inversion provides a latent code that reconstructs a given image. As the image itself is given, the produced latent code is usually not of interest on its own. Rather, one applies inversion to then manipulate the latent code to produce a new latent code that corresponds to a novel image. In this light, the limitations of inversion are clear. First, inversion methods require that the input image be invertible. That is, it must reside within one of the latent spaces of StyleGAN. Second, it is assumed that there is a known global transformation in the latent space to produce the desired manipulated code. However, for some applications, at least one of these assumptions is not true. For example, consider commonly studied image-to-image tasks such as semantic map-to-image and sketch-to-image \cite{isola2017image}. As StyleGAN is trained on one domain, usually the natural image domain, the sketch image would not be invertible to StyleGAN's latent space. Hence, several works have analyzed this limitation and have proposed a broader task of \textit{Latent Space Embedding.} In this setting, for some image $x$, one seeks a function $f$ such that $G(f(x)) \sim h(x)$, where $G$ is the pretrained StyleGAN generator and $h$ is some conceptually known function in image space (e.g., sketch-to-image). Under this perspective, inversion is a special case in which $h$ is the identity function. However, many methods have proposed training such function $f$ for specific transformations $h$. \input{Figures/latent_embedding} First, Nitzan~{{et al}. }~\shortcite{Nitzan2020FaceID} propose using StyleGAN to disentangle identity from other facial attributes and recompose novel images. They do so by extracting identity and attribute representations from different images, combining them, and then training a mapping network to directly produce the latent code that fuses the two representations, resulting in a novel face image, see Figure~\ref{fig:latent_embedding}(a). Next, Richardson~{{et al}. }~\shortcite{richardson2020encoding} proposed a generic framework, pixel2style2pixel (pSp), to perform a wide variety of image-to-image tasks, such as the aforementioned sketch-to-face and semantic map-to-face. pSp employs an encoder architecture based on a feature pyramid network (FPN), to naturally match the StyleGAN hierarchical generative path. Through the right inductive bias, this work demonstrates state-of-the-art inversion quality, along with various other successful encoding tasks for human faces, including in-painting, super-resolution, unsupervised frontalization, colorization, and more, see Figure \ref{fig:latent_embedding}(b). Several works used the above concept of latent space embedding for a variety of tasks, often obtaining state-of-the-art performance. Most notably for the task of restoring corrupted images. PULSE \cite{menon2020pulse} solves super resolution of facial images. Specifically, PULSE performs a latent-space optimization to recover a code, from which StyleGAN synthesis followed by downsampling reconstructs the original low-resolution input image (see Figure \ref{fig:latent_embedding}(c)). Time-Travel Rephotography \cite{Luo-Rephotography-2020} (Figure \ref{fig:latent_embedding}(d)) restores old photographs, transforming them to modern imagery. They do so by following a similar approach to PULSE, with a dedicated degradation module replacing the down-sampling step. GFPGAN \cite{wang2021gfpgan} solves blind face restoration by constructing dedicated losses and architecture. GLEAN \cite{chan2021glean} use an encoder-latent bank-decoder architecture to solve super-resolution tasks. Once more, the decoder is a well-trained StyleGAN generator. Of the aforementioned tasks, a task receiving considerable attention is that of sketch-to-image due to its immediate application to a variety of real-world settings. Building on the multi-modal sketch-to-image approach from pSp~\cite{richardson2020encoding}, Wei~{{et al}. }~\shortcite{wei2021simple} utilize a specialized face parsing loss to improve the alignment between an input sketch or semantic map and the output realistic facial image. Finally, Wang~{{et al}. }~\shortcite{wang2021sketch} modify a pre-trained StyleGAN for transforming a given sketch into a realistic image. As the generator tuning is subtle, the inherent characteristics of the original generator (e.g., color, texture) are well-preserved while supporting multi-modal synthesis. A myriad of other applications has also been explored via the task of latent space embedding. Chai~{{et al}. }~\shortcite{chai2021latent} train an encoder for performing image composition and image completion by leveraging the strong image prior of a pre-trained StyleGAN generator. Alaluf~{{et al}. }~\shortcite{alaluf2021matter} pair a pSp encoder~\cite{richardson2020encoding} and pre-trained age regressor~\cite{RotheDEX} for performing age transformation on real images via StyleGAN's latent domain. Jang~{{et al}. }~\shortcite{jang2021stylecarigan} transform real facial images to caricatures by altering the specific layers of a pre-trained StyleGAN. Specifically, they leverage the hierarchical nature of StyleGAN and modify the coarse input layers controlling head shape while keeping the fine layers controlling style and color unchanged. Xu~{{et al}. }~\shortcite{xu2021linear} and Ling~{{et al}. }~\shortcite{ling2021editgan} edit a given image in the domain of its part-segmentation. The fundamental observation is that one can train a simple function, $f$ inferring a semantic segmentation, corresponding to the image generated by a latent code, from intermediate activations of StyleGAN on that latent code. Specifically, they use the up-sampled and concatenated per-layer activations as input to $f$. This observation and construction was concurrently proposed by other works \cite{tritrong2021repurposing, zhang2021datasetgan} for different applications and are discussed in Section \ref{sec:discriminative}. Given an image, Xu~{{et al}. }~\shortcite{xu2021linear} propose to compute its semantic segmentation using off-the-shelf methods. Then, the segmentation map is edited with some desired effect and finally, it is embedded into the latent space of StyleGAN through StyleGAN's own layers as well as those of the function $f$. The resulting latent may then be forwarded through StyleGAN to generate the edited image. Other works~\cite{wei2021simple,zhu2021shot,yang2021shapeediter} examined the task of face swapping by blending the latent representations of two input images embedded via a learned encoder. Zhu~{{et al}. }~\shortcite{zhu2021barbershop} study the task of hairstyle transfer. In their work, they decompose an input latent code into a pair of latent codes representing structure and appearance. To transfer a given hairstyle, they blend between several images by taking specific regions of the structure latent codes and combining them with a target appearance. Finally, Chandran~{{et al}. }~\shortcite{chandran2021rendering} combine traditional and neural synthesis approaches by projecting high-quality skin maps into the latent space of StyleGAN, which is tasked with filling in regions that traditional methods struggle with --- such as the eyes, inner mouth, or hair. While all the aforementioned works showed incredible results and promise in real-world scenarios, they are limited in the domains they operate over. Some works have explored going beyond the facial domain and have explored applying StyleGAN for full-body synthesis in various applications such as virtual try-on and portrait reposing~\cite{Lewis2021TryOnGANBT,albahar2021pose}. \subsection{Latent Spaces} \label{sec:spaces} Unlike common GANs, StyleGAN has more than one innate latent space. Moreover, to increase the expressive power of StyleGAN, it is common to work with extensions of these spaces, illustrated in Figure~\ref{fig:space}. Here, we review the commonly used spaces and describe the differences between them. \begin{itemize} \item The first latent space is $\mathcal{Z}$ in the sense that random latent codes can be sampled from it to be inserted into the generator itself. $\mathcal{Z}$ is defined to be a normally distributed space, and it is the only space that has a closed-form definition. Therefore, images that belong to the GAN's manifold can be easily sampled from $\mathcal{Z}$. \item Latent codes from $\mathcal{Z}$ are transformed to latent codes in $\mathcal{W}$ through an MLP, commonly referred to as the \textit{mapping network}. In a sense, the distribution of $\mathcal{W}$ is learned, and therefore better matches the distribution of the real data compared to the original $\mathcal{Z}$ space. This learned distribution provides the virtue of disentanglement. Many works employ this disentanglement property to achieve semantic image editing by traversing the latent space. \item Latent codes in $\mathcal{W}$ are not directly inserted into the synthesis network. Instead, each latent code in $\mathcal{W}$ is first transformed through a learned affine transformation. Such an affine transformation is learned during the training of each layer of the synthesis network. The space spanned by the outputs of these transformations is commonly referred to as the \textit{StyleSpace}, or $\mathcal{S}$. Unlike $\mathcal{W}$ in which a single latent code is used for generating an image, in $\mathcal{S}$ there are several latent codes for a single image, one for each affine transformation block (e.g., 26 for a generator with a $1024 \times 1024$ output resolution). It has been shown \cite{wu2020stylespace} that $\mathcal{S}$ is even more disentangled than $\mathcal{W}$. More specifically, each dimension, or channel, of $\mathcal{S}$ tends to control a single semantic attribute of the generated image. Therefore, by carefully manipulating the dimensions of $\mathcal{S}$ it is possible to obtain highly disentangled edits. \item Representing real images with StyleGAN remains a challenge. The good properties of $\mathcal{W}$ have attracted most works aiming at representing real images to focus on it. Abdal~{{et al}. }~\shortcite{abdal2019image2stylegan} propose working in an extended latent space, denoted by $\mathcal{W+}$ In $\mathcal{W+}$, one inserts a different latent code for each layer of the synthesis network (e.g., $18$ for a generator with a $1024 \times 1024$ resolution). StyleGAN was not trained on $\mathcal{W+}$ and thus images sampled from it do not necessarily have high quality. Moreover, it should be noted that oftentimes, when operating in $\mathcal{W+}$, it is possible to reach areas that are outside the learned distribution of $\mathcal{W}$. Such areas further push the latent code outside the distribution over which the generator was trained on. As the distribution of $\mathcal{W}$ cannot be explicitly modeled, keeping the latent code in the trained distribution is a challenging task. \item To alleviate the need of preserving the latent code inside the distribution of $\mathcal{W}$, it is possible to work with an extension of $\mathcal{Z}$ instead of $\mathcal{W}$. Similarly to the definition of $\mathcal{W+}$, in $\mathcal{Z+}$ \cite{song2021agilegan} a different latent code is sampled for each layer of the synthesis network (e.g., $18$ for a $1024 \times 1024$-resolution generator). Note, that in $\mathcal{S}$ there is no notion of $\mathcal{S+}$ as the latent codes for each layer are different by design. \end{itemize} \section{Fine-Tuning the Generator} \label{sec:fine-tuning} \subsection{Data Reduction} Training a StyleGAN model requires substantial amounts of data, confined to quite a small domain. This means that the amount of available data serves as a strong bottleneck for adapting StyleGAN to new domains. An established way to address the lack of data is through augmentation. To stabilize training in limited data scenarios, several methods \cite{zhao2020diffAugment, Karras2020ada, zhao2020image} used differential augmentations during the training process. In contrast to classification tasks, generative augmentations pose a challenge --- if the discriminator observes sufficient augmented samples, the generator might produce such augmented results by itself. In many cases, the augmentations leakage to the generated images is highly undesirable, \emph{e.g}.} \def\Eg{\emph{E.g}. when the augmentations contain rotations or unrealistic colorization changes. By monitoring overfitting indications during training and adaptively increasing augmentation strength, Karras~{{et al}. }~\shortcite{Karras2020ada} are able to introduce additional supervision to the network through augmentations, without allowing them to leak into the generated results. They achieved state-of-the-art results in low data domains, significantly reducing the number of training samples required for training. Sinha~{{et al}. }~\shortcite{sinha2021negative} also suggest explicitly providing the discriminator with negative out-of-distribution samples to bias the generator away from unwanted samples. Another direction, proposed by Yang~{{et al}. }~\shortcite{yang2021insgen} is to empower the discriminator to better extract knowledge from the training set by providing it with an auxiliary task in the form of instance-discrimination via a contrastive learning objective. Kumari~{{et al}. }~\shortcite{kumari2021ensembling} propose to leverage the feature space of pre-trained vision models, trained for different vision tasks. By progressively selecting and employing the models as additional discriminators, they manage to improve synthesis quality in both limited-data and large-scale settings. \input{Figures/domain_adaptation} Another established and popular approach is \textbf{domain adaptation}, where different works seek to convert pre-trained StyleGAN models into other semantically similar domains using few data exemplars. Aside from reducing the amount of data needed to train a model from scratch, Karras~{{et al}. }~\shortcite{Karras2020ada} fine-tuned a StyleGAN generator trained over the FFHQ dataset into the domain of MetFaces, a collection of images from the Metropolitan Museum of Art, using only $1,336$ training samples. Following the above, Pinkney~{{et al}. }~\shortcite{pinkney2020resolution} leverage the disentangled control over the coarse, medium, and fine semantic attributes StyleGAN offers and perform \textit{domain-mixing} for depicting the geometry of one domain with the textural appearance of another. The authors fine-tune a well-trained StyleGAN for human faces using only $300$ cartoon examples. They then propose blending the models, replacing high-resolution layers of the fine-tuned model with the pre-trained layers of the source domain. This yields a toonification effect, producing an output domain of cartoons, with the complex variety and structure of human faces. Several works make use of a similar form of fine-tuning. Song~{{et al}. }~\shortcite{song2021agilegan} introduce several synthesis paths within the generator for different attributes, achieving high-quality portrait stylization. Following the fine-tuning process, Jang~{{et al}. }~\shortcite{jang2021stylecarigan} leverage the semantic correspondence between the two models. By feeding the same latent codes to both generators, an extensive paired training data set can be generated. This data is then used to train a translation network between the domains (in this case, a shape-exaggeration network operating over the caricatures domain). Within the \textbf{few-shot} settings, several works perform domain adaptation based on as few as $10$ training exemplars. When the translation is done between semantically similar domains, the methods manage to preserve the semantic properties and diversity of the source domain. Li~{{et al}. }~\shortcite{li2020few} maintain diversity by applying an elastic weight consolidation loss, regularizing weights change based on Fisher information, computed from a discriminator. To facilitate few-shots adaptation, Ojha~{{et al}. }~\shortcite{ojha2021fewshotgan} propose explicitly maintaining the source domain structure, through a distance consistency loss between pairs of resulting images. In addition, a shared image and patch discriminator is applied to create patch-level adversarial similarity throughout the latent space together with image-level similarity around chosen anchors. Taking domains with data shortage to the extreme, Gal~{{et al}. }~\shortcite{gal2021stylegannada} perform zero-shot domain adaptation, fine-tuning StyleGAN without providing any exemplar images. They propose describing the desired target domain in text and using a pre-trained linguistic-visual model~\cite{radford2021learning} to guide the adaptation. The GAN is trained such that the CLIP-space direction between the resulting images before and after the tuning process aligns with the CLIP-space direction between a pair of source and target description texts. Zhu~{{et al}. }~\shortcite{zhu2021mind} perform single-shot domain adaptation by matching the reference image in the target domain with a corresponding synthesized image from the source domain, obtained through latent space optimization. Using the reference pair, in addition to the CLIP-space loss defined in StyleGAN-NADA, they introduce a new objective, which is to maintain CLIP-space direction similarity between each reference image and the current training iteration's synthesized image. Using this method, the authors manage to achieve better adaptation of pose, lighting, and expression through the domain transfer process. Taking a different approach, Yang~{{et al}. }~\shortcite{yang2021oneshot} freeze the generator weights and learn a linear transformation in $\mathcal{Z}$ space, using as little as a single reference image. We refer the reader to Figure~\ref{fig:domain_adaptation} for sample domain adaptation results. \subsection{Data-Aware Generator Tuning} Arguably, the most promising direction for StyleGAN development is through data-aware model manipulation. A pre-trained StyleGAN model is phenomenal in local structure and disentanglement (see Section~\ref{sec:architecture}), but is relatively confined in generality. As such, it stands to reason that there could be significant benefit in adapting the model to include new, specific data points. Then, if the GAN's structure is maintained, these new points could be better processed for editing or discriminative applications. This concept has been suggested in the past already~\cite{bojanowski2018optimizing}. For example, in the context of GANs, Bau {{et al}. }~\shortcite{semantic2019bau} propose adapting the image prior learned by Progressive GAN~\cite{karras2017progressive} to image statistics of an individual image. Through minimal fine-tuning, the authors were able to faithfully reconstruct a given image, and present editing capabilities of quality unseen at the time, including synthesizing new objects seamlessly, removing unwanted objects, and changing object appearance. Similarly, Pan~{{et al}. }~\shortcite{pan2020exploiting} use BiGGAN~\cite{brock2018large} to capture high-level semantic image priors such as color, texture, spatial coherence, etc., for tasks such as colorization, inpainting, morphing, and category transfer. This is contrary to the traditional approach~\cite{ulyanov2018deep}, where only low-level priors are captured. Their method is based on GAN-inversion, but they overcome the difficulty of GAN-inversion methods to generate out-of-domain images by allowing the generator to be fine-tuned on the fly when searching for the latent source. They regularize the generator fine-tuning with feature matching loss from the discriminator, and use progressive fine-tuning (from shallow layers to deep). In the context of StyleGAN, Roich~{{et al}. }~\shortcite{roich2021pivotal} take a similar approach. Given a real-world image that is similar, but not included in the domain of a pretrained StyleGAN (e.g., an image of a human face, with very untypical facial features, makeup, or hairstyle), they propose finding the closest latent code to the desired appearance (termed the `pivot'), and fine-tuning the generator so the exact appearance would be reconstructed with this code. In addition, they ensure the process does not impair the disentangled latent space through regularization. This simple approach produces significantly better reconstructions (see Fig.~\ref{fig:inv}), and allows employing off-the-shelf editing techniques with high quality, essentially bypassing the notorious distortion-editability trade-off (see Section~\ref{sec:encoding}). Such fine-tuning sessions are typically brief, lasting an order of a single minute. As described in Section \ref{sec:inversion}, this generator tuning can alternatively be performed as a forward pass procedure using hypernetworks \cite{alaluf2021hyperstyle, dinh2021hyperinverter}. Tzaban~{{et al}. }~\shortcite{tzaban2022stitch} further improve the tuning scheme to semantically edit a video while preserving temporal coherence. First, they observe that using an encoder for the initial inversion allows for a temporally-smooth edit after tuning the generator. Second, they propose to further tune the generator to better stitch the edited cropped face back to the original frame. Bau~{{et al}. }~\shortcite{bau2020rewriting} perform a similar tuning operation, but where the awareness is to the task instead of the data. The authors propose changing semantic and physical properties (or \textit{rules}) of deep generative networks, relying on the concept of linear associative memory. While current methods for image editing allow users to manipulate single images, this method allows changing semantic rules and properties of the network, so that all images generated by the network have the desired property. This includes removing undesired patterns such as watermarks and adding objects such as human crowds or trees. Kwong~{{et al}. }~\shortcite{kwong2021unsupervised} outline a method for cross-domain editing by inverting images into a source domain and re-synthesizing them in a fine-tuned model using the same code. Cherepkov~{{et al}. }~\shortcite{cherepkov2021navigating} expand the range achievable by existing state-of-the-art generative models used for image editing and manipulation, such as StyleGAN2. While existing methods find interpretable directions in the model’s latent space and operate on latent codes, they find interpretable directions in the space of generator parameters and use them to manipulate images and expand the range of possible visual effects. They show that their discovered manipulations, such as changing car wheel size, cannot be achieved by manipulating the latent code. Finally, Liu~{{et al}. }~\shortcite{liu2022selfconditioned} demonstrate that brief fine-tuning sessions can be used to condition a model on labels derived from the latent-space itself, thereby ``baking'' editing directions into the GAN and improving treatment of rare data modalities, such as extreme poses or underrepresented ethnicities. \section{Introduction} The ability of GANs to generate images of phenomenal realism at high resolutions is revolutionizing the field of image synthesis and manipulation. More specifically, StyleGAN \cite{karras2019style} has reached the forefront of image synthesis, gaining recognition as the state-of-the-art generator for high-quality images and becoming the de-facto golden standard for the editing of facial images. See Figure~\ref{fig:teaser}, top for some visual examples. \input{Figures/teaser/teaser} \input{Figures/teaser/teaser_editing} StyleGAN presents a fascinating phenomenon. It is unsupervised, and yet its latent space is surprisingly well behaved. As it turns out, it is so well behaved that it even supports linear latent arithmetic. For example, it supports adding a vector representing age to a set of latent codes, resulting in images representing the original individuals, but older. Similarly, it has been demonstrated that StyleGAN arranges its latent space not only linearly, but also in a disentangled manner, where traversal directions exist that alter only specific image properties, while not affecting others. Such properties include global, domain-agnostic aspects (e.g., viewing angles or zoom), but also domain-specific properties such as expressions or gender for human faces, car colors, dog breeds, and more (see Figure~\ref{fig:teaser}, and Figure \ref{fig:edit}). Exploring what these qualities entail, recent StyleGAN-based work has presented astounding realism, impressive control, and inspiring insights into how neural networks operate. As groundbreaking as it may be, these powerful editing capabilities only reside within the model's latent space, and hence only operate on images generated by StyleGAN itself. Seeking to bring real-world images to the power of StyleGAN's latent control, inversion into StyleGAN's latent space has received considerable attention. Further harnessing StyleGAN's powers, other applications have also arisen, bringing contributions to the worlds of segmentation, augmentation, explainability, and others. In this report, we map out StyleGAN's phenomenal success story, along with analyzing its severe drawbacks. We start by discussing the architecture itself and analyze the role it plays in creating the leading generative model since its conception in 2018. % We then shift the discussion to the resources and characteristics StyleGAN's training requires, and lay out the work that reduces, re-uses, and recycles it. In Section \ref{sec:editing}, we discuss StyleGAN's latent spaces. We show how linear editing directions can be found, encouraged, and leveraged into powerful semantic editing. We inquire into what properties StyleGAN can and cannot disentangle well and dive into a surprisingly wide variety of approaches to achieve meaningful semantic latent editing. In Section \ref{sec:encoding}, the quest for applying StyleGAN's power in real-world scenarios turns to a discussion about StyleGAN inversion. To express a given real image in StyleGAN's domain, many different approaches have been suggested, all of which thoroughly analyze and exploit the generator's architecture. Some propose latent code optimization and others apply data-driven inference. Some works seek an appropriate input seed vector, while others interface with StyleGAN at other points along the inference path, greatly increasing its expressive power. Unsurprisingly though, it turns out that the well-behaved nature of StyleGAN's latent space diminishes in regions far from its well-sampled distribution. This in practice means that given a real-life image, its accurate reconstruction quality (or \textit{distortion}) comes at the cost of \textit{editability}. Finding different desired points on this reconstruction-editability trade-off is a main point of discussion in the works covered in this section. Encoding an image into StyleGAN's latent space has more merit than for image inversion per se. There are many applications where the image being encoded is not the one the desired latent code should represent. Such encoding allows for various image-to-image translation methods \cite{Nitzan2020FaceID,richardson2020encoding,alaluf2021matter}. In Section \ref{sec:encoding}, we present and discuss such supervised and unsupervised methods. In Section \ref{sec:discriminative}, we show the competence of StyleGAN beyond its generative power and discuss the discriminative capabilities StyleGAN can be leveraged for. This includes applications in explainability, regression, segmentation, and more. In most works and applications, the pre-trained StyleGAN generator is kept fixed. However, in Section \ref{sec:fine-tuning}, we present recent works that fine-tune the StyleGAN generator and modify its weights to bridge the gap between the training domain (in-domain) and the target domain, which could possibly be out-of-domain. Each section addresses both the newcomer, with basic concepts and conceptual intuition, and the experienced, with a summary of the most established and promising approaches, along with some pointers regarding when to use them. \section{Evaluation Metrics}~\label{sec:metrics} While many aspects of GAN quality can be evaluated qualitatively, it is often desirable to assess the model quality more objectively. Evaluation metrics can be used to produce reliable, standardized benchmarks and to better gauge the advancement of the field. As we discuss below, this problem is not restricted to StyleGAN editing alone, but to the evaluation of most GANs and editing operations. \paragraph*{GAN Evaluation} The evaluation of generative models is straightforward when ground truth is at hand. For example, GAN inversion can be measured by various metrics assessing the distortion, such as pixel-wise distance using mean-squared error, perceptual similarity using LPIPS \cite{zhang2018unreasonable}, structural similarity using MS-SSIM \cite{wang2003multiscale}, or identity similarity~\cite{marriott2020assessment}, employed for facial images using a face recognition network \cite{deng2019arcface}. In the absence of such ground truth for the task of unconditional image synthesis, the evaluation of GAN quality remains an open challenge. Undoubtedly, the most popular metric is the Frechet Inception Distance (FID) \cite{heusel2017gans}. FID measures the similarity between two distributions using the Frechet Distance, where each distribution consists of visual features extracted by utilizing a pretrained recognition network ~\cite{szegedy2016rethinking}. Namely, given two sets of images, low FID indicates these sets share similar visual statistics. For the case of GANs, the target dataset is compared to the same number of random synthesized images, showing the similarity between these distributions. Former to FID, Inception Score (IS) \cite{salimans2016improved} was introduced for the same purpose, measuring KL divergence over the same feature statistics. An additional approach has been suggested to measure the distance between real and generated images using the Sliced Wasserstein Distance (SWD) \cite{rabin2011wasserstein}, which computes the statistical similarity between local image patches extracted from the Laplacian pyramid of the images. However, as FID is shown to be better correlated with the human perception of high-quality images, it has become the most widely used metric. Despite its vast popularity, the FID metric does have drawbacks. As the extracted visual features are local, FID struggles to grasp a global structure. For facial images, which bear a simple structure, FID is still effective. Yet, images containing extremely unrealistic structures but high-quality textures, such as a cat with eight legs, can still achieve a good FID score undesirably. Another major concern is the employment of the popular truncation trick~\cite{marchesi2017megapixel,karras2019style}. Many works generate images using a latent truncation but measure FID without it, as it alters the distribution substantially and leads to a deterioration of FID values~\cite{katzir2022multilevel}. % Sajjadi ~\cite{sajjadi2018assessing} proposed a solution to this exact problem by breaking down the GAN evaluation into recall and precision. High precision indicates high quality and realistic image generation, while high recall refers to generating a large amount of variation which is similar in diversity to the original data. \paragraph*{Editing Evaluation} For most practical cases, acquiring ground truth data and labeling to directly evaluate editing is infeasible or altogether impossible. As such, creative solutions have been proposed to tackle the problem of editing quality evaluation. Contrary to disentanglement or GAN quality, the evaluation of StyleGAN's editing ability has not been widely studied. A few key aspects need to be analyzed for the evaluation of these editing procedures. Consider the example of adding a smile to a facial image. The most important aspect is the semantic meaning, namely, whether the editing successfully implants a smile. For binary editing, this could be easily performed using a classifier ~\cite{mokady2019masked, lample2017fader}, but in most cases, continuous editing is required. A regression model can be adopted for this case. However, for many attributes, these models are unavailable or require a vast amount of annotations to be trained. For example, recent works ~\cite{zhu2020improved, roich2021pivotal} used the Microsoft Face API ~\cite{azure} to measure face rotation but fail to measure the smile extent continuously. Furthermore, Zhu~{{et al}. }~\shortcite{zhu2020improved} demonstrate that the semantic editing magnitude when employing fixed editing is larger for the more native and editable regions of StyleGAN, and hypothesize that the magnitude could be utilized as an editability metric. Another key aspect is refraining from distorting the unedited parts of the image, usually referred to as preserving the original identity. For example, smile editing should not result in the appearance of glasses or a change in haircut. Some works ~\cite{Nitzan2020FaceID,richardson2020encoding,alaluf2021matter,tov2021designing, roich2021pivotal} focus on facial images, where identity preservation could be evaluated using facial recognition networks~\cite{deng2019arcface}. Since these networks are trained to be invariant to most attributes, adding a smile should not affect the output substantially. Therefore, an identity similarity can be measured by the cosine similarity of the facial identity representations. Nevertheless, as have been shown by Zhu~{{et al}. }~\shortcite{zhu2020improved}, the less editable latent spaces produce lower magnitude edits, leading to a bias in favor of these barely editable regions. Intuitively, the identity is better preserved better when the editing effect is reduced. Consequently, Roich~{{et al}. }~\shortcite{roich2021pivotal} suggest measuring the identity similarity while performing edits of the same magnitude, e.g. rotation to a predetermined angle. Such metrics have been shown to be more robust, with the identity similarity for the less editable $\mathcal{W+}$ space inversion being inferior compared to the native $\mathcal{W}$ space. Recent works \cite{yao2021latent, alaluf2021hyperstyle} have taken the above procedure a step further, plotting the measured identity similarity along a \textit{range} of editing magnitudes. This results in a continuous curve measuring identity preservation as a function of editing strength. In the context of videos, Tzaban~{{et al}. }~\shortcite{tzaban2022stitch} measured temporal coherence of edited videos, separating the evaluation of local (TL-ID) and global (TG-ID) identity consistency. Locally, they evaluate the identity similarity between pairs of adjacent frames. Globally, they measure similarity between all possible pairs, \emph{i.e}.} \def\Ie{\emph{I.e}.{} not necessarily adjacent. Still, these metrics are mostly limited to facial data, as it is challenging to procure identity recognition networks for other domains such as churches, cars, or cats. To this end, Abdal~{{et al}. }~\shortcite{abdal2020styleflow} focused on the setting of sequential editing and proposed to measure similarity between results obtained when applying the same semantic directions in a different order. Tov {{et al}. }~\shortcite{tov2021designing} suggested the latent editing consistency (LEC) metric to evaluate the editing quality realized by a given encoder $E$. Their method consists of performing latent editing followed by synthesis, encoding, and applying the reverse editing. Optimal editing is expected to result in minimal distortion as the editing procedure should only affect the desired attribute. One more concern is image quality. One of StyleGAN's key benefits is high visual quality, and editing methods should aim to preserve it. To this end, the common FID metric can be used over the edited images. However, editing might cause a significant bias between the edited and the real data, leading to inaccurate evaluation. If available, a classifier or regression model can be used to balance both image collections with respect to some attribute. A further approach, presented by Zhu~{{et al}. }~\shortcite{zhu2020improved}, is to evaluate the interpolation quality. They suggest that good editability should retain the high quality of StyleGAN even for the interpolated images, and utilize the FID metric for this purpose. Lastly, a number of works utilized a user study to evaluate editing quality~\cite{zhu2020improved, tov2021designing} through human judgment. Although this approach carries a profound understanding of the editing procedure, it consumes significant resources and is susceptible to unwanted manipulations. To this day, there is no widely acceptable assessment metric for latent manipulation quality.
{'timestamp': '2022-03-01T02:59:47', 'yymm': '2202', 'arxiv_id': '2202.14020', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.14020'}
arxiv
\section{Introduction} $\mathcal{EL}^{++}$ is a lightweight Description Logic that admits sound and complete reasoning in polynomial time and has been used to define the Web Ontology Language (OWL) 2 EL profile \cite{motik2009owl}. $\mathcal{EL}^{++}$ is of great value in real-world applications, and especially in the life sciences where a large number of ontologies have been developed \cite{smith2007obo} and the OWL 2 EL profile is widely used \cite{hoehndorf2011common}. Statistical methods \cite{subramanian2005gene} and semantic similarity measures \cite{pesquita2009semantic} have been developed and widely used to analyze ontologies as well as entities characterized with concepts in ontologies. Recent years have witnessed increasing interest in distributed representation learning in a variety of fields including natural language processing \cite{mikolov2013distributed} and recommender systems \cite{he2017neural}. This motivated efforts in understanding and exploiting the Description Logic $\mathcal{EL}^{++}$ through embeddings \cite{kulmanov2019embeddings,mondala2021emel}. The embedding methods for $\mathcal{EL}^{++}$ consider concepts as $n$-balls in an $n$-dimensional embedding space. The rationality behind representing concepts as geometric regions rather than single points in the embedding space is twofold. First, logical operations within ontological axioms, such as subsumptions and intersections, require geometric operations on top of regional representations. Second, the semantics of $\mathcal{EL}^{++}$ interprets concepts as sets of entities, and these are naturally represented as regions in the embedding space. Therefore, geometric embeddings not only fulfill the need of embedding $\mathcal{EL}^{++}$ axioms but also establish a direct correspondence to the semantics of the $\mathcal{EL}^{++}$ Description Logic. \begin{figure}[t] \centering \includegraphics[width=0.3\textwidth,trim=0 340 650 0,clip]{ELBEIDEA.pdf} \vspace{-0.2cm} \caption{Example of concept intersections in $2$-dimensional space. The intersection of two boxes remains as a box whereas the intersection of $2$-balls is a lens-shaped region and not a $2$-ball.} \label{idea} \vspace{-0.3cm} \end{figure} Although these embedding methods are effective and theoretically well-motivated due to the relation between geometric regions and interpretations of the axioms, a common key issue remains unsolved: the \textbf{intersectional closure}, i.e., the property that the intersection of two concepts is again a concept within the embedding space, is not satisfied. Intuitively, the intersection of concept $Parent$ and concept $Male$ should also be a concept (i.e.., the concept $Father$) with the same type of geometric representation. However, as shown on the left of Figure \ref{idea}, the intersection of two $n$-balls is no longer an $n$-ball. Without the property of intersectional closure, conflicts arise when generating embeddings; for example, if the ontology contains both the axioms $Parent \sqcap Male \sqsubseteq Father$ and $Father \sqsubseteq Male \sqcap Parent$, the only valid solution to finding an embedding is to make $Father$, $Male$, and $Parent$ co-extensional; if additional axioms require $Parent$ to contain entities that are disjoint with $Male$ (such as for $Mother$), no valid embedding for the axioms can be found. This leads to instability during learning and challenges in determining similarity between concepts in embedding space, and it breaks the property that generating an embedding should generate a model of the theory. To this end, we developed \underline{EL} \underline{B}ox \underline{E}mbeddings (ELBE) to learn $\mathcal{EL}^{++}$ embeddings that satisfy the \textbf{intersectional closure}. As pointed out by works on geometric embeddings in other research fields \cite{ren2019query2box}, boxes, i.e., the area contained within axis-parallel high-dimensional rectangles, are particularly suitable for modeling logical operations in the embedding space. As shown on the right of Figure \ref{idea}, the intersection of $2$-dimensional boxes remains as a $2$-dimensional box and therefore satisfies the intersectional closure; the same property holds in higher dimensions. Therefore, we propose to use boxes as the geometric representations of concepts in $\mathcal{EL}^{++}$ based ontologies. To do so, we specifically design box-based constraints that embed axioms of $\mathcal{EL}^{++}$ ontologies. Our main contributions are summarized as below: \begin{itemize} \item We propose a novel method named ELBE that uses axis-parallel boxes to satisfy intersectional closure for $\mathcal{EL}^{++}$ embeddings; \item We conduct extensive experimental evaluations and provide in-depth analysis on real-world benchmark datasets to demonstrate the effectiveness the proposed method; \item We present a case study on a synthetic dataset to gain insights of our proposed method. \end{itemize} \section{Related work} \subsection{Description Logic $\mathcal{EL}^{++}$} $\mathcal{EL}^{++}$ falls into the family of description logics, which are fragments of first order logic and vary in their expressiveness. $\mathcal{EL}^{++}$ is particular suitable for representing and reasoning over large ontologies due to its polynomial time complexity in inferring subsumptions. Therefore, many large ontologies, especially in the biomedical domain, are based on $\mathcal{EL}^{++}$, including the Gene Ontology \cite{ashburner2000gene}, Human Phenotype Ontology \cite{kohler2017human}, and SNOMED CT \cite{donnelly2006snomed}. Furthermore, $\mathcal{EL}^{++}$ forms the basis of the OWL 2 EL profile \cite{motik2009owl}. \subsection{Distributed Representation Learning for $\mathcal{EL}^{++}$} Recently, inspired by the effectiveness of distributed representation learning in a variety of fields \cite{mikolov2013distributed,he2017neural}, several works propose to learn embeddings for concepts in $\mathcal{EL}^{++}$ ontologies. Specifically, \cite{kulmanov2019embeddings,mondala2021emel} learn \textit{geometric} embeddings for $\mathcal{EL}^{++}$ ontologies. The key idea of learning geometric embeddings is that the embedding function projects the symbols used to formalize $\mathcal{EL}^{++}$ axioms into an interpretation $\mathcal{I}$ of these symbols such that $\mathcal{I}$ is a model of the $\mathcal{EL}^{++}$ ontology. Other approaches \cite{chen2021owl2vec,smaili2019opa2vec} rely on more \textit{general} graph embeddings or word embeddings and apply them to ontology axioms. In this work, we learn $\mathcal{EL}^{++}$ embeddings using axis-parallel boxes, which falls into the \textit{geometric} embedding based methods. The aim of ELBE is to generate a model for a theory where the points that are contains within an $n$-box are the extension of a concept. By ensuring intersectional closure, our novel method addresses the instability in the learning process and the difficulty of similarity measurement in previous works. Furthermore, it can represent the extension of concept intersections within the embedding space. \subsection{Knowledge Graph Embedding} Distributed representation learning on knowledge graphs, i.e., knowledge graph embedding, has been extensively explored during recent years. Representative methods include methods that combine random walks with a language model \cite{grover2016node2vec,ristoski2016rdf2vec}, translation based methods \cite{bordes2013translating,wang2014knowledge} that regard a relation as the translation from a head entity to a tail entity, tensor decomposition methods \cite{yang2014embedding,balavzevic2019tucker} that assume the score of a triple can be decomposed into several tensors, and deep learning methods \cite{cai2018kbgan,vashishth2020compositionbased} that utilize deep neural networks to embed knowledge graphs. Although we follow the well-established translation based knowledge graph embedding method TransE \cite{bordes2013translating} in terms of the geometric interpretation of relational mappings, there is a key difference to be noted: these methods embed entities and relations in knowledge graphs from triples, while we embed concepts and relations in ontologies based on $\mathcal{EL}^{++}$ axioms. \section{Preliminaries} In this section, we first formulate the problem we aim to solve. Then, we introduce the key terminologies in description logic $\mathcal{EL}^{++}$ and elaborate the limitations of previous geometric embedding methods for $\mathcal{EL}^{++}$ ontologies. \subsection{Problem Formulation} An ontology in the Description Logic $\mathcal{EL}^{++}$ is formulated as $\mathcal{O}=(C,R,I; ax)$ where $C$ is a set of concept symbols, $R$ a set of relation symbols, $I$ a set of individual symbols, and $ax$ a set of axioms. We aim to find an embedding $e: \mathcal{O} \mapsto \Re^n$ such that the image of $e$ is a model of $\mathcal{O}$. Furthermore, the the embedding should allow answering queries: given a query concept description $Q$, find all concepts $C$ such that $C \sqsubseteq Q$; more specifically, we rank concepts $C$ to find the top-$k$ concepts that satisfy the query. \subsection{$\mathcal{EL}^{++}$ Terminologies} \label{elterminologies} In $\mathcal{EL}^{++}$, the TBox, i.e., terminological box, contains axioms describing concept hierarchies, while the ABox, i.e., assertional box, contains axioms stating the relations between individuals (or entities) and concepts. The ABox axioms can be eliminated by replacing $C(a)$ with $\{a\} \sqsubseteq C$ and replacing $r(a,b)$ with $\{a\}\sqsubseteq \exists r.{b}$. The Tbox axioms in $\mathcal{EL}^{++}$ can be normalized into one of the seven normal forms (NFs) summarized in Table \ref{nfs}. The syntax and semantics of $\mathcal{EL}^{++}$ is summarized in Table \ref{tbl:el}. \begin{table}[htbp]\centering \renewcommand\arraystretch{1.0} \renewcommand\tabcolsep{10pt} \caption{\label{nfs}Normal forms of $\mathcal{EL}^{++}$ and their abbreviations. } \begin{tabular}{c|c} \toprule \textbf{Abbr.} & \textbf{TBox Axioms} \\ \midrule NF1 & $C$ $\sqsubseteq$ $D$ \\ \midrule NF2 & $C\sqcap D \sqsubseteq E$ \\ \midrule NF3 & $\exists R.C \sqsubseteq D$ \\ NF4 & $C \sqsubseteq \exists R.D$ \\ \midrule NF5 & $C\sqcap D \sqsubseteq \bot$ \\ NF6 & $\exists R.C \sqsubseteq \bot$ \\ NF7 & $C\sqsubseteq \bot$ \\ \bottomrule \end{tabular} \end{table} \begin{table}[htbp] \footnotesize \renewcommand\arraystretch{1.0} \renewcommand\tabcolsep{5pt} \centering \caption{\label{tbl:el}Syntax and semantics of $\mathcal{EL}^{++}$. } \begin{tabular}{c|c|c} \toprule {\bf Name} & \textbf{Syntax} & \textbf{Semantics} \\ \midrule top & $\top$ & $\Delta^{\mathcal{I}}$ \\ \midrule bottom & $\bot$ & $\emptyset$ \\ \midrule nominal & $\{ a \} $ & $\{ a^{\mathcal{I}} \}$ \\ \midrule conjunction & $C \sqcap D$ & $ C^{\mathcal{I}} \cap D^{\mathcal{I}}$ \\ \midrule existential & \multirow{2}[2]{*}{$\exists r.C$} & $ \{ x \in \Delta^{\mathcal{I}} | \exists y \in \Delta^{\mathcal{I}} :$ \\ restriction & & $(x,y) \in r^{\mathcal{I}} \land y \in C^{\mathcal{I}} \} $ \\ \midrule concept inclusion & $C \sqsubseteq D$ & $C^{\mathcal{I}} \subseteq D^{\mathcal{I}}$ \\ \midrule instantiation & $C(a)$ & $a^\mathcal{I} \in C^\mathcal{I}$ \\ \midrule role assertion & $r(a,b)$ & $(a^\mathcal{I},b^\mathcal{I}) \in r^\mathcal{I}$ \\ \bottomrule \end{tabular} \end{table} \subsection{Limitations of Previous Works} Methods that construct geometric models for logical theories based on $n$-balls, such as ELEm \cite{kulmanov2019embeddings}, have a crucial limitation. Representing ontology concepts as $n$-balls entails that they cannot represent intersections of concepts within the same formalism because intersections of $n$-balls are not $n$-balls. This does prevent embeddings based on $n$-balls to represent and infer equivalent concept axioms and model the second normal form ($C \sqcap D \sqsubseteq E$) naturally. Specifically, it leads to complications with a loss function designed to minimize the loss for the second normal form, and likely results in embeddings of lower quality as a consequence. \section{Methodology} We consider the seven types of TBox axioms in $\mathcal{EL}^{++}$ ontologies as training instances. In this section, we first detail our specially designed box-based objective functions for each type of the TBox axioms. Then we present a case study in the family domain to demonstrate the rationalness of our proposed ELBE. \begin{figure*}[!t] \centering \subfigure[]{\includegraphics[width=2.2in,trim=50 10 200 110,clip]{dst1.pdf}\label{dis1}} \subfigure[]{\includegraphics[width=2.2in,trim= 0 0 230 90,clip]{dst2.pdf}\label{dis2}} \subfigure[]{\includegraphics[width=2.2in,trim=250 50 0 60,clip]{dst3.pdf}\label{dis3}} \caption{(a) The distance between centers of two boxes. (b) The distance with offsets. (c) When $\delta x$, $\delta y$ are both 0. } \label{fig5} \end{figure*} \subsection{First Normal Form (NF1)} We use $\beta (C)$ to represent the box embedding of concept $C$. Inspired by \cite{ren2020query2box}, we use two vectors to represent a box. One vector represents the center of the box and the other vector defines the offset. The center is the intersection of the diagonals. The offset is the vector that represents the size of each dimension of the box, so all the elements are non-negative values. Let $e_c: C \cup R \longrightarrow \mathbb{R}^n$ be the mapping function that maps each concept to the center of its box embedding and that maps each relation to its embedding. Let $e_o: C \longrightarrow \mathbb{R}^n$ be the mapping function that maps each concept to the n-dimension vector space as the offset of the box. The loss function for the first normal form, $C \sqsubseteq D$, aims to ensure that the box embedding of concept $C$ lies entirely within the box embedding of concept $D$. Figure \ref{dis1} illustrates two concepts $C$ and $D$ with their two box embedding $\beta (C)$ and $\beta (D)$. The red line indicates the difference between the center vectors: $| e_c(D)-e_c(C) |=(\delta x, \delta y) $ where $\delta x$ and $\delta y $ are two non-negative real number. In Figure \ref{dis2}, we show how the red line defined by $\delta x$ and $\delta y $ is computed as $| e_c(D)-e_c(C)| + e_o(C) - e_o(D) =(\delta x, \delta y) $. As shown in Figure \ref{dis3}, when both $\delta x$, $\delta y$ are $0$ or less than $0$, then $\beta (D)$ will contain $\beta (C)$. When we extend to higher dimensions, if the elements of difference vector (in two dimension is $(\delta x, \delta y)$) are all less or equal to $0$, then $\beta (C)$ is contained within $\beta (D)$. So the loss function of the first normal form, $C \sqsubseteq D$, and which ensures that $\beta(C)$ is contained within $\beta(D)$ is: \begin{equation} \begin{split} loss_{C \sqsubseteq D}(c,d) = &||max(zeros,\left|e_c(c)-e_c(d)\right|\\ &+e_o(c)-e_o(d)-margin)|| \\ \end{split} \end{equation} For all loss functions we use a margin vector. If all elements of margin vector are no larger than $0$, then $\beta (C)$ lies properly in $\beta (D)$. \subsection{Second Normal Form (NF2)} In the embeddings space, the second norm form $C\sqcap D \sqsubseteq E$ implies that the intersection of $\beta (C)$ and $\beta (D)$ is contained within $\beta (E)$. The key aim for the loss is to find the intersection of two boxes: $e_c(new)=(box_{min}+box_{max})/2 $, and $e_o(new)=\left|(box_{max}-box_{min})\right|/2$. It will be computed using the concepts $C$ and $D$ by equation \ref{left} and \ref{right}. We compute \begin{equation} box_{min} = max(e_c(C)-e_o(C),e_c(D)-e_o(D)) \label{left} \end{equation} and \begin{equation} box_{max} = min(e_c(C)+e_o(C),e_c(D)+e_o(D)) \label{right} \end{equation} from which we can obtain the center and offset of the intersection. For this new embedding representing the intersection of two concepts, we apply the same loss as for the first normal form (where concept $C$ from the first norm form is now the intersection of the concepts $C$ and $D$ in the second norm form). The loss function for the second normal form $C \sqcap D \sqsubseteq E$ will be: \begin{equation} \begin{split} loss_{C\sqcap D \sqsubseteq E}(c,d,e)=||max(zeros,|e_c(new)\\ -e_c(e)|+e_o(new)-e_o(e)-margin)|| \end{split} \end{equation} \subsection{Normal Forms with $R$ (NF3, NF4)} The first two normal forms do not include any quantifiers or relations. Every point that lies properly within a box representing a concept is an entity that lies in the extension of the concept (see Table \ref{tbl:el}), and we apply relations as transformations on these points. We use TransE \cite{bordes2013translating} to represent the relations between these entities. The losses in Equations \ref{nf3} and \ref{nf4} capture this intention; in particular, the extension of the concept $\exists R.D$ is the transformation of all entities in the extension of $D$ by $-e_c(R)$. \begin{equation} \begin{split} loss_{C \sqsubseteq \exists R.D}(c,d,r) =||max(zeros,|e_c(c) \\+e_c(r)-e_c(d)|+e_o(c)-e_o(d) -margin)|| \end{split} \label{nf3} \end{equation} \begin{equation} \begin{split} loss_{\exists R.C \sqsubseteq D}(c,d,r) =||max(zeros,|e_c(c) \\-e_c(r)-e_c(d)|-e_o(c)-e_o(d)-margin)|| \end{split} \label{nf4} \end{equation} \begin{figure}[H] \centering \includegraphics[width=0.5\textwidth,trim=60 400 100 50,clip]{family.pdf} \caption{Visualization of embeddings in the family domain.} \label{family} \end{figure} \subsection{Normal Forms with $\bot$ (NF5, NF6, NF7)} In $\mathcal{EL}^{++}$, the $\bot$ concept can only appear on the right-hand side of three of the normal forms: $C\sqcap D \sqsubseteq \bot$, $\exists R.C \sqsubseteq \bot$, and $C \sqsubseteq \bot$. Intuitively, the first normal form states that the concepts $C$ and $D$ are disjoint. The box embedding of the intersection of $C$ and $D$ can be calculated by Eqn. \ref{left} and \ref{right}. If at least one element in $box_{max}$ is less then the corresponding element in $box_{min}$, then there is no intersection and the loss is zero; otherwise, the loss is as Eqn. \ref{nf2Dis}: \begin{equation} \begin{split} loss_{C\sqcap D \sqsubseteq \bot}(c,d) = &||max(zeros,-\left|e_c(c)-e_c(d)\right|\\ &+e_o(c)+e_o(d)+margin)||\\ \end{split} \label{nf2Dis} \end{equation} The loss functions in Equations \ref{nf1Dis} and \ref{nf4Dis} capture the intuition that if a concept is unsatisfiable then its embedding should have no extensions; we use a very similar loss of the normal form where $\exists R.C$ is unsatisfiable due to our relation model based on linear transformations. \begin{equation} \begin{split} loss_{C \sqsubseteq \bot}(c) = ||e_o(c)|| \end{split} \label{nf1Dis} \end{equation} \begin{equation} \begin{split} loss_{\exists R.C \sqsubseteq \bot}(c,r) = ||e_o(c)|| \end{split} \label{nf4Dis} \end{equation} We also add negatives to improve the performance of our method: \begin{equation} \begin{split} loss_{C \not\sqsubseteq \exists R.D}(c,d,r) =||max(zeros,-|e_c(c)\\ +e_c(r)-e_c(d)|+e_o(c)+e_o(d)+margin)|| \end{split} \label{nf3neg} \end{equation} \subsection{Case Study: The Family Domain} We construct a simple knowledge base to test and understand the embeddings of our model. We use the family domain in which we generate a knowledge base that contains examples for each of the normal forms (Eqn. \ref{fam1}--\ref{famlast}). We chose margin $margin={0}$ and an embedding dimension of $2$ so that we can visualize the generated embeddings in $\Re^2$. As shown in Figure \ref{family}, ELBE can correctly model the relationship between each concepts, especially the intersection of two concepts. In the family domain, we can infer that $Mother$ is equivalent to the intersection of $Female$ and $Parent$, and $Father$ is equivalent to the intersection of $Male$ and $Parent$. \begin{eqnarray} \label{fam1} & Male & \sqsubseteq Person \\ & Female & \sqsubseteq Person \\ & Father & \sqsubseteq Male \\ & Mother & \sqsubseteq Female \\ & Father & \sqsubseteq Parent \\ & Mother & \sqsubseteq Parent \\ & Female \sqcap Male & \sqsubseteq \bot \\ & Female \sqcap Parent & \sqsubseteq Mother \\ & Male \sqcap Parent & \sqsubseteq Father \\ & \exists hasChild.Person & \sqsubseteq Parent \\ & Parent & \sqsubseteq Person \\ & Parent & \sqsubseteq \exists hasChild.\top \label{famlast} \end{eqnarray} \section{Experiments} In this section, we conduct extensive experiments to compare ELBE with state of the art methods by answering the following research questions: \begin{itemize} \item \textbf{RQ1}: Does the proposed box based method ELBE perform better than the state-of-the-art methods? \item \textbf{RQ2}: How does satisfying intersectional closure contribute to learning $\mathcal{EL}^{++}$ embeddings? \end{itemize} \begin{table*}[htbp] \renewcommand\arraystretch{1.35} \renewcommand\tabcolsep{5pt} \centering \begin{tabular}{l|r|r|r|r|r|r|r|r} \toprule \makecell[c]{Method} & \multicolumn{1}{l|}{H@10(R)} & \multicolumn{1}{l|}{H@10(F)} & \multicolumn{1}{l|}{H@100(R)} & \multicolumn{1}{l|}{H@100(F)} & \multicolumn{1}{l|}{MR(R)} & \multicolumn{1}{l|}{MR(F)} & \multicolumn{1}{l|}{AUC(R)} & \multicolumn{1}{l}{AUC(F)} \\ \midrule \makecell[c]{TransE(R)} & \makecell[c]{0.03} & \makecell[c]{0.05} & \makecell[c]{0.22} & \makecell[c]{0.27} & \makecell[c]{855} & \makecell[c]{809} & \makecell[c]{0.84} & \makecell[c]{0.85} \\ \makecell[c]{TransE(P)} & \makecell[c]{0.06} & \makecell[c]{0.13} & \makecell[c]{0.41} & \makecell[c]{0.54} & \makecell[c]{378} & \makecell[c]{330} & \makecell[c]{0.93} & \makecell[c]{0.94} \\ \makecell[c]{SimResnik} & \makecell[c]{0.08} & \makecell[c]{0.18} & \makecell[c]{0.38} & \makecell[c]{0.49} & \makecell[c]{713} & \makecell[c]{663} & \makecell[c]{0.87} & \makecell[c]{0.88} \\ \makecell[c]{SimLin} & \makecell[c]{0.08} & \makecell[c]{0.17} & \makecell[c]{0.34} & \makecell[c]{0.45} & \makecell[c]{807} & \makecell[c]{756} & \makecell[c]{0.85} & \makecell[c]{0.86} \\ \makecell[c]{EmEL++} & \makecell[c]{0.07} & \makecell[c]{0.17} & \makecell[c]{0.48} & \makecell[c]{0.65} & \makecell[c]{336} & \makecell[c]{291} & \makecell[c]{0.94} & \makecell[c]{0.95} \\ \makecell[c]{ELEm} & \makecell[c]{\underline{0.10}} & \makecell[c]{\underline{0.23}} & \makecell[c]{0.50} & \makecell[c]{\underline{0.75}} & \makecell[c]{\underline{247}} & \makecell[c]{\underline{187}} & \makecell[c]{\underline{0.96}} & \makecell[c]{\underline{0.97}} \\ \midrule \makecell[c]{\textbf{ELBE}} & \makecell[c]{\textbf{0.11}} & \makecell[c]{\textbf{0.26}} & \makecell[c]{\textbf{0.57}} & \makecell[c]{\textbf{0.77}} & \makecell[c]{\textbf{201}} & \makecell[c]{\textbf{154}} & \makecell[c]{\textbf{0.96}} & \makecell[c]{\textbf{0.97}} \\ \bottomrule \end{tabular}% \caption{\label{tbl:results-yeast} Prediction performance for yeast protein--protein interactions. } \end{table*}% \begin{table*}[htbp] \renewcommand\arraystretch{1.35} \renewcommand\tabcolsep{5pt} \centering \begin{tabular}{l|r|r|r|r|r|r|r|r} \toprule \makecell[c]{Method} & \multicolumn{1}{l|}{\makecell[c]{H@10(R)}} & \multicolumn{1}{l|}{\makecell[c]{H@10(F)}} & \multicolumn{1}{l|}{\makecell[c]{H@100(R)}} & \multicolumn{1}{l|}{\makecell[c]{H@100(F})} & \multicolumn{1}{l|}{\makecell[c]{MR(R)}} & \multicolumn{1}{l|}{\makecell[c]{MR(F)}} & \multicolumn{1}{l|}{\makecell[c]{AUC(R)}} & \multicolumn{1}{l}{\makecell[c]{AUC(F)}} \\ \midrule \makecell[c]{TransE(R)} & \makecell[c]{0.02} & \makecell[c]{0.03} & \makecell[c]{0.12} & \makecell[c]{0.16} & \makecell[c]{2262} & \makecell[c]{2189} & \makecell[c]{0.85} & \makecell[c]{0.85} \\ \makecell[c]{TransE(P)} & \makecell[c]{0.05} & \makecell[c]{0.11} & \makecell[c]{0.32} & \makecell[c]{0.44} & \makecell[c]{809} & \makecell[c]{737} & \makecell[c]{0.95} & \makecell[c]{0.95} \\ \makecell[c]{SimResnik} & \makecell[c]{0.05} & \makecell[c]{0.10} & \makecell[c]{0.23} & \makecell[c]{0.28} & \makecell[c]{2549} & \makecell[c]{2476} & \makecell[c]{0.83} & \makecell[c]{0.83} \\ \makecell[c]{SimLin} & \makecell[c]{0.04} & \makecell[c]{0.08} & \makecell[c]{0.19} & \makecell[c]{0.22} & \makecell[c]{2818} & \makecell[c]{2743} & \makecell[c]{0.81} & \makecell[c]{0.82} \\ \makecell[c]{EmEL++} & \makecell[c]{0.04} & \makecell[c]{0.13} & \makecell[c]{0.38} & \makecell[c]{0.56} & \makecell[c]{772} & \makecell[c]{700} & \makecell[c]{0.95} & \makecell[c]{0.95} \\ \makecell[c]{ELEm} & \makecell[c]{\underline{0.09}} & \makecell[c]{\underline{0.22}} & \makecell[c]{\underline{0.43}} & \makecell[c]{\underline{0.70}} & \makecell[c]{\underline{658}} & \makecell[c]{\underline{572}} & \makecell[c]{\underline{0.96}} & \makecell[c]{\underline{0.96}} \\ \midrule \makecell[c]{\textbf{ELBE}} & \makecell[c]{\textbf{0.09}} & \makecell[c]{\textbf{0.22}} & \makecell[c]{\textbf{0.49}} & \makecell[c]{\textbf{0.72}} & \makecell[c]{\textbf{434}} & \makecell[c]{\textbf{362}} & \makecell[c]{\textbf{0.97}} & \makecell[c]{\textbf{0.98}} \\ \bottomrule \end{tabular}% \caption{\label{tbl:results-human} Prediction performance for human protein--protein interactions.} \end{table*}% \subsection{Experimental settings} \paragraph{Datasets.} Following the well-established previous works \cite{kulmanov2019embeddings}, we use two real-world benchmark datasets to evaluate ELBE; the datasets are used to predict protein--protein interactions (PPIs) in yeast and humans. Each protein is associated with its biological functions as expressed using the Gene Ontology (GO) \cite{ashburner2000gene}, and interactions are predicted based on the biological hypothesis that proteins that are functionally similar are more likely to interact. We use the OWL representation of the datasets where proteins are instances, and if protein $P$ is associated with the function $F$, we add the axiom $\{ P \} \sqsubseteq \exists hasFunction.F$ (based on the ABox axiom $(\exists hasFunction.F)(P)$). We use 80\% of the total interacted protein pairs for model training, 10\% and 10\% for validation and testing, respectively. In addition, we generate a synthetic dataset to evaluate the performance of ELBE on the inference of equivalence concept axioms. The details of this task are in Section \ref{secEEC}. For generating the dataset, we choose the GO as the basic dataset, then randomly choose 2,131 axioms of NF2 ($C \sqcap D \sqsubseteq E$). Then, for each NF2 axiom we chose, we add the axioms $C \sqsubseteq E$ and $D \sqsubseteq E$ axioms to the dataset. The two NF1 axioms and one NF2 axiom form a triple that we use for the entailment of equivalence concepts. We randomly choose 1,000 of these triples for evaluation and use the rest for training the embeddings. \paragraph{Baselines} We compare ELBE with TransE \cite{bordes2013translating}, Resnik's similarity \cite{resnik1995using}, Lin's similarity \cite{harispe2015semantic}, EmEL++ \cite{mondala2021emel}, ELEm \cite{kulmanov2019embeddings}. For TransE, we use two representations, a native RDF-based rendering of the OWL knowledge base, and a ``plain'' representation based on OWL2Vec* \cite{chen2021owl2vec} transformation rules, to generate knowledge graph embeddings and use them for link prediction. For Resnik's similarity and Lin's similarity, we use the best-match average strategy for combining pairwise class similarities, then compute the similarity between each protein. For EmEL++ and ELEm, we predict whether axioms of the type ${P_1} \sqsubseteq \exists interacts.{P_2}$ hold. \paragraph{Implementation Details.} We implement ELBE using the Python library PyTorch\footnote{https://pytorch.org/} and conduct all the experiments on a Linux server with GPUs (Nvidia RTX 2080Ti) and Intel Xeon CPU. In the training phase, the initial learning rate of the Adam \cite{kingma2014adam} optimizer is tuned by grid searching within \{$1e^{-2}$, $5e^{-3}$, $1e^{-3}$, $5e^{-4}$\} for both tasks. We perform an extensive search for optimal parameters, testing embedding sizes for \{$25$, $50$, $100$, $200$, $400$\} and margin vectors for \{$-0.01$, $-0.05$, $-0.01$, $0$, $0.01$, $0.05$, $0.1$\}. The optimal set of key hyper-parameters for ELBE is $embedding\_size=50$, $margin={-0.05}$. For the PPI task, we evaluate the performance based on hit rate at ranks 10 (H@10) and 100 (H@100), mean rank (MR) and area under the ROC curve (AUC) and report both raw and filtered results (e.g., MR(F) indicates mean rank of the filtered result). For entailment of equivalent concepts, we evaluate the performance based on hit rate at ranks 1, 3, and 10, and the mean rank. You can see our code at github\footnote{https://github.com/bio-ontology-research-group/EL2Box\_embedding}. \subsection{Protein--Protein Interactions (RQ1)} We use the similarity-based function in Eqn \ref{sim1} for predicting PPIs. \begin{equation} \begin{split} \label{sim1} sim(P_1,interact,P_2) = -||max(zeros,|e_c(P_1) \\+e_c(interact)-e_c(P_2) |- e_o(P_1)-e_o(P_2))|| \end{split} \end{equation} For a query $P_1 \sqsubseteq \exists interacts.P_2$, we predict interactions of $P_2$ to all proteins from our training set and identify the rank of $P_1$. We compare the overall performance of ELBE with that of baselines to answer RQ1. The results are shown in Table \ref{tbl:results-yeast} for the yeast PPI dataset and in Table \ref{tbl:results-human} for the human PPI dataset. The results shows that ELBE consistently outperforms other baselines. \subsection{Entailment of Equivalence Concepts (RQ2)} \label{secEEC} ELBE outperforms other methods in our experiments, and we hypothesize this is due to the improved representation of concept intersections. We perform a more thorough analysis of ELBE's ability to represent and infer intersections. In the knowledge base based on GO, if there are three axioms of the form $E \sqsubseteq C$, $E \sqsubseteq D$ and $C\sqcap D \sqsubseteq E$, then we can infer (deductively) that $C \sqcap D \equiv E$. We perform an experiment to test whether ELBE is able to make these inferences within the embedding space. To the best of our knowledge, the current methods for $\mathcal{EL}^{++}$ embeddings are all based on geometric models based on $n$-balls; we used ELEm \cite{kulmanov2019embeddings} as representative. To do the entailment of equivalence concepts task, we predict which concept equals the intersection of two other concepts. Intuitively, we should calculate the intersection of concepts first and then compare the intersection to the embedding of each concept, and choose the closest one. However, ELEm only approximate the intersection and do not actually represent it; therefore, we use the center of the smallest $n$-ball containing the intersection as representation of the concept and choose the concept that has the closest center of its $n$-ball embedding. The similarity-based function for ELEm is in equation \ref{elemSim}. \begin{equation} \begin{split} h=\frac{r_{\eta}(C)^2-r_{\eta}(D)^2+||f_{\eta}(D)-f_{\eta}(C)||^2}{2||f_{\eta}(D)-f_{\eta}(C)||} \end{split} \end{equation} \begin{equation} \begin{split} k=\frac{h}{||f_{\eta}(D)-f_{\eta}(C)||} \end{split} \end{equation} \begin{equation} \begin{split} sim_{ball}(C,D,E)=|f_{\eta}(C)+k(f_{\eta}(D)-f_{\eta}(C))- f_{\eta}(E)| \end{split} \label{elemSim} \end{equation} In this similarity function, $r_{eta}$ and $f_{eta}$ are the radius and center of the $n$-ball of the ELEm. The similarity-based function for ELBE is in equation \ref{elbeSim}: \begin{equation} \begin{split} sim_{box}(C,D,E)=|(box_{min}+box_{max})/2-e_c(E)| \end{split} \label{elbeSim} \end{equation} The $box_{min}$, $box_{max}$ vectors can be calculated by Equations \ref{left} and \ref{right}. We evaluate the predictive performance based on recall at rank $1$, rank $3$, rank $10$, and mean rank. The results are shown in Table \ref{tbl:interClosure}. We find that ELBE outperforms ELEm in all metrics. When we consider only rank $1$ concepts as a result of ``reasoning'' within the embedding space, we find that ELBE improves substantially over ELEm and can perform inferences of equivalence accurately. In the test triples, ELBE can predict over 87\% of the equivalence axioms correctly, while ELEm can predict only 71\%. In other word, by satisfying the intersectional closure, ELBE can perform entailment of equivalence; this may also help ELBE to improve the general performance in other types of queries. \begin{table}[htbp] \renewcommand\arraystretch{1.3} \renewcommand\tabcolsep{5pt} \centering \caption{\label{tbl:interClosure} Performance for entailment of equivalence concepts tasks.} \begin{tabular}{l|r|r|r|r} \toprule \makecell[c]{Method} & \multicolumn{1}{l|}{\makecell[c]{H@1}} & \multicolumn{1}{l|}{\makecell[c]{H@3}} & \multicolumn{1}{l|}{\makecell[c]{H@10}} & \multicolumn{1}{l}{\makecell[c]{MR}} \\ \midrule \makecell[c]{ELEm} & \makecell[c]{0.710} & \makecell[c]{0.896} & \makecell[c]{0.969} & \makecell[c]{3.561} \\ \makecell[c]{ELBE} & \makecell[c]{\textbf{0.871}} & \makecell[c]{\textbf{0.974}} & \makecell[c]{\textbf{0.985}} & \makecell[c]{\textbf{3.470}} \\ \bottomrule \end{tabular}% \vspace{-0.3cm} \end{table}% \section{Conclusions} We developed ELBE, an embedding model for $\mathcal{EL}^{++}$ ontologies based on $n$-boxes. In experiments with two datasets from the biomedical domain as well as one synthetic dataset, we demonstrated that ELBE outperforms other $\mathcal{EL}^{++}$ embeddings, knowledge graph embeddings, and semantic similarity measures. When comparing with other geometric embeddings of $\mathcal{EL}^{++}$ ontologies, ELBE solves the intersectional closure problem and therefore performs better in the entailment of equivalent concepts axioms. Solving the intersectional closure problem is a crucial step towards establishing a correspondence between vector space embeddings and models of axiomatic theories. \section{Future Work} One limitation of ELBE is the use of TransE as model for relations. TransE can only deal with one-to-one relations, while one-to-many and many-to-many relations are important for accurately embedding ontologies. Furthermore, TransE is a linear transformation model; consequently, some of our loss functions (in particular $loss_{\exists R.C \sqsubseteq \bot}$) are insufficient to capture the $\mathcal{EL}^{++}$ semantics. In future work, we will explore more expressive relation models for $\mathcal{EL}^{++}$ embedding to solve these limitations. \clearpage \small \bibliographystyle{named}
{'timestamp': '2022-03-01T02:59:43', 'yymm': '2202', 'arxiv_id': '2202.14018', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.14018'}
arxiv
\section{Introduction} \label{sect:intro} Shannon's pioneering work \cite{Shannon48} established that the highest code-rate that a channel can support is achieved as the code becomes long. Since 1978, however, it has been known that optimally accurate Maximum Likelihood (ML) decoding of linear codes is an NP-complete problem \cite{berlekamp1978inherent}. Taken together, those results have driven the engineering paradigm of co-designing significantly restricted classes of linear code-books in tandem with code-specific decoding methods that exploit the code-structure to enable computationally efficient approximate-ML decoding \cite{lin2004error} for long, high-redundancy codes. For example, Bose-Chaudhuri-Hocquenghem (BCH) codes with hard detection Berlekamp-Massey decoding \cite{berlekamp1968algebraic,massey1969shift}, Turbo codes with soft detection iterative decoders \cite{turbo:code}, Low Density Parity Check Codes (LDPCs) \cite{gallager1963low} with soft detection belief propagation decoding~\cite{ldpc97,fossorier1999reduced}, and the recently proposed CRC-Assisted Polar (CA-Polar) codes, which will be used for all control channel communications in 5G New Radio \cite{3gpp38212}, with soft detection CRC-Assisted Successive Cancellation List (CA-SCL) decoding~\cite{KK-CA-Polar,TV-list,llr-ca-scl,leonardon2019fast, 7114328, 6823099, 9186729, 8361464, 7471817, 9020375} and some alternate candidates \cite{9195233, 9613535, 9613577}. Contemporary applications, including augmented and virtual reality, vehicle-to-vehicle communications, machine-type communications, and the Internet of Things, have driven demand for Ultra-Reliable Low-Latency Communication (URLLC) \cite{durisi2016toward,she2017radio,chen2018ultra,parvez2018survey,medard20205}. As realizing these technologies requires shorter codes, the computational complexity issues associated with long codes will be vacated in delivering URLLC, offering the opportunity to revisit the possibility of creating high-accuracy near-optimal universal decoders. The development of practical universal decoders would open up a massively larger palette of potential code-books that can be decoded with a single algorithmic instantiation, greatly reducing hardware footprint, future-proofing devices against the introduction of new codes, and enabling the flexibility for each application to select the most suitable code-book. Key to unlocking that promise is the development of algorithms that are inherently suitable for efficient implementation in circuits. One potential approach is the recently introduced Guessing Random Additive Noise Decoding (GRAND). Originally established for hard decision demodulation systems \cite{Duffy18,kM:grand}, GRAND provides ML decodings for any moderate redundancy block-code construction. It does so by sequentially removing putative noise-effects, ordered from most likely to least likely based on a statistical channel model, from the demodulated received sequence and querying if what remains is in the code-book. The first instance where a code-book member is found is the decoding. Pseudo-code for GRAND can be found in Algorithm \ref{fig:grand_alg}. \floatstyle{spaceruled \restylefloat{algorithm \begin{breakablealgorithm} \caption{Guessing Random Additive Noise Decoding. Inputs: a demodulated channel output $y^n$; a code-book membership function such that $\code-book(y^n)=1$ if and only if $y^n$ is in the code-book; and optional statistical noise characteristics or soft information, $ \Phi $. Output: decoded element $c^{n,*}$; and the number of code-book queries made, $ D $, a measure of confidence in the decoding.} \label{fig:grand_alg} \begin{algorithmic} \STATE {\bf Inputs}: Code-book membership function $C: \{0,1\}^n \mapsto \{0,1\}$; demodulated bits $y^n$; optional information $\Phi$. \STATE {\bf Output}: Decoding $c^{n,*}$, soft output $D$ \STATE $d\leftarrow 0$, $D\leftarrow 0$. \WHILE {$d=0$} \STATE $z^n\leftarrow$ next most likely binary noise effect sequence (which may depend on $\Phi$) \STATE $D\leftarrow D+1$ \IF{$\code-book(y^n\ominus z^n) = 1$} \STATE $c^{n,*}\leftarrow y^n\ominus z^n$ \STATE $d\leftarrow 1$ \ENDIF \ENDWHILE \STATE{\bf return} $c^{n,*}$, $D$ \end{algorithmic} \hrule \end{breakablealgorithm} Consider an arbitrary block code of rate $R=k/n$ consisting of $M=2^k$ binary strings of length $n$, $\mathcal{C}_n=\{c^{n,1},\ldots ,c^{n,M}\}$. With $c^n$ being a transmitted code-word, $y^n$ denoting the hard decision demodulation, $Z^n$ denoting an independent binary additive noise-effect on the binary sequence, and $\oplus$ denoting addition in $\mathbb {F}_2$, we have $y^n = c^n \oplus Z^n$. A maximum likelihood decoding satisfies \begin{align*} c^{n,*} &= \arg\max_{i\in\{1,\ldots,M\}} P(y^n|c^{n,i}) \\ & = \arg\max_{i\in\{1,\ldots,M\}} P\left(Z^n = y^n\oplus c^{n,i}\right). \end{align*} Even for short codes, na\"ive brute force identification of such a $c^{n,*}$ is not possible as it requires $M=2^k$ computations for each decoding. By rank-ordering putative noise-effects in decreasing order of likelihood and breaking ties arbitrarily, i.e. determining the sequences $\{z^{n,i}\in\{0,1\}^n\}$ such that $P\left(Z^n = z^{n,i}\right) \geq P\left(Z^n = z^{n,j}\right)$ for all $i<j$, subtracting them from the demodulated received sequence in that order and querying if what remains, $y^n\oplus z^{n,i}$, is in the code-book, the first such $z^{n,*}$ is an ML decoding so long as noise-effects are queried in decreasing order of likelihood, even for channels with memory in the absence of interleaving \cite{kM:grand, grand-mo}. The simplicity of GRAND's hard detection operation and the evident parallelizability of its code-book queries have already resulted in the proposal \cite{abbas2020, abbas2021high-MO} and realization \cite{Riaz21} of efficient circuit implementations. The VLSI designs in \cite{abbas2020, abbas2021high-MO} focus on maximizing throughput and minimizing worst-case latency by parallelization. The taped-out realization \cite{Riaz21} provides a universal 128-bit hard decoder chip with class-leading measurements of precision, latency and energy per bit. GRAND algorithms have two core components: a code-book membership checker and a sequential putative noise-effect sequence generator. The former is common to all GRAND variants. If the code is unstructured and stored in a dictionary, a code-book query corresponds to a tree-search with a complexity that is logarithmic in the code-length. If the code is a Cyclic Redundancy Check (CRC) code, which is typically only used for error detection, checking for code-book membership requires a simple polynomial calculation. If the code is linear in any finite field, code-book membership can be determined by a matrix multiplication and comparison. Instead it is the putative noise-effect sequence generator that differs with each variant in light of statistical or per-realization information on channel characteristics. Incorporating soft detection information into decoding decisions is known to significantly improve accuracy \cite{Coo88,KNH97,GS99}. Doing so requires that additional quantized soft information be passed from the receiver to the decoder and, for GRAND, the development of an appropriate noise-effect pattern generator that can accurately and efficiently create noise-effect sequences in order of decreasing likelihood in light of that soft information. Symbol Reliability GRAND (SRGRAND) \cite{Duffy19a,Duffy21} is a variant that avails of the most limited quantized soft information where one additional bit tags each demodulated symbol as being reliably or unreliably received. SRGRAND retains the desirable parallelizability of the original algorithm, is readily implementable in hardware, and provides a $0.5-0.75$ dB gain over hard-detection GRAND \cite{Duffy21}. At the other extreme, Soft GRAND (SGRAND) \cite{solomon20} is a variant that uses real-valued soft information per demodulated bit to build a dedicated noise-effect query order for each received signal. Using dynamic max-heap data structures, it is possible to create a semi-parallelizable implementation in software and, being a true soft-ML decoder, it provides a benchmark for optimal decoding accuracy performance. However, SGRAND's execution is algorithmically involved and does not lend itself to hardware implementation. Here we develop Ordered Reliability Bits GRAND (ORBGRAND), which bridges the gap between SRGRAND and SGRAND by obtaining the decoding accuracy of the latter in an algorithm that is, by design, suitable for implementation in circuits. A preliminary version of ORBGRAND that provides near-ML performance for arbitrary length, moderate-redundancy codes and block error rates (BLER) greater than $10^{-3}$ was presented at IEEE ICASSP in 2021 \cite{duffy2021ordered}. Its promise for a highly parallelized hardware realization has already resulted in VLSI architectures being proposed \cite{abbas2021high, condo2021high, condo2021fixed} and it has been used to investigate the suitability of both existing and non-traditionally structured codes for use in URLLC \cite{Papadopoulou21, grand-crc}. Here we explain the rationale behind ORBGRAND's design and expand on the preliminary conference version to generate near-ML performance for higher SNR. In the process, we describe an efficient algorithm that is suitable for hardware implementation, and establish performance. The rest of this paper is organized as follows. Section \ref{sec:relwork} provides a brief overview of practical short codes and other approaches to universal soft detection decoding. Section \ref{sect:theOrb} presents the rationale behind ORBGRAND and its practical implementation, which leads to the basic and full versions of ORBGRAND. Performance evaluation results that demonstrate ORBGRAND's effectiveness are presented in Section \ref{sect:simulation}. Section \ref{sect:summary} closes with final remarks. \section{Related work} \label{sec:relwork} In the quest to identify short code solutions, new low-latency applications have placed renewed focus on conventional codes \cite{short_fec, bch_m2m, fec_wireless} such as Reed-Solomon Codes\cite{ReedSolo} and BCH codes\cite{journals/iandc/BoseR60a}. Soft detection decoders offer a non-trivial decoding performance gain over hard decoders \cite{lin2004error}, which will be especially necessary for short, high-rate codes. However, many traditional codes do not have corresponding soft decoders. Some state-of-art codes with dedicated soft decoders, such as Turbo and LDPC codes, can reach near Shannon-capacity performance with long codes, but their performance degrades when used with short, high-rate codes. Notably, Polar codes, which were the first non-random codes that were mathematically established to be capacity-achieving~\cite{Arikan09}, have received significant attention. Owing to their poor performance at practical block-lengths \cite{arikan2009performance,pfister2014brief,sarkis2015fast}, however, they have not been adopted on their own. Instead, a concatenated design has been proposed where a CRC is first added to the data, which is then Polar coded, resulting in CA-Polar codes. These codes are usually decoded with a list decoding approach where a collection of candidate Polar code-words is first determined, and then a code-word that satisfies the CRC is selected~\cite{KK-CA-Polar,TV-list,llr-ca-scl,leonardon2019fast}. As they can be constructed at short block-lengths and have an efficient soft detection decoder, CA-Polar codes have been adopted for use for all control channel communications in the 5G New Radio standard \cite{3gpp38212}. Considered as a single code, a CA-Polar code is itself a linear code, albeit one that has no dedicated decoder. As a result, GRAND algorithms have previously established that there is additional performance left to be squeezed of out of them \cite{grand-crc}. An alternate approach to designing code-specific decoders is to instead develop a universal decoder. One class of soft detection decoders that can decode any binary linear code, which works on a list-decoding principle, has been substantially investigated \cite{dorsch1974decoding,FL95,gazelle1997reliability,VF04,wu2006soft,baldi2016use,Yue21order}. In Ordered Statistics Decoding (OSD), rather than compute the conditional likelihood of the received signal for all members of the code-book, instead the computation is done for a restricted list of candidate code-words that is hoped to contain the transmitted one. The algorithm permutes the columns of the parity check matrix in a manner that depends on the received signal reliability and Gaussian elimination is then performed to rewrite the generator matrix in systematic format, subject to checks that ensure a basis is identified, so that the systematic element of the code is based on the most reliable bits. Treating the code as a hash, a candidate list of code-words is determined by placing a ball of fixed Hamming distance around the reliable bits, and completing them with the hash. Transforming elements of this list back into the original basis, maximum likelihood decoding is performed on the restricted list. To achieve approximate-ML decoding performance, multiple stages of reprocessing are required, making it a challenge to implement the algorithm efficiently in hardware, especially for high throughput designs \cite{Papadopoulou21}. ORBGRAND inherits GRAND's potential for a highly parallelized implementation suitable for either high throughput applications or ultra-low power for use in battery-operated devices. Leaving the code-book checker unchanged, core to ORBGRAND is a new noise-effect pattern generator that incorporates per-realization soft information in a manner that lends itself to efficient hardware implementation, as explained in the following sections. \section{ORBGRAND} \label{sect:theOrb} We first introduce the principle behind ORBGRAND's design, before explaining how the basic and full variants are implemented. \subsection{ORBGRAND Principles} \label{sub:principle} An $n$-bit binary block code-word $c^n\in\{0,1\}^n$, is modulated to $\text{mod}(c^n)\in\{-1,1\}^n$ by $\text{mod}(c_i) = 2c_i-1$, transmitted and impacted by independent continuous additive noise, $N^n\in \mathbb {R}^n$, resulting in a random received signal $Y^n = \text{mod}(c^n)+N^n$, from which the hard decision sequence $y^n = \text{demod}(Y^n)$, an estimate of $c^n$, is obtained. The noise effect is the difference between what the transmitted binary codeword and the demodulated received signal, $Z^n = c^n \ominus y^n$. All GRAND algorithms make queries to identify the noise effect, $Z^n$, rather than the original continuous noise on the channel $N^n$. With the log-likelihood ratio defined as \begin{align*} \text{LLR}(Y_i) = \log {\frac{P(Y_i| c_i = 1)}{P(Y_i|c_i =0)}}, \end{align*} the hard detection $y_i$ is obtained from $Y_i$ by $y_i = (\text{sign}(\text{LLR}(Y_i))+1)/2$, and $L{i}$ is referred to as the reliability of $y_i$. While there are many ways to quantitatively capture the soft information in $Y^n$, for ORBGRAND it is instructive to first represent it as a sequence, $B^n=(B_1,B_2,\ldots ,B_n)$, where $B_i$ is the {\it a posteriori} probability that the hard decision bit $y_i$ is in error, which can be written as \begin{align*} B_i &= P(y_i \neq c_i|Y_i) = \frac{P(y_i \neq c_i, Y_i)}{P(Y_i)} \\ &= \frac{P(y_i \neq c_i, Y_i)/P(y_i = c_i, Y_i)}{1 + P(y_i \neq c_i, Y_i)/P(y_i = c_i, Y_i)}, \end{align*} and so $B_i$ can be expressed in terms of the bit reliabilities as \begin{align} \label{eq:B_llr} B_i = \frac{e^{-L{i}}}{1 + e^{-L{i}}} \in[0,1/2], \end{align} where $B_i$ is monotonically decreasing with $L{i}$. From $B^n$ we can evaluate the {\it a posteriori} probability of a binary noise-effect sequence $z^n$, \begin{align*} & P(Z^n=z^n) \\ &=\prod_{i:z_i=0} (1-B_i) \prod_{i:z_i=1} B_i \nonumber = \prod_{i=1}^n (1-B_i) \prod_{i:z_i=1} \frac{B_i}{1-B_i} \nonumber \\ &\propto \prod_{i:z_i=1} \frac{B_i}{1-B_i} = \exp\left(-\sum_{i=1}^n L{i}z_i\right). \end{align*} Therefore, up to a constant shared by all sequences, the likelihood of a putative noise effect sequence $z^n$ is determined by the sum of the reliabilities of hard-detected bits being flipped, $\text{Rel}(z^n)= \sum_{i=1}^n L{i} z_i$. To rank order putative noise sequences, $z^n$, in decreasing likelihood, it is, therefore, sufficient to rank order them by increasing reliability sum, $\text{Rel}(z^n)$. If no soft information is available, by defining $L{i}$ to be an arbitrary positive constant for all $i$, $\text{Rel}(z^n)$ is proportional to the Hamming Weight of $z^n$, $w_\text{H}(z^n)=\sum_{i=1}^n z_i$. In this case, putative noise sequences would be rank ordered in increasing Hamming weight, as used in the original hard detection GRAND for a binary symmetric channel. SRGRAND filters $L{i}$, setting it to be $+\infty$ if it is above a threshold and to a positive constant if below that threshold, resulting in putative noise sequences being be rank ordered in increasing Hamming weight within the masked region of finite reliability bits. Armed with $\{L{i}:i\in\{1,\ldots,n\}\}$, true soft ML decoding is achieved by SGRAND \cite{solomon20} using a dynamic algorithm that recursively generates a max-heap for each set of reliabilities to generate $z^n$ with increasing $\text{Rel}(z^n)$. Our goal with ORBGRAND is to obtain comparable performance with an algorithm that is amenable to efficient implementation by design. For notational simplicity, we shall assume that the reliabilities, $\{L{i}:i\in\{1,\ldots,n\}\}$, happen to be received in increasing order of bit position, so that $L{i}\leqL{j}$ for $i\leq j$. In practice, for each received block we sort the reliabilities and store the permutation, $\pi^n=(\pi_1,\ldots,\pi_n)$, such that $\pi_i$ records the received order index of the $i^\text{th}$ least reliable bit. The permutation $\pi^n$ enables us to map all considerations back to the original order that the bits were received in. The core of the approach underlying ORBGRAND is the development of statistical models of the non-decreasing sequence $\{L{i}:i\in\{1,\ldots,n\}\}$ that are accurate, robust, and lead to computational efficient algorithms for generating rank ordered putative noise sequences. The approach can be most readily understood with the example of a channel using BPSK modulation that is subject to Additive White Gaussian Noise (AWGN), where $\text{LLR}(Y) \propto Y$. As constants of proportionality will prove to have no impact on ORBGRAND's order, from here on we will refer to $\absorbLLR{i}=|Y_i|$ as the reliability of the $i$-th bit. Sample rank ordered reliability values $\{\absorbLLR{i}:i\in\{1,\ldots,n\}\}$ are plotted in Fig. \ref{fig:ordered_rlbl} for various SNRs. \begin{figure}[htbp] \centerline{\includegraphics[width=0.45\textwidth]{ordered_rlbl2}} \caption{Samples of ordered reliability of 512-bit sequences in AWGN channel with given SNRs.} \label{fig:ordered_rlbl} \end{figure} At lower SNR, the reliability curve is near linear with a zero intercept, while for high SNR the intercept is non-zero and there is notable curvature, particular for the least reliable bits, which are most significant for generating an accurate query order. Different levels of approximation to the reliability curve lead to distinct decoding complexity and performance, as will be explored in the following sections. \subsection{Basic ORBGRAND - The Low SNR Model} \label{sub:basicorb} The simplest statistical model, $\relest^n$, for the reliability curve is a line through the origin with slope $\beta>0$, \begin{align} \relest_i = \beta\, i \text{,~for~} i=1, 2, \ldots, n. \label{eq:llr2i} \end{align} This model is illustrated by the dashed line in Fig. \ref{fig:ordered_rlbl}, where it can be seen to provide a good approximation at lower SNR. For the zero-intercept linear model, \begin{align} \label{eq:lw1} \text{Rel}(\sort{z}^n) \approx \sum_{i:\sort{z}_i=1} \relest_i = \beta \sum_{i=1}^n i z_i = \beta w_\text{L}(\sort{z}^n), \end{align} where we define is the sum of the positions that are flipped in $z^n$ \begin{align} \label{eq:lw} w_\text{L}(z^n)=\sum_{i=1}^n i z_i, \end{align} to be the {\it Logistic Weight} of the binary sequence $z^n$. Thus, in this model the likelihoods of putative noise effect sequences are ordered in increasing logistic weight and hence the value of $\beta$ need not be estimated. As a result, for any $\beta$, the first putative error sequence always corresponds to no bits being flipped, which has $w_\text{L}=0$. The second query corresponds to $\sort{z}^n$ with the least reliable bit flipped, having $w_\text{L}=1$. The third corresponds to only the second least reliable bit of $\sort{z}^n$ flipped, which has $w_\text{L}=2$. The next query is either the noise-effect where only the third least reliable bit is flipped, or the one where the least reliable and second least reliable bits are both flipped, both having $w_\text{L}=3$, with the tie broken arbitrarily. The ordering proceeds in that fashion as illustrated in Fig. \ref{fig:basic_orb_pat}, which describes the noise-effect sequence generator in basic ORBGRAND \cite{duffy2021ordered}. Thus, for its operation, ORBGRAND based on this statistical model only requires the permutation recording the positions of the rank ordered reliabilities of the received bits, $\pi^n$, from which the algorithm proceeds deterministically. \begin{figure}[ht] \begin{center} \includegraphics[width=0.38\textwidth]{basic_orb_pat} \end{center} \caption{First 100 ORBGRAND noise effect queries where bit positions are in increasing order of hard-detection reliability. Each row is a noise sequence with white being no bit flip and black corresponding to a bit flip.} \label{fig:basic_orb_pat} \end{figure} Note that for a binary string of length $n$, the maximum logistic weight is achieved by the sequence of all $1$s giving $w_\text{L}(1,\ldots,1)=n(n+1)/2$, and so what remains to do for basic ORBGRAND is to develop an efficient algorithm that sequentially generates putative noise sequences in terms of increasing logistic weight. To do so, we must be able to identify all allowable noise-effect sequences for each given logistic weight $W\in\{0,\ldots, n(n+1)/2\}$, \begin{align} \label{eq:znwl} \cS_W = \left\{\sort{z}^n \in\{0,1\}^n: w_\text{L}(\sort{z}^n) =W\right\}. \end{align} That objective can be fractionated by conditioning on the Hamming weight, $w$, of the sequences, giving \begin{align} &\cS_W = \label{eq:fractionation}\\ & \bigcup_{w=1}^{\lfloor (\sqrt{1+8W}-1)/2\rfloor} \left\{\sort{z}^n \in\{0,1\}^n: w_\text{H}(\sort{z}^n)=w, w_\text{L}(\sort{z}^n) =W\right\}, \nonumber \end{align} where the upper-bound on the union stems from the fact that if the Hamming weight of $\sort{z}^n$ is $w$, the smallest logistic weight that $\sort{z}^n$ can have is from the sequence with flipped bits in the first $w$ positions of $\sort{z}^n$, giving a logistic weight of $w_\text{L}(z^n) = w(w+1)/2 \leq W$. Consider a single set in the union in Eq. \eqref{eq:fractionation} for Hamming weight $w$. Determining \begin{align*} \left\{\sort{z}^n \in\{0,1\}^n: w_\text{H}(\sort{z}^n)=w, w_\text{L}(\sort{z}^n) =W\right\} \end{align*} is equivalent to finding all integer-valued vectors of length $w$ satisfying \begin{align} \left\{v^w \in\mathbb {N}^w : 1\leq v_1<\ldots <v_w\leq n, \sum_{i=1}^w v_i =W\right\}, \label{eq:intpart} \end{align} where $v^w$ contains the indices of the flipped bits in $\sort{z}^n$, which amounts to finding all integer partitions of $W$ of size $w$ with non-repeating positive parts subject to a maximum value of $n$. By setting \begin{align} v_i = i + u_i, \text{~for~}i=1, 2, \ldots, w, \label{eq:vu} \end{align} it is possible to reformulate the set in Eq. \eqref{eq:intpart} in one final way in terms of the $u_i$, as the integer partitions of $W'=W-w(w+1)/2$ into $w$ not-necessarily distinct, non-negative parts no larger than $n'=n-w$ \cite{Yaglom1964}. That is, determining all the elements in the set Eq. \eqref{eq:intpart}, is equivalent to finding all integer vectors $u^w$ such that \begin{equation} \left\{ u^w \in\mathbb {N}^w : 0 \leq u_1 \leq u_2 \leq \ldots \leq u_w\leq n', \sum_{i=1}^w u_i =W' \right\}. \label{eq:intpart2} \end{equation} Here we introduce an efficient algorithm for determining all sequences that are in the partition, which is suitable for implementation in hardware. It will form an essential component of the full ORBGRAND, which uses a more sophisticated model than described in Eq. \eqref{eq:llr2i}. \subsection{Integer Partition Pattern Generator} \label{subsec:land} Integer partitions can be represented by diagrams \cite{Cameron2001} as illustrated in Fig. \ref{fig:part_diag}, where each column represents an integer part with its value, $u_i$, equaling to the number of cells in the column and the total number of cells in the diagram equaling the integer to be partitioned $\sum_i u_i$. Here we use a mirror image of a Ferrers Diagram, where the parts are listed in the increasing order to assist in the description of the algorithm. \begin{figure}[ht] \begin{center} \includegraphics[width=0.38\textwidth]{part_diag} \end{center} \caption{Procedure for partitioning $W'=8$ into $w=4$ non-negative, non-decreasing parts, each no larger than $n'=4$. The upward arrow indicates the corresponding part is to be increased by 1 in the next step. (c) and (e) mark the values of $d(i)$ and $D(i)$ for $1\leq i \leq 4$.} \label{fig:part_diag} \end{figure} A function $d:\{1,\ldots, w\}\mapsto\{0,\ldots,W'\}$ records the ``drop'' between adjacent $i$, $i+1$ parts \begin{align*} d(i) = \begin{cases} 0 & \text{ if } i=w\\ u_{i+1}-u_i & \text{ if } i\in\{1,\ldots,w-1\}\\ \end{cases} \end{align*} from which the accumulated drop function is defined by $D(i) = \sum_{j=i}^wd(j)$, where $D(1)$ records the total drop in the integer partition $u^w$. Examples of $d(i)$ and $D(i)$ are shown in Fig. \ref{fig:part_diag} (c) and (e). Fig. \ref{fig:part_diag} (a) represents an extreme case in which the minimum number of non-zero integer parts is achieved by pushing cells to the right with part values maximized. Another extreme case is that cells are spread to maximum number of parts achieving the minimum number of rows, or equivalently, satisfying $D(1) \leq 1$, as illustrated in Fig. \ref{fig:part_diag} (h). All partitions for the setting of $W'=8$, $w=4$ and $n'=4$ are obtained in the migration procedure from (a) to (h), which can be accomplished with the Landslide algorithm presented in Algorithm \ref{alg:land}. The algorithm heavily relies on the Build-mountain routine, in which a partial partition is performed to push unallocated cells to the right-most parts, akin to building the steepest, highest mountain allowable on the right side of the diagram. For example, in Fig. \ref{fig:part_diag} (e), $u_1=1$ is determined from step (d), the remaining 7 cells are to be assigned to $u_2$, $u_3$ and $u_4$. The assignment can be accomplished by first making $u_2$, $u_3$ and $u_4$ identical to $u_1=1$, and then assigning the remaining 4 cells to the right-most parts, with $u_4$ maximized and $u_3$ increased by 1. In general, when the values of $\{u_1,u_2, \ldots, u_k \}$ have been specified, the allocation of the remaining cells to $\{u_{k+1},u_{k+2}, \ldots, u_w \}$, or the Build-mountain routine, is carried out as follows: \begin{enumerate} \item $u_i \gets u_k$, for $k+1 \leq i\leq w$ \item $W'' \gets W'-\sum_{i=1}^{w}u_i$ \item Obtain $q$ and $r$ such that $W'' = q(n'-u_k) + r$ \item if $q \neq 0$, $u_i \gets n'$, for $w-q+1 \leq i \leq w$ \item $u_{w-q} \gets u_{w-q} + r$ \end{enumerate} The initial partition in Fig. \ref{fig:part_diag} (a) is obtained with the same method by simply assuming a dummy part $u_0=0$. With the Build-mountain routine explained, the Landslide algorithm is described as in Algorithm \ref{alg:land}. \floatstyle{spaceruled \restylefloat{algorithm \begin{breakablealgorithm} \caption{The Landslide Algorithm} \label{alg:land} \begin{flushleft} \textbf{Input:} $W'$, $w$, $n'$ \newline \textbf{Output:} $\{u^{w,j}, j=1, 2, \ldots\}$ \end{flushleft} \begin{algorithmic}[1] \STATE Build-mountain for initial partition \STATE $j \gets 1$ \STATE $u^{w, j} \gets u^w$ \STATE Update $D(i)$ for $1 \leq i \leq w$ \WHILE{$D(1) \geq 2$} \STATE Locate the largest $k$ such that $D(k) \geq 2$ \STATE $u_k \gets u_k+1$ \STATE Build-mountain from $u_k$ \STATE Update $D(i)$ for $1 \leq i \leq w$ \STATE $j \gets j+1$ \STATE $u^{w, j} \gets u^w$ \ENDWHILE \STATE Return $\left\{u^{w,1}, u^{w,2}, u^{w,3}, \ldots \right\}$ \end{algorithmic} \end{breakablealgorithm} Using the same example from Fig. \ref{fig:part_diag}, the procedure of the Landslide algorithm is illustrated in Algorithm \ref{alg:land}, along with the mapping from partition $u^{w,i}$ to $v^{w,i}$ according to Eq. \eqref{eq:vu}. The diagram indicates the potential for efficient implementation of the Landslide algorithm. While one routine generates partitions for one Hamming weight $w$ at a time, multiple parallel routines can generate partitions for different Hamming weights, providing sufficient noise-effect sequences for highly-parallelized code-book checking. \begin{figure}[htbp] \centerline{\includegraphics[width=0.49\textwidth]{int_part}} \caption{The Landslide algorithm is applied to achieve partitioning $W=18$ into $w=4$ distinguished parts with maximum value of $n=8$; The partition problem is first converted to partitioning $W'=8$ into $w=4$ repeatable parts with maximum value of $n'=4$; Mapping from the latter partition to the former one is simply achieved by adding 1, 2, 3, 4 individually} \label{fig:land} \end{figure} \subsection{The full ORBGRAND Algorithm} \label{sub:fullORB} The zero-intercept, linear statistical model for rank-ordered bit reliabilities that underpins basic ORBGRAND in Eq. \eqref{eq:llr2i} requires no input beyond a rank ordering of received hard-detection bits by increasing reliability and provides a good approximation to the reliability curve in low SNR conditions. It is, however, evidently a poor description at higher SNR in Fig. \ref{fig:ordered_rlbl}. That mismatch results in basic ORBGRAND's query order diverging from true likelihood order at higher SNR, with corresponding performance loss. By expanding the statistical model used to describe the reliability data to a piece-wise linear one for full ORBGRAND, we retain the algorithmic efficiencies of generating integer partition sequences while improving block error rate performance at higher SNR. As illustrated in Fig. \ref{fig:single_line}, with $I_0=0$ and $I_m=n$, the $m$-segment statistical model curve is represented as \begin{align} \label{eq:relest_seg} \relest_j = J_{i-1}+\beta_i(j-I_{i-1}) \text{,~for~} I_{i-1}<j \leq I_i, \end{align} where $1 \leq i \leq m$ is the segment index. The anchor indices $\{I_i: i\in\{0, 1, \ldots, m\}\}$ define the domain of each segment, while $J_{i-1} \in\mathbb {Z}$ and $\beta_i\in\mathbb {N}$, respectively, determine the initial value and slope of the $i$-th segment. That $J_{i-1}$ and $\beta_i$ are restricted to being integers is crucial to enabling efficient algorithmic implementation producing rank ordered putative noise sequences, and results will demonstrate that no loss in performance results from this constraint. The model used for basic ORBGRAND, Eq. \eqref{eq:llr2i}, is a special case of Eq. \eqref{eq:relest_seg} with $m=1$, $I_1=n$ and $J_0=0$. \begin{figure}[htbp] \centerline{\includegraphics[width=0.38\textwidth]{single_line}} \caption{Full piece-wise linear statistical model to the ordered reliability curve used in ORBGRAND, with the start and end indices indicated for the $i$-th segment.} \label{fig:single_line} \end{figure} The approximate reliability sum of $z^n$, namely the reliability weight, based on the full model is then \begin{align*} \text{Rel}(\sort{z}^n) & \approx\sum_{i:\sort{z}_i=1}\relest_{i} = \sum_{i=1}^n \relest_{i}z_i = \sum_{i=1}^m\sum_{j=I_{i-1}+1}^{I_i} \relest_{j}z_j \\ &= \sum_{i=1}^m J_{i-1}w_\text{H}{(z_{I_{i-1}+1}, \ldots z_{I_i})} \\ &+\sum_{i=1}^m \beta_i w_\text{L}{(z_{I_{i-1}+1}, \ldots z_{I_i})} \in\mathbb {Z}_+, \end{align*} and the likelihood of noise effect sequences decreases with increasing reliability weight. With this new approximation, the set of noise-effect sequences for a weight of $W$ becomes \begin{align} \cS_W &=\left\{\sort{z}^n \in\{0,1\}^n: \sum_{i=1}^m\sum_{j=I_{i-1}+1}^{I_i} \relest_{j}\sort{z}_j =W\right\} \nonumber\\ &= \bigcup_{W^m:\sum_{i=1}^m W_i=W} \left(\Psi^1_{W_1} \times \Psi^2_{W_2} \times \cdots \Psi^m_{W_m} \right), \label{eq:cartP} \end{align} where \begin{align*} \Psi^i_{W_i}=\left\{(z_{I_{i-1}+1},\ldots,z_{I_i}): \sum_{j=I_{i-1}+1}^{I_i} \relest_{j}z_j = W_i\right\} \end{align*} for $i\in\{1,\ldots,m\}$ and $\times$ represents Cartesian product. Thus, to generate all elements of $\cS_W$ in Eq. \eqref{eq:cartP}, we identify the set of all possible splitting patterns of $W$, denoted by \begin{align} \label{eq:Pw} \Xi_W = \left\{W^m \in\mathbb {Z}_+^m : \sum_{i=1}^{m}W_i = W \right\}, \end{align} using Algorithm \ref{alg:split}, explained later. For a given $W^m=(W_1,\ldots,W_m) \in \Xi_W$, consider the generation of the partial sequence set $\Psi^i_{W_i}$ defined in Eq. \eqref{eq:cartP}. Recalling Eq. \eqref{eq:relest_seg}, each partial sequence must satisfy \begin{align} & W_i = \sum_{j=I_{i-1}+1}^{I_i} (J_{i-1} + (j-I_{i-1})\beta_i)z_j \nonumber \\ & = J_{i-1}w_\text{H}{(z_{I_{i-1}+1}, \ldots z_{I_i})}+\beta_iw_\text{L}{(z_{I_{i-1}+1}, \ldots z_{I_i})}, \label{eq:W2IJ} \end{align} which, defining $w_i=w_\text{H}{(z_{I_{i-1}+1}, \ldots z_{I_i})}$ and with $v_k = j_k-I_{i-1}$ being the relative indices of the flipped bits, is equivalent to \begin{align} \label{eq:wu_i} w_\text{L}{(z_{I_{i-1}+1}, \ldots z_{I_i})} = \sum_{k=1}^{w_i} v_k = \frac{W_i - w_i J_{i-1}}{\beta_i}. \end{align} Eq. \eqref{eq:wu_i} indicates that, with the partial reliability weight $W_i$ and Hamming weight $w_i$ specified for the $i$-th segment, the partial noise-effect sequence generation reduces to the integer partition problem that is efficiently solved by the Landslide algorithm in section \ref{subsec:land}. Splitting a reliability weight value of $W$ into $m$ parts, as defined in Eq. \eqref{eq:Pw}, is a distinct integer partition problem, which we call the integer splitting problem for differentiation. The difference here lies in that the same group of parts with different orders are distinct splitting patterns. A common approach to finding all splitting patterns in $\Xi_W$ is given in Algorithm \ref{alg:split}, which starts with sweeping $W_1$ from 0 to $W$. For a given value of $W_1$, $W_2$ is swept from 0 to $W-W_1$. For each fixed $W_1$ and $W_2$, $W_3$ is swept and the nested loop reaches $W_{m-1}$. Then $W_m$ is computed as $W-\sum_{j=1}^{m-1}W_j$, ensuring the sum of all parts is $W$. The size of the set $\Xi_W$ obtained from the algorithm is $\xi_W = \binom{W+m}{m-1}$. \floatstyle{spaceruled \restylefloat{algorithm \begin{breakablealgorithm} \caption{The Integer Splitting Algorithm} \label{alg:split} \begin{flushleft} \textbf{Input:} $W$, m \newline \textbf{Output:} $\{W^{m,k} : k=1, 2, \ldots,\xi_W \}$ \end{flushleft} \begin{algorithmic}[1] \STATE $k \gets 0$ \FOR {$W_1 = 0$ To $W$} \FOR {$W_2 = 0$ To $W-W_1$} \STATE \ldots\ldots (nested loops over $W_i$, $i=3, 4, \ldots, m-2$) \FOR {$W_{m-1} = 0$ To $W-\sum_{l=1}^{m-2}W_l$} \STATE $W_m \gets W-\sum_{l=1}^{m-1}W_l$ \STATE $k \gets k+1$ \STATE $W^{m, k} \gets \{W_1, W_2, \ldots, W_m\}$ \ENDFOR \STATE \ldots\ldots (nested loops over $W_i$, $i=3, 4, \ldots, m-2$) \ENDFOR \ENDFOR \RETURN{} $\{W^{m,k} : k=1, 2, \ldots,\xi_W\}$ \end{algorithmic} \end{breakablealgorithm} Eq. \eqref{eq:wu_i} indicates that the actual number of valid splitting patterns is, however, much smaller than $\xi_W$, owning to the requirement that each element $W_i$ of a valid $W^m$ must satisfy all of: \begin{align} \label{eq:wi_cond} \begin{cases} & W_i = 0 \text{~or~} W_i - w_i J_{i-1} \ge \frac{(1+w_i)w_i}{2} \\ & W_i - w_i J_{i-1} \le (I_i-I_{i-1}+1)w_i - \frac{(1+w_i)w_i}{2} \\ & W_i - w_i J_{i-1} \text{~is divisible by~} \beta_i. \end{cases} \end{align} Therefore, any non-zero element $W_i$ in $W^m$ must be associated with a non-empty set of partial Hamming weights $\{w_i\}$, such that Eq. \eqref{eq:wi_cond} is satisfied. Otherwise $W^m$ is invalid and should be discarded. The associated set for $W_i$ can be obtained with Algorithm \ref{alg:phm}. \floatstyle{spaceruled \restylefloat{algorithm \begin{breakablealgorithm} \caption{The collection algorithm for valid partial Hamming weights} \label{alg:phm} \begin{flushleft} \textbf{Input:} $W_i$, $J_{i-1}$ \newline \textbf{Output:} $\{ w_{i,k} : k=1, 2, \ldots \}$ or FAIL \end{flushleft} \begin{algorithmic}[1] \STATE $k \gets 0$ \FOR {$w = 1$ To ${\lfloor \frac{\sqrt{1+8W_i}-1)}{2}\rfloor}$} \IF {$W_i, w$ and $J_{i-1}$ satisfy Eq. \eqref{eq:wi_cond}} \STATE $k \gets k + 1$ \STATE $w_{i,k} \gets w$ \ENDIF \ENDFOR \IF {$k$ is $0$} \RETURN{} FAIL \ELSE \RETURN{} $\{ w_{i,k}: k=1, 2, \ldots \}$ \ENDIF \end{algorithmic} \end{breakablealgorithm} The FAIL return from Algorithm 3 invalidates $W_i$ as well as the whole split pattern $W^m$. In Algorithm 2, each new value of $W_i$ is checked against Algorithm 3. A return of FAIL discard the current value of $W_i$ and force the loop to jump to the next iteration with a new value of $W_i$. Only when $W_i$ is validated, can the follow-up nested loop over $W_{i+1}$ continue. Each returned partial Hamming weights set $\{ w_{i,k} \text{,~} k=1, 2, \ldots \}$ should also be saved for the later generation of partial noise-effect sequences. In addition to the validation from Algorithm \ref{alg:phm}, more measures are available for further reduction of the set size of $\Xi_W$. For example, after the initial value of 0, $W_i$ can jump to $J_{i-1}+\beta_i$ omitting all values in between. Generally, due to the small segment number $m$ in practice, the generation of splitting patterns $W^m$ has limited impact on the overall efficiency of the ORBGRAND algorithm, which is instead dominated by the efficient Landslide algorithm. A significant complexity reduction is, however, available if $J_{i-1}$ is divisible by $\beta_i$. In this case, $W_i$ must also be divisible by $\beta_i$ in order to have Eq. \eqref{eq:wi_cond} satisfied. This can be achieved by sweeping $W_i$ in steps of size $\beta_i$. Then the validation of a partial Hamming weight $w_i$ is straightforward, forsaking the need of Algorithm \ref{alg:phm}. The extra restriction on $J_{i-1}$ logically leads to a potential performance loss. As demonstrated by later simulations, the minor performance loss justifies the complexity reduction measure. Given parameters of the statistical model in Eq. \eqref{eq:relest_seg}, all the components necessary to create the full ORBGRAND algorithm have been described. The likelihood order of generated noise-effect sequences is governed by the increasing value of reliability weight. For each specified weight value $W$, Algorithm 2 (or its optimized version) is used to generate $\Xi_W$, the set of valid splitting patterns. Each splitting pattern $W^m \in \Xi_W$ has its element (or partial reliability weight) $W_i$ assigned to the $i$-th segments. In each segment, Eq. \eqref{eq:wu_i} indicates that the Landslide algorithm can efficiently generate $\Psi_{W_i}$, the set of all possible partial noise-effect patterns, as defined in Eq. \eqref{eq:cartP}. Cartesian product over partial sequence sets, as shown in Eq. \eqref{eq:cartP}, is performed to create the set of noise-effect sequences for the current splitting pattern $W^m$. Finally, the union operation in Eq. \eqref{eq:cartP} forms $\cS_W$, the full set of noise-effect sequences for the reliability weight of $W$. Parallel implementation can be achieved at several levels, such as jointly generating partial sequences for multiple segments, or concurrently generating noise-effect sequences for multiple splitting patterns. What remains now is determining the parameters in the piece-wise linear model. \subsection{Piece-wise linear fitting and quantization} \label{sub:fit} Key to ORBGRAND's practical complexity is that it operates on $\relest^n=(\relest_1,\ldots,\relest_n)$, an approximation to the original rank ordered reliability curve for a given received code block $(\absorbLLR{1},\ldots, \absorbLLR{n})$. The approximation level determines the trade-off between algorithmic complexity and the decoding performance. The simplest statistical model is a line through the origin, which only requires rank ordering of the received bits by their reliability, but results in degraded performance at higher SNR scenarios. The model underlying the full ORBGRAND necessitates two stages: piece-wise linear fitting and quantization. While there are numerous approaches for either higher accuracy or lower complexity, here we introduce a method with moderate algorithmic complexity that serves as a reference design and demonstrates the robustness of ORBGRAND. Given an independent and identically distributed set of random variables, $\{A_i:i\in\{1,\ldots,n\}\}$, drawn from a cumulative distribution $F_A$, results from the theory of Order Statistics \cite{david2004order} tell us that rank ordering from least to greatest, so that $A_{(i)}$ is the $i$-th smallest value, leads to $A_{(i)} \approx F^{-1}_A\left(i/n\right)$ for $1 \leq i \leq n$ and large $n$. $F^{-1}_A(\cdot)$ is a monotonically increasing function and serves as the functional mean of rank ordered ensembles of observations $\{A_i:i\in\{1,\ldots,n\}\}$. For rank ordered reliabilities of blocks of bits received from the channel, $(\absorbLLR{1},\ldots, \absorbLLR{n})$, this serves as guidance for a fitting procedure for the statistical model. We can, therefore, use the edge point at index $I_{a,0}=1$ and the center point at index $I_{a,1}=n/2$ on $L^n$ as the initial set of anchor points from which other anchor points for segmentation can be found, as illustrated in Fig. \ref{fig:dynamic}. A straight line is drawn linking the anchor points at $I_{a,0}$ and $I_{a,1}$. The maximum vertical gap between the straight line and the reliability curve determines the location of the new anchor point with its index marked as $I_{a,2}$. New anchor points can be found between adjacent anchor points in the same way. A rule of thumb is that more points should be located in the high-curvature area near the edge. The indices of anchor points define the segmentation of the reliability curve, and the linear lines linking adjacent anchor points form a piece-wise linear fitting to the reliability curve. \begin{figure}[htbp] \centerline{\includegraphics[width=0.38\textwidth]{dynamic}} \caption{Identification of anchor points for segmentation of the reliability curve.} \label{fig:dynamic} \end{figure} If the curve $L^n$ is close to a straight line between two anchor points an additional segment is unnecessary, or, a casually added segment has little impact to the performance except for some overhead in the splitting of logistic weight. The same fitting technique can be applied to the high reliability area near the right edge, however, as shown in Fig. \ref{fig:dynamic}, we choose to extend the central line to cover the area. In low SNR cases, the extended straight line by itself is a good approximation, and in high SNR cases, high reliability bits have little influence on the generation order of noise-effect sequences. The assertion has been verified with simulations. From Eq. \eqref{eq:relest_seg}, the piece-wise linear approximating curve is defined with three sets of non-negative integer parameters: $I_i \in\mathbb {Z}_+, 0 \leq i \leq m$, the indices for segmentation; $J_i \in\mathbb {Z}, 0 \leq i \leq m-1$, the offset of each linear segment; and $\beta_i \in\mathbb {N}, 1 \leq i \leq m$, the slope of each segment. When $m+1$ anchor points on $L^n$ have been obtained, their indices are used as the segmentation indices and is denoted as $I_i, i=0, 1, 2, \ldots, m$, where $I_0=0$ and $I_m=n$. We further use the smallest slope of fitted linear lines to quantize parameters, which is computed as \begin{align} \label{eq:Q} Q = \min \left \{ \frac{L_{I_1}-L_1}{I_1-1},\min_{i\in\{2,\ldots,m\}} \left\{ \frac{L_{I_i}-L_{I_{i-1}}}{I_i-I_{i-1}} \right\} \right\} \end{align} where the slope of the first segment is specially treated due to the lack of $L_0$. The quantized parameters of linear lines are then computed as, \begin{equation} \label{eq:quant} \begin{cases} & \beta_1 = \left [ \frac{L_{I_1}-L_1}{(I_1-1)Q} \right ] \text{,~for~} i=1; \beta_i = \left [ \frac{L_{I_i}-L_{I_{i-1}}}{(I_i-I_{i-1})Q} \right ] \text{,~for~} 2 \leq i \leq m \\ & J_0 = \left [ \frac{L_{1}}{Q} \right ] - \beta_1 \text{,~for~} i=0; J_i = \left [ \frac{L_{I_i}}{Q} \right ] \text{,~for~} 1 \leq i \leq m-1, \end{cases} \end{equation} where $[~]$ is the rounding operation. Again, $\beta_1$ and $J_0$ are specially treated for the first segment. A complexity reduction technique in section \ref{sub:fullORB} requires $J_{i-1}$ to be integer multiples of $\beta_i$, which can be easily achieved with operation $\left [ J_{i-1}/\beta_i \right ] \beta_i$. The segmentation method in Fig. \ref{fig:dynamic} and line parameters obtained from Eq. \eqref{eq:quant} complete the piece-wise linear fitting and quantization. \section{Performance Evaluation} \label{sect:simulation} As stated in the motivation, ORBGRAND is particularly well suited to low to moderate redundancy. Such redundancy regimes can be achieved by having short length codes, or longer codes with sufficiently high rate to make the number of redundancy bits low to moderate. Commonly used codes have structures that limits their operating range, but Random Linear Codes (RLCs) have no such limitation and can be constructed for any length and rate. As an illustration, Fig. \ref{fig:ORBGRANDrates} shows as heat map of block error rates (BLERs) for different code lengths and rates for RLCs decoded using basic ORBGRAND. \begin{figure}[htbp] \centerline{\includegraphics[width=0.45\textwidth]{ORBGRAND_rates.pdf}} \caption{Decoding performance of ORBGRAND applied to RLCs of different length $n$ with up to $n-k=20$ redundant bits over AWGN channels using BPSK at an SNR of 9.8 leading to a hard detection bit flip probability of $p=10^{-3}$.} \label{fig:ORBGRANDrates} \end{figure} With the range of suitable rates and lengths for ORBGRAND in mind, we can now explore the performance. A key feature of all GRAND algorithms is that they provide excellent decoding performance for all moderate redundancy codes, regardless of length or structure, and so can be used to identify the best code structures. Our first comparison is naturally CA-Polar codes, which are are the state of the art codes which are both moderate length and high rate and which are designed for decoding with soft information, with dedicated CA-SCL decoders. We consider CA-Polar[256, 234], which has 22 parity bits and uses the 11-bit CRC specified for 5G NR up-link control channels. The CA-SCL decoder the list size is set to 16, and apply the CA-SCL decoder from the AFF3CT toolbox \cite{Cassagne2019a} as our performance reference. Non-standard codes include BCH codes, which can be well designed for low to moderate redundancy but are not designed for decoding with soft information, and CRCs, which are designed for error detection rather than correction but that are being considered for error correction using GRAND \cite{grand-crc,LiangLiu2021}. CRCs present desirable low complexity in encoding and code-book checking. Finally, we also consider RLCs, whose use with GRAND is also being explored \cite{grand-mo, grand-crc, duffy2021ordered, Riaz21, Papadopoulou21}. Our comparison is in Fig. \ref{fig:combo_plot}, where the 3-line version of ORBGRAND is used to decode. All ORBGRAND algorithms in our figures below have been set to abandon searching and record a block error if no code-book element is identified within $5 \times 10^6$ code-book queries. \begin{figure}[htbp] \centerline{\includegraphics[width=0.45\textwidth]{combo_plot}} \caption{Decoding performance of ORBGRAND applied to CA-Polar[256, 234], CRC[256, 234], RLC[256, 234] and BCH[255,231] codes.} \label{fig:combo_plot} \end{figure} One of the main innovations of this paper over the original conference paper that introduced ORBGRAND \cite{duffy2021ordered} is the multi-line approach. We next explore the effect of the number of lines, and of the selection of the intervals for those lines. To do so, we envisage three CA-Polar code configurations, CA-Polar[256, 234], CA-Polar[512, 490] and CA-Polar[1024, 1002], which all have 22 parity bits and the 11-bit CRC specified for 5G NR up-link control channels. Fig. \ref{fig:polar_256_234} presents the simulation results of CA-Polar[256, 234]. For lower SNR, all ORBGRAND variants exhibit substantially better performance than CA-SCL because of the incomplete utilization of CRC bits for error correction in the CA-SCL algorithm \cite{grand-crc}. For a BLER of $10^{-4}$ or below, CA-SCL outperforms the basic variant of ORBGRAND as its model does not produce putative noise sequences in near-ML order at higher SNR. ORBGRAND with 1-line fitting provides an observable, but limited, improvement over the basic version because their only difference is that the 1-line version starts from the quantized value of $\absorbLLR{1}$ instead of the origin in the basic version. With the 2-line version, the curvature in the low reliability region is captured by the two fitted lines, essentially resulting in the elimination of performance loss, and leaving only a small room of improvement for the 3-line version, which in turn overlaps with the 4-line version. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{polar_256_234} \caption{Performance evaluation of CA-Polar[256, 234] as decoded with CA-SCL, a list size of 16, or ORBGRAND variants with normal ORBGRAND quantization.} \label{fig:polar_256_234} \end{figure} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{polar_256_234_js} \caption{Performance evaluation of CA-Polar[256, 234] as decoded with CA-SCL, list size of 16, or ORBGRAND variants with $J_{i-1}$ divisible by $\beta_i$.} \label{fig:polar_256_234_js} \end{figure} Similar observations can be seen in the simulation results for CA-Polar[512, 490] and CA-Polar[1024, 1002] codes in Fig. \ref{fig:polar_512_490}, \ref{fig:polar_512_490_js} and Fig. \ref{fig:polar_1024_1002}, \ref{fig:polar_1024_1002_js} respectively, except that with longer block lengths, the 3-line and 4-line versions have more significant decoding improvement. Also, with the same number of parity bits, the loss of performance of the basic version occurs at a higher BLER, as shown in Fig. \ref{fig:polar_1024_1002}, where CA-SCL surpasses the basic version before BLER of $10^{-3}$. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{polar_512_490.pdf} \caption{Performance evaluation of CA-Polar[512, 490] decoded with CA-SCL, list size of 16, or ORBGRAND variants with normal ORBGRAND quantization.} \label{fig:polar_512_490} \end{figure} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{polar_512_490_js} \caption{ Performance evaluation of CA-Polar[512, 490] decoded with CA-SCL, list size of 16, or ORBGRAND variants with $J_{i-1}$ divisible by $\beta_i$.} \label{fig:polar_512_490_js} \end{figure} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{polar_1024_1002} \caption{Performance evaluation of CA-Polar[1024, 1002] decoded with CA-SCL, having a list size of 16, or ORBGRAND algorithms with normal quantization.} \label{fig:polar_1024_1002} \end{figure} \begin{figure} \centering \includegraphics[width=0.9\linewidth]{polar_1024_1002_js} \caption{ Performance evaluation of CA-Polar[1024, 1002] decoded with CA-SCL, having a list size of 16, or ORBGRAND algorithms with $J_{i-1}$ divisible by $\beta_i$.} \label{fig:polar_1024_1002_js} \end{figure} Up to now the simulations have demonstrated the effectiveness of the multi-line ORBGRAND in maintaining its performance advantage over the state-of-art CA-SCL decoders. In the next step we evaluate the influence of complexity control methods, which can bring significant advantages for ORBGRAND in practical implementations, on performance. An example complexity control measure is to have $J_{i-1}$ in Eq. (\ref{eq:wu_i}) be an integer multiple of $\beta_i$. As discussed in Section \ref{sub:fullORB}, the advantage is that Algorithm \ref{alg:phm} is no longer needed, improving the efficiency of Algorithm \ref{alg:split}. As shown in Fig. \ref{fig:polar_256_234_js}, Fig. \ref{fig:polar_512_490_js} and Fig. \ref{fig:polar_1024_1002_js}, with the factor of $J_{i-1}/ \beta_i$ joined in, there is trivial change of performance between decoders with corresponding segmentation, demonstrating the robustness of ORBGRAND. \section{Discussion} \label{sect:summary} With an abundance of new applications requiring low latency and high reliability for their operation, finding and decoding short, high-rate codes is attracting substantial attention. Old and new candidate codes along with their standard decoders have been explored and recognized to have imperfections in either the decoder or the code itself. We have introduced ORBGRAND, a practical soft detection variant of guessing random additive noise decoding, with which it is possible to decode any moderate redundancy code with near optimal performance. ORBGRAND offers a range of design complexities with its basic version being the simplest and requiring the least soft information. The core algorithm of the basic ORBGRAND generates integer partitions, for which we proposed the Landslide algorithm, which is suitable for efficient hardware and real-time implementation. That algorithm is an essential component for the full ORBGRAND, which has higher design complexity, but can better exploit soft information at higher SNRs for additional decoding gains. Simulation results show that the performance of ORBGRAND is directly dependent on how well the reliability curve is approximated, and the basic ORBGRAND adopts the simplest one. Inspired by the finding, we proposed the piece-wise linear approximation to the reliability curve, which optimizes ORBGRAND across all SNRs. The ORBGRAND algorithm, curve fitting techniques, and robustness to complexity improvement are established with simulations. The decoding performance is dependent on ORBGRAND's design complexity, but the 3-line version is capable of maintaining close-to-optimal performance in most scenarios. The proposed complexity control method is demonstrated to have little impact on performance, illustrating the robustness of ORBGRAND and anticipating the potential for further complexity reduction measures to facilitate VLSI implementation. \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-02T02:27:04', 'yymm': '2202', 'arxiv_id': '2202.13951', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13951'}
arxiv
\section{Introduction} One major issue in developing conversational dialogue systems is the significant efforts required for evaluation. This hinders rapid developments in this field because frequent evaluations are not possible or very expensive. The goal is to create automated methods for evaluating to increase efficiency. Unfortunately, methods such as BLEU~\cite{papineni-etal-2002-bleu} have been shown to not be applicable to conversational dialogue systems~\cite{liu-etal-2016-evaluate}. Following this observation, in recent years, the trend towards training methods for evaluating dialogue systems emerged~\cite{lowe-etal-2017-towards,deriu-cieliebak-2019-towards,mehri2020usr,deriu2020survey}. The models are trained to take as input a pair of context and candidate response, and output a numerical score that rates the candidate for the given context. These systems achieve high correlations to human judgments, which is very promising. Unfortunately, these systems have been shown to suffer from instabilities. \cite{sai2019re} showed that small perturbations to the candidate response already confuse the trained metric. This work goes one step further: we propose a method that automatically finds strategies that elicit very high scores from the trained metric while being of obvious low quality. Our method can be applied to automatically test the robustness of trained metrics against adversarial strategies that exploit certain weaknesses of the trained metric. \begin{figure}[ht!] \centering \includegraphics[width=0.95\linewidth]{figures/Example.pdf} \caption{Overview of the process. It takes a context and an response generated by a dialogue policy and computes a score based on the trained metric. The score is then used as a reward to update the policy. In this example, the policy converges to a fixed response, which achieves an almost perfect score, although it is clearly a low-quality response. The policy always returns this response, regardless of the context, and the trained metric always scores it perfectly.} \label{fig:example} \end{figure} Our method uses a trained metric as a reward in a Reinforcement Learning setting, where we fine-tune a dialogue system to maximize the reward. Using this approach, the dialogue system converges towards a degenerate strategy that gets high rewards from the trained metric. It converges to three different degenerate types of strategies to which the policy converges in our experiments: the \emph{Parrot}, the \emph{Fixed Response}, and the \emph{Pattern}. For each dataset and metric, an adversarial response is found, which belongs to one of the three strategy types. The responses generated from these strategies then achieve high scores on the metric. Even more, in most cases, the scores are higher than the scores achieved by human written responses. Figure \ref{fig:example} shows the pipeline. The dialogue policy receives a reward signal from the trained metric. Over time, the policy converges to a fixed response, which objectively does not match the context but gets a near-perfect score on the trained metric. We release the code~\footnote{\url{https://github.com/jderiu/metric-robustness}}. \section{Related Work} \noindent{\textbf{Trained Metrics.}} In recent years the field of trained metrics gained traction after word-overlap methods have been shown to be unreliable~\cite{liu-etal-2016-evaluate}. The first of these metrics is ADEM~\cite{lowe-etal-2017-towards}, which takes as input a context, a reference, and the candidate response and returns a score. The main issue with ADEM is the reliance on references and annotated data (i.e., human ratings of responses), which are costly to obtain, and need to be redone for each domain. RUBER~\cite{tao2018ruber} extended ADEM by removing the reliance on annotated data for training. However, it still relies on a reference during inference. AutoJudge~\cite{deriu-cieliebak-2019-towards} removed the reliance on references, which allows the evaluation of multi-turn behavior of the dialogue system. However, AutoJudge still leverages annotated data for training. USR~\cite{mehri2020usr} is a trained metric that does not rely on either annotated data or any reference. It is trained in a completely unsupervised manner while still highly correlated to human judgment ($0.4$ Spearman Correlation). Similarly, MAUDE \cite{sinha2020learning} is trained as an unreferenced metric built to handle the online evaluation of dialogue systems. \noindent{\textbf{Robustness of Trained Metrics.}} There is not yet much research on the robustness of trained metrics. \newcite{sai2019re} evaluated the robustness of ADEM by corrupting the context in different ways. They show that by just removing punctuation, the scores of ADEM change, and in $64\%$ of cases are superior to the scores given for the same response without removed punctuation. Other corruption mechanisms yielded similar results. \newcite{Yeh2021ACA} compared a large variety of automated metrics for dialogue system evaluation by comparing, e.g.,\ turn- and dialogue-level correlation with human judgemnts and studying the impact of the dialogue length. They find that no single metric is robust against all alternations but see potential in ensembling different metrics. \newcite{novikova-etal-2017-need} investigate automated metrics in the task-oriented NLG domain and find that the metrics do not sufficiently reflect human ratings. \section{Method} Our method applies a trained metric as a reward signal $R(c,r)$ to update a dialogue system $\pi(c)$ in a reinforcement learning setting, where $c$ denotes the context and $r$ the response. The dialogue system is trained by generating a response for a context, which is then scored by the automated metric. The dialogue system is then updated using the score as the reward. This process is repeated for different contexts. We use the Actor-Critic framework to optimize the policy~\cite{sutton1999actorcritic}. See Algorithm \ref{algo:rl} for an overview. \begin{algorithm}[t] \small \SetAlgoLined \While{training}{ sample $c$ from pool of contexts\; $r = \pi_{\theta}(c)$ generate response\; $s = R(c, r)$ compute reward\; fit action-value function $Q_{\sigma}$\, i.e., $\mathcal{L}(\sigma) = \frac{1}{2}\sum_i \norm{R(c, r) + Q_(c^{\prime}, r^{\prime}) - Q_{\sigma}(c, r)}$; compute the advantage $A(\textit{r}, \textit{c}) = R(\textit{r}, \textit{c}) - Q(c, r) + Q(c^{\prime}, r^{\prime})$\; $\theta = \theta + \alpha \bigtriangledown J_{RL}(\theta)$ fit policy\; } \caption{Advantage Actor-Critic Algorithm, where $\pi_{\theta}$ denotes the policy, $c$ denotes the context, $r$ the response generated by the policy, and $s$ denotes the score by the automated metric, i.e., the reward.} \label{algo:rl} \end{algorithm} The policy gradient is defined as $\bigtriangledown J_{RL}(\theta) = \bigtriangledown_{\theta}log~\pi_{\theta}(r|c) * A(\textit{r}, \textit{c})$, where $\pi_{\theta}(r|c)$ defines the probability of the generated response for the given context, and $A(c,r)$ the advantage function. The learned policy depends on the reward function, i.e., the automated metric. If the reward function is susceptible to adversarial attacks, the policy will likely generate an objectively suboptimal solution, which is rated highly by the automated metric. Conversely, we expect the policy to improve the dialogue systems' responses if the automated metric is robust against adversarial examples. \input{tables/selected_responses} \section{Experimental Setup} \subsection{Datasets} We perform the evaluation on three widely-used datasets in the dialogue modelling domain. Namely, Dailydialog \citep{li-etal-2017-dailydialog}, Empathetic Dialogues \citep{rashkin-etal-2019-towards}, and PersonaChat \citep{zhang-etal-2018-personalizing}. \subsection{Metrics} We use various state-of-the-art automated metrics developed for evaluating conversational dialogue systems without reference, i.e., so-called unreferenced metrics.. These are metrics where no reference is needed, i.e. they only use the context and response to determine the score. They can be represented as a function $s = R(c, r)$, which rate the response $r$ for a given context $c$. We selected state-of-the-art trained metrics which achieve good correlations to human judgments to evaluate our approach—namely, USR~\cite{mehri2020usr}, ATT~\cite{gao2021adversarially}, and MAUDE~\cite{sinha2020learning}. Additionally, we added the Blender language model score (BlenderLM)~\cite{roller2020recipes}. For the ATT~\footnote{\url{https://github.com/golsun/AdversarialTuringTest}}, MAUDE~\footnote{\url{https://github.com/facebookresearch/online\_dialog\_eval}}, and BlenderLM metrics~\footnote{\url{https://huggingface.co/facebook/blenderbot-400M-distill}}, we use the out-of-the-box models provided by the respective authors. For the USR metric, we perform custom training on each dataset. Furthermore, we report the USR-retrieval (\emph{USR Ret}), USR-masked-language-model \emph{USR MLM}, and the USR-regression \emph{USR Full} scores. Note that the \emph{USR Full} is a combination of the \emph{USR Ret} and \emph{USR MLM} metric. More details can be found in Appendix \ref{sec:appendix_metrics}. \input{tables/rankings_small} \subsection{Strategies} For our approach, we use Blenderbot as our policy \cite{roller2020recipes} since it is currently a state-of-the-art conversational dialogue system~\footnote{Note that here we are referring to Blenderbot as a dialogue system. BLM is using the Blenderbot LM as a metric.}. We use the validation set for each domain to perform reinforcement learning. This is to avoid the dialogue systems being fine-tuned on already seen data. We use the test set to evaluate the reward over the number of episodes. We perform the reinforcement learning for 15 epochs, where each epoch is composed of 500 updates. We noted from pre-experiments that this is enough for a dialogue system to converge to a degenerate strategy. We track the average reward achieved on the test set after each epoch. Each experiment is repeated 10 times since we expect the policy to converge to slightly different strategies in different runs. We select the repetition which achieved the highest score (i.e., reward) and use it to determine the strategy. We also experimented with automated strategy detection, see Appendix \ref{sec:appendix_c}. \section{Results} The policies typically converge towards one of the following three degenerate strategies. \noindent{\textbf{Parrot.}} Here, the policy simply copies parts of the context into the response. Sometimes, it applies slight changes. For instance, it changes the pronouns from "you" to "I". \noindent{\textbf{Fixed Response.}} Here, the policy converges on a fixed response which it returns regardless of the context. \noindent{\textbf{Pattern.}} This is a mix between the \emph{Parrot} and the \emph{Fixed Response}. It creates a fixed template filled with parts of the context. Table~\ref{tab:selected} shows the selected responses for each pair of domain and metric. For all metrics except \emph{ATT}, the fixed response is composed of a grammatically correct sentence. Note that these responses are always returned by the fine-tuned dialogue system, regardless of the context. \subsection{Scores} Table \ref{tab:scores} shows the main results. In almost all cases, the degenerated strategy outperforms the vanilla Blenderbot and humans with respect to the automated metric. The most striking example is the \emph{ATT} metric, where the fixed response achieves scores by orders of magnitude better than the ones achieved by humans. For both \emph{USR Ret} and \emph{MAUDE}, the scores achieved by the fixed response are almost perfect, i.e., they are close to 1.0, which is the upper bound. Also, for \emph{USR MLM}, the scores are significantly higher than the ones achieved by Blenderbot. Interestingly, the \emph{USR FULL} seems to be more immune to the pattern that were found. However, even for \emph{USR FULL}, the parrot strategy beats the humans by a significant margin in the \emph{PersonaChat} domain. \noindent{\textbf{Copy.}} We also display the scores achieved by simply copying the context on each metric, which is inspired by the \emph{Parrot} strategy. The only metric which is immune to the \emph{Copy} strategy is \emph{ATT}. Under all the other metrics, the \emph{Copy} achieves very high scores. In some cases, it achieves even better scores than the converged policy. For instance, for the \emph{Dailydialog} domain, it achieves $0.811$ points under the \emph{USR MLM} metric, which is $0.3$ point higher than the converged policy and twice as good as the human score. \section{Conclusion} Trained metrics for automatic evaluation of conversational dialogue systems are an attractive remedy for the costly and time-consuming manual evaluation. While high correlation with human judgments seems to validate the metrics regarding their ability to mimic human judging behavior, our analysis shows that they are susceptible to rather simple adversarial strategies that humans easily identify. In fact, all metrics that we used failed to recognize degenerate responses. Our approach is easily adaptable to any newly developed trained metric that takes as input a pair of context and response. There are no known remedies for this problem. Thus, the next open challenge is to find methods that improve the robustness.
{'timestamp': '2022-03-01T02:52:24', 'yymm': '2202', 'arxiv_id': '2202.13887', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13887'}
arxiv
\section{Applications} \label{sec:app} The {\sc Cgal}{} library, and in particular the {\sc Cgal}{} arrangement packages have been used intensively at the Computational Geometry Lab at Tel Aviv University for over twenty years now, not only for research, where the researchers typically (though not always---see Section~\ref{ssec:neural}) have good knowledge of generic programming in C++, but also for teaching. We have been using {\sc Cgal}{} for projects in the Computational Geometry course, for assignments and final projects in the courses ``Algorithmic Robotics and Motion Planning'' and ''Algorithms for 3D printing and other Manufacturing Processes'', and for the implementation of a variety of robot algorithms in guided software workshops. Using {\sc Cgal}{} for teaching has persistently been a pain-point in these courses especially due to the intricate utilization of C++ in the implementation of the library. This has recently dramatically changed with the introduction of the Python bindings presented in this paper, as we describe in two examples below. \subsection{A Multi Robot Motion Planning Platform} \label{ssec:discopygal} We developed a program called {\sc DiscoPygal}{} written in Python that provides visualization and verification for multi-robot motion planning in 2D. The program uses Python bindings of {\sc Cgal}{} arrangements, {\sc Cgal}{} Minkowski sums, and other components of {\sc Cgal}{} needed for the implementation of fundamental motion-planning algorithms and enables the dynamic loading of motion-planning algorithms in the form of Python scripts during run time. It allows users to easily swap and compare between different motion-planning algorithms, and even modify an existing implementation of an algorithm while the program is running. (There is no need to recompile the code or restart the program.) The precompiled library for the {\sc Cgal}{} bindings used by the program can be supplied with it, such that even the installation of {\sc Cgal}{}, boost, or a C++ compiler is not required in order to use the program. We were invited to give a crash course in multi-robot motion planning in a summer school geared primarily toward engineering doctoral students,\footnote{\url{http://disc.tudelft.nl/education/summer-school/disc-summer-school-2021/}} where the organizers particularly asked for hands-on algorithm implementation and experimentation session. After two hours of lecture including fifteen minutes of presentation of {\sc DiscoPygal}, students installed it and were able to interact with it. Testimonies of students and organizers affirmed that the system was friendly and easy-to-use, and fruitful in assisting the students to absorb the algorithmic ideas. The students only needed to access and write Python code, while still employing heavy-duty {\sc Cgal}{} procedures in the background. In this year's Algorithmic Robotics course, the experimental assignments are based on {\sc DiscoPygal}{}. This is the first time that the introduction of the software into the assignment passed completely smoothly, without compromising the required level of algorithmic sophistication. The system allows the students to focus on algorithmic issues using Python, a programming language they are all familiar with, freeing them from many of the past points of hardship raised by working directly with {\sc Cgal}{}, and in particular with the advanced generic-programming mechanisms that {\sc Cgal}{} uses. A snapshot of the {\sc DiscoPygal}{} application window is shown in Figure~\ref{fig:disco}. The window is divided into three parts; informative messages are displayed on the console on the left, a rich menu resides to the right of the console; the workspace is drawn on the right. The particular workspace in the figure consists of two disc robots. The objective is to swap their positions. The path of each robot planned by the system is drawn in the color of the robot. \begin{figure}[!htp] \centering% \includegraphics[width=\linewidth]{discoPygal_two_robots.png} \caption{A snapshot of the {\sc DiscoPygal}{} application window.} \label{fig:disco} \end{figure} \subsection{Neural Collision Detection} \label{ssec:neural} In collaboration with neuroscientists, we helped developing a simulation system for the interaction between neurons and blood vessels in the brain~\cite{Har-Gil2021.07.20.452894}. The need arose to use three-dimensional alpha shapes. The {\sc Cgal}{} offerings in this respect looked a perfect fit, with the caveat that the main tools of the simulation are developed in Python and the most convenient programming language for that part of the project is Python. We developed Python bindings for the {\sc Cgal}{} alpha-shape package, and their usage was immediately and almost effortlessly integrated into the overall system by the neuroscientists. \section{Binding code} \label{sec:code} Boost.Python allows users to expose C++ classes and functions to Python using nothing more than a C++ compiler. It exploits metaprogramming techniques to implement a rich set of features and high-level user-friendly interface. Boost.Python extracts as much as information as possible from the source code to be wrapped. This approach is referred to as \emph{user guided wrapping}. Additional information that cannot be automatically deduced is explicitly supplied by the user. The interface specification is written in the same full-featured C++ language as the code being exposed, which has the potential of generating efficient binding. In this section we describe some of the techniques we use to ensure that. \subsection{Return value policy} \label{sec:code:rvp} Python and C++ use fundamentally different ways of managing the memory and lifetime of objects. This can lead to issues when creating bindings for functions that return a non-trivial type. Just by looking at the type, it is unclear whether Python should take charge of the returned value and eventually free its resources, or whether this is handled by the C++ code. When writing code in C++, it is usually considered a good practice to use smart pointers, which exactly describe ownership semantics. Still, even good C++ interfaces use raw references and pointers sometimes. In some cases, in order to assure proper memory management of a return value from a function, explicitly specifying a return value policy is needed. The policy may depend on whether the returned object is a newly created object, a reference to some already existing (internal) object, or a \cppLstinline{const} reference to some existing object. Additionally, in some cases we need to tie the lifetime of the result to the lifetime of the arguments, or the other way around. For some functions of kernel objects the kind of return value depends on the kernel type; thus, the return value policy needs to be set accordingly. For example, when \cppLstinline{Exact\_predicates\_inexact\_constructions\_kernel} is the kernel type, the return type of some functions that return a coordinate or a coefficient is a \cppLstinline{const} reference, while when the kernel type is \cppLstinline{Exact\_predicates\_exact\_constructions\_kernel} the same functions return an object by value. This is why for these functions a \myLstinline{Kernel_return_value_policy} type is being passed as the return value policy. The type is defined differently based on the kernel being exposed. \subsection{Intersection Detection} \label{sec:code:intersectionDetection} Substitution failure is not an error (SFINAE) refers to a situation in C++ where an invalid substitution of template parameters is not in itself an error.\footnote{For more information on SFINAE see, e.g., \url{https://en.cppreference.com/w/cpp/language/sfinae}.} In particular, it may occur during a process called \emph{overload resolution}. In order to compile a function call, the compiler creates a set of candidate functions the names of which match the call and that can be accessed by the caller. Then, it reduces the candidate set to a set of viable functions that includes all function instances the parameters of which match the call arguments. Finally, the compiler selects the best match among the viable functions according to the C++ standard;\footnote{For the full specification of the C++ standard see \url{https://isocpp.org/std/the-standard}.} a flowchart that describes the process is shown in Figure~\ref{fig:ors}. When the substitution of an explicitly specified or deduced type for the template parameter fails, the specialization is discarded from the overload set instead of causing a compilation error. \begin{figure}[!htp] \centerline{\begin{tikzpicture}[>=stealth,align=center,every node/.style={font=\sffamily}] \tikzstyle{state}=[text centered,node distance=0.5cm,% rectangle,rounded corners,fill=white,draw=black,% minimum width=1.0cm,minimum height=0.45cm] \tikzstyle{lookup}=[state,bottom color=purple!40] \tikzstyle{deduction}=[state,fill=orange!40] \tikzstyle{reduction}=[state,fill=yellow!40] \tikzstyle{selection}=[state,fill=green!40] \node (lookup)[lookup]{Name Lookup}; \node (lookupFailure)[below left=0.5 and -1 of lookup] {\textcolor{red}{Error: Lookup failure}}; \node (deduction)[deduction,below right=1 and -1.2 of lookup] {Template Argument Deduction}; \node (deductionFailure)[below left=0.5 and -2.8 of deduction] {\textcolor{red}{Error: Deduction failure}}; \node (reduction)[reduction,below right=1 and -1.2 of deduction] {Reduction}; \node (reductionFailure)[below left=0.5 and -1.6 of reduction] {\textcolor{red}{Error: Substitution failure}}; \node (selection)[selection,below right=1 and 0.0 of reduction] {Final Selection}; \node (success)[below right=0.5 and -0.7 of selection]{\textcolor{blue}{Best Match}}; \node (slectionFailure)[below left=0.5 and -1.6 of selection] {\textcolor{red}{Error: Ambiguity failure}}; \draw [thick,->,>=Stealth] (lookup) -- (deduction); \draw [thick,->,>=Stealth] (lookup) -- (lookupFailure); \draw [thick,->,>=Stealth] (deduction) -- node[anchor=west]{Non-empty candidate Set}(reduction); \draw [thick,->,>=Stealth] (deduction) -- (deductionFailure); \draw [thick,->,>=Stealth] (reduction) -- node[anchor=west]{Non-empty viable Set} (selection); \draw [thick,->,>=Stealth] (reduction) -- (reductionFailure); \draw [thick,->,>=Stealth] (selection) -- (success); \draw [thick,->,>=Stealth] (selection) -- (slectionFailure); \end{tikzpicture}} \caption{Overload resolution steps} \label{fig:ors} \end{figure} The function template \cppLstinline{CGAL::do_intersect(const T1& o1, const T2& o2)} determines whether two geometric objects intersect. The function is overloaded with several implementations that handle different combinations of types of arguments. They are provided by the \cgalPackage{2D and 3D Geometry Kernel}{} package (see Section~\ref{ssec:modules:kernel}). However, not every combination of two types is implemented in this package. For example, the intersection of a line segment and a circle in the general case is a point with algebraic coordinates, and thus not supported by the package.\footnote{For a complete list of valid combinations of \cppLstinline{do_intersect()} argument types refer to the reference manual at \url{https://doc.cgal.org/latest/Kernel_23/group__do__intersect__linear__grp.html}.} We use SFINAE to generate bindings for all supported combinations while avoiding getting compilation errors for unsupported combinations as follows. Our entry point is the function \cppLstinline{export_intersections_2()} shown in Listing~\ref{lst:exportIntersection}. It also serves as the entry point for the generation of bindings for the function \cppLstinline{CGAL::intersection(const T1& o1, const T2& o2)}; see Section~\ref{sec:code:intersectionComputation}. The function template \cppLstinline{bind_do_intersect()} is overloaded with two implementations. One of these implementations is of indefinite arity.\footnote{A function of indefinite arity is a variadic function. For more information on \emph{variadic functions} see \url{https://en.cppreference.com/w/cpp/language/variadic_arguments}.} We call this function and pass a list of arguments, such that every argument is a pointer to a type that represents a planar geometric object, and that can be a type of a parameter of \cppLstinline{CGAL::do_intersect()}. Supporting a new type, say \cppLstinline{T}, is as easy as defining a new variable, say \cppLstinline{t}, of type \cppLstinline{T*} and passing \cppLstinline{t} as an additional argument in the call to \cppLstinline{bind_do_intersect()}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:exportIntersection},% caption={Entry points for the code that automatically generates binding for \cppLstinline{CGAL::do_intersect()} and \cppLstinline{CGAL::intersection()} with arguments that represent planar geometric objects.}] void export_intersections_2() { Iso_rectangle_2* iso_rectangle(nullptr); Line_2* line(nullptr); Ray_2* ray(nullptr); Segment_2* segment(nullptr); Triangle_2* triangle(nullptr); Point_2* point(nullptr); Circle_2* circle(nullptr); bind_do_intersect(iso_rectangle, line, ray, segment, triangle, point, circle); bind_intersection(iso_rectangle, line, ray, segment, triangle, point, circle); } \end{lstlisting} \end{lstfloat} Our first goal is automatically generating all calls \cppLstinline{bind_do_intersect_pair<T1, T2>(true)}, where each of \cppLstinline{T1} and \cppLstinline{T2} is a type pointed by an argument passed to \cppLstinline{bind_do_intersect()}. The code excerpts in Listings~\ref{lst:doIntersectExpansion} does it using variadic templates. A variadic template is a function template that accepts a function parameter pack and is parameterized with a template parameter pack that represents the type of the function parameter pack. The central idea is to unpack the function parameter pack, process the first item in the list, then pass the rest of the list on to a recursive call until the list vanishes. The last call with a single argument matches the second implementation of the overloaded function and stops the recursion. As we need to obtain combinations of two arguments, we use two pairs of overloaded functions. Each one of the template parameters \cppLstinline{T1} or \cppLstinline{T2} of \cppLstinline{bind_do_intersect_pair()} must be substituted with a type of of a candidate parameter of \cppLstinline{CGAL::do_intersect()}. Thus, given a pointer type we obtain the pointee type and use the latter when calling \cppLstinline{bind_do_intersect_pair<T1, T2>(true)}; see Line~3, Line~4, Line-12, and Line~20. We use pointer types rather than the types themselves to avoid invoking the constructors and destructors of the objects; observe, that using variadic templates requires passing concrete objects. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:doIntersectExpansion},% caption={Automatic generation of calls \cppLstinline{bind_do_intersect_pair<T1, T2>(true)}.}] template<typename PT> void bind_do_intersect_inner(PT) {} template<typename PT1, typename PT2, typename... PTs> void bind_do_intersect_inner(PT1 arg1, PT2 arg2, PTs... args) { typedef typename std::remove_pointer<PT1>::type T1; typedef typename std::remove_pointer<PT2>::type T2; bind_do_intersect_pair<T1, T2>(true); bind_do_intersect_pair<T2, T1>(true); bind_do_intersect_inner(arg1, args...); } template<typename PT> void bind_do_intersect(PT arg) { typedef typename std::remove_pointer<PT>::type T; bind_do_intersect_pair<T, T>(true); } template <typename PT1, typename... PTs> void bind_do_intersect(PT1 arg, PTs... args) { bind_do_intersect_inner(arg, args...); bind_do_intersect(args...); typedef typename std::remove_pointer<PT1>::type T1; bind_do_intersect_pair<T1, T1>(true); } \end{lstlisting} \end{lstfloat} Consider two types \cppLstinline{Type1} and \cppLstinline{Type2}, and assume that the \cppLstinline{CGAL::do_intersect(const Type1& o1, const Type2& o2)} overloaded version is not implemented but all other three are, and refer to Listing~\ref{lst:do_intersect}. The function name \cppLstinline{bind_do_intersect_pair()} is overloaded with two implementations. As a consequence, assuming that the code compiles, one overload of \cppLstinline{bind_do_intersect_pair()} is selected for every permutation of (\cppLstinline{Type1}, \cppLstinline{Type2}). The primary implementation of \cppLstinline{bind_do_intersect_pair()} (Line~1) uses \emph{variadic arguments} and serves as a fall-through when the evaluation of the second implementation fails during the resolution process. The parameter type of the second implementation is defined as the return type of \cppLstinline{CGAL::do_intersect<Kernel>(T1(), T2())}. When \cppLstinline{T1} and \cppLstinline{T2} are substituted with \cppLstinline{Type1} and \cppLstinline{Type2}, respectively, the evaluation fails, and the blank implementation is selected, as this is the only candidate left. In all other three cases the evaluation succeeds and the second implementation is selected, as functions that accept variadic parameters have a lower rank for the purpose of overload resolution. Observe that in all calls to \cppLstinline{bind_do_intersect_pair()} (Lines~8,9,16,24) we pass a \cppLstinline{bool} argument of value \cppLstinline{true}. This value can be \cppLstinline{false} just as well, but its type, that is \cppLstinline{bool}, must match the return type of \cppLstinline{CGAL::do_intersect<Kernel>(T1(), T2())} when defined. The result is not only compact code that is easy to maintain, but also code that supports bindings for every potential \cppLstinline{CGAL::do_intersect()} overload that might be implemented in the future. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:do_intersect},% caption={Automatic generation of binding for \cppLstinline{CGAL::do_intersect()} exploiting SFINAE.}] template <typename, typename> void bind_do_intersect_pair(...) {} template <typename T1, typename T2> void bind_do_intersect_pair(decltype(CGAL::do_intersect<Kernel>(T1(), T2()))) { bp::def<bool(const T1&, const T2&)>("do_intersect", &CGAL::do_intersect<Kernel>); } \end{lstlisting} \end{lstfloat} \subsection{Intersection Computation} \label{sec:code:intersectionComputation} The situation presented by the overloaded function template \cppLstinline{CGAL::intersection(const T1& o1, const T2& o2)} that computes the intersection of two geometric objects is a bit more complicated. The various implementations are also provided by the \cgalPackage{2D and 3D Geometry Kernel}{} package. Similar to the \cppLstinline{CGAL::do_intersect()} function templates, different implementations handle different combination of types of arguments and not all combinations are supported. The intersection of two geometric objects can be either empty, a single object, or several points. Unlike the \cppLstinline{CGAL::do_intersect()} function templates, the return types of which are all simple \cppLstinline{bool}, the return type of each \cppLstinline{CGAL::intersection()} function template is a polymorphic type that either implicitly converts to \cppLstinline{false} if the intersection is empty or represents the intersection and depends on the types of the input arguments. Following the idea presented in the previous section, we introduce several template functions, where \cppLstinline{bind\_intersection\_pair()} is the last one called; see Line~1 and Line~3 in Listing~\ref{lst:intersection} for the primary and specialized implementations, respectively. Given a combination of two specific types, \cppLstinline{T1} and \cppLstinline{T2}, we still evaluate the return value of the function template \cppLstinline{CGAL::intersection(const T1& o1, const T2& o2)} as a mean to determine whether the function is defined, but we do not try to match this type to a type of an argument. Instead, we introduce an unnamed template parameter with a default value that evaluates to the return type of \cppLstinline{CGAL::intersection(const T1& o1, const T2& o2)}; see Line~4 in the listing. Observe that the outcome of the evaluation is irrelevant. The only thing that matters is whether the evaluation succeeds---it succeeds only if the function template \cppLstinline{CGAL::intersection(const T1& o1, const T2& o2)} is defined. If it is defined, the specialized implementation is selected by the overload-resolution process, and the function \cppLstinline{cgalpy_intersection(const T1& t1, const T2& t2)}, which actually computes the intersection, is exposed; see Listing~\ref{lst:intersectionImpl}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:intersection},% caption={Automatic generation of binding for \cppLstinline{CGAL::intersection()} exploiting SFINAE}.] template <typename, typename> void bind_intersection_pair(...) {} template <typename T1, typename T2, typename = decltype(CGAL::intersection<Kernel>(T1(), T2()))> void bind_intersection_pair(bool) { bp::def("intersection", &cgalpy_intersection<T1, T2>); } \end{lstlisting} \end{lstfloat} The exposed Python function that computes the intersection returns \pyLstinline{None} if the intersection is empty; see Line~17 in Listing~\ref{lst:intersectionImpl}. If the intersection consists of a single geometric object, the function returns a single Python object the type of which is the exposed {\sc Cgal}{} C++ type of the geometric object; see Line~4. Finally, if several points comprise the intersection, the return type is a list of Python objects (see Line~10), where the type of each element in the list is the the exposed type of \cppLstinline{Kernel::Point_2}. For more information of functions that return collections of object see Section~\ref{sec:code:output}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:intersectionImpl},% caption={Implementation of the binding for \cppLstinline{CGAL::intersection()}.}] class Intersection_visitor : public boost::static_visitor<bp::object> { public: template<typename T> bp::object operator()(T& operand) const { return bp::object(operand); } // Handle vector of points bp::object operator()(std::vector<Point_2>& operand) const { bp::list lst; for (const auto& p : operand) lst.append(p); return lst; } }; template <typename T1, typename T2> bp::object cgalpy_intersection(const T1& t1, const T2& t2) { auto result = CGAL::intersection<Kernel>(t1, t2); if (! result) return bp::object(); // no intersection return boost::apply_visitor(Intersection_visitor(), *result); } \end{lstlisting} \end{lstfloat} \subsection{Minkowski Sum Construction} \label{sec:code:minkSumComputation} The situation presented by the function template \cppLstinline{CGAL::minkowski_sum_2()} that applies the \emph{convex-decomposition approach} (see Section~\ref{ssec:modules:ms2}) is even more complicated. The function template shown in Line~1 of Listing~\ref{lst:minkSumConvexDecomposition} has 10 instances of valid combinations of argument types. There is another set, of the same cardinality, of function templates that also accept a fourth traits parameter. The number of instances of the function template shown in Line~8 is 36, and also here there is another set, of the same cardinality, of function templates that accept an additional traits parameter. Consider the function template shown in Line~1. We need to generate bindings for instances of this function only for valid combinations of \cppLstinline{PolygonType1}, \cppLstinline{PolygonType2}, and \cppLstinline{PolygonConvexDecomposition_2} types. Hereafter and in the code listing we use the respective short names \cppLstinline{PT1}, \cppLstinline{PT2}, and \cppLstinline{PP} instead. A valid combination exists only if \cppLstinline{PP} is a type of a polygon-partition unary function that can be applied to a polygon of type \cppLstinline{PT1} and to a polygon of type \cppLstinline{PT2}. Some supported polygon-partition functions cannot be applied to polygon with holes, hence invalid combinations. In particular, if \cppLstinline{pp} is a polygon-partition function, the calls \cppLstinline{pp(pgn1, it)} and \cppLstinline{pp(pgn2, it)} must be valid, where \cppLstinline{pgn1} and \cppLstinline{pgn2} are input polygons of types \cppLstinline{PT1} and \cppLstinline{PT2}, respectively, and \cppLstinline{it} is an output iterator of a container of the resulting polygons. Dereferencing the iterator must yield a type that can represent a simple polygon. If \cppLstinline{PT} is identical to \cppLstinline{Polygon_2}, then \cppLstinline{std::list<PT>::iterator} can serve as an output iterator; otherwise, \cppLstinline{PT} must represent a polygon with holes, and in this case \cppLstinline{std::list<PT::Polygon_2>::iterator} can serve as an output iterator. We use SFINAE yet again to make this distinction and we use SFINAE one more time to generate binding for \cppLstinline{CGAL::minkowski_sum_2()} only for valid combinations of argument types. \begin{lstfloat} \begin{lstlisting}[style=cppframedStyle,basicstyle=\normalsize,% label={lst:minkSumConvexDecomposition},% caption={Signatures of function templates that compute the 2D Minkwoski sum using the convex-decomposition approach.}] template <typename Kernel, typename Container, typename PolygonConvexDecomposition_2> Polygon_with_holes_2<Kernel, Container> minkowski_sum_2(const PolygonType1<Kernel, Container>& p, const PolygonType2<Kernel, Container>& q, const PolygonConvexDecomposition_2& decomp) template <typename Kernel, typename Container, typename PolygonConvexDecompositionP_2, typename PolygonConvexDecompositionQ_2> Polygon_with_holes_2<Kernel, Container> minkowski_sum_2(const PolygonType1<Kernel, Container>& p, const PolygonType2<Kernel, Container>& q, const PolygonConvexDecompositionP_2& decomp_p, const PolygonConvexDecompositionQ_2& decomp_q) \end{lstlisting} \end{lstfloat} Our entry point is the function \cppLstinline{void bind_mink_sum()}; see Line~15 in Listing~\ref{lst:minkowskiSumExpansion}. We need to capture valid combinations of three types. In particular, we need to generate all calls \cppLstinline{minkowski_sum_triplet<PT1, PT2, PP>(true)}; see Line~12 and Line~15 in Listing~\ref{lst:minkSumResolution} for the primary and specialized implementations, respectively. The first two types represent polygons and there are only two types of polygons to choose from, namely, \cppLstinline{Polygon_2} and \cppLstinline{Polygon_with_holes_2}. Therefore, instead of using variadic templates (see Listing~\ref{lst:doIntersectExpansion}, which can be used to capture valid combinations of any fixed number of types taken from a long list of types), we simply introduce two functions as shown in Listing~\ref{lst:minkowskiSumExpansion}. \begin{lstfloat} \begin{lstlisting}[style=cppframedStyle,basicstyle=\normalsize,% label={lst:minkowskiSumExpansion},% caption={Automatic generation of calls \cppLstinline{minkowski_sum_triplet<PT1, PT2, PP>(true)}.}] template <typename T1, typename T2> void bind_mink_sum_decomp_one_strategy_2T() { bind_mink_sum_triplet<T1, T2, ms2::Polygon_nop_decomposition_2>(true); bind_mink_sum_triplet<T1, T2, pp2::Polygon_vertical_decomposition_2>(true); bind_mink_sum_triplet<T1, T2, pp2::Polygon_triangulation_decomposition_2>(true); bind_mink_sum_triplet<T1, T2, pp2::Small_side_angle_bisector_decomposition_2>(true); } template <typename T> void bind_mink_sum_1T() { bind_mink_sum_2T<T, Polygon_2>(); bind_mink_sum_2T<T, Polygon_with_holes_2>(); } void bind_mink_sum() { bind_mink_sum_1T<Polygon_2>(); bind_mink_sum_1T<Polygon_with_holes_2>(); } \end{lstlisting} \end{lstfloat} We introduce a class template called \cppLstinline{target}; see Line~3 in Listing~\ref{lst:minkSumResolution}. it is parameterized with a named parameter \cppLstinline{T} and an unnamed parameter that defaults to \cppLstinline{void}. It delegates the type \cppLstinline{std::list<T>::iterator}. We also introduce a specialization (Line 7) that delegates the type \cppLstinline{std::list<T::Polygon_2>::iterator}. The second parameter is substituted with a type provided by a utility class template called \cppLstinline{has<>} (Line~1). If the type \cppLstinline{T::Polygon_2} is undefined, the evaluation of \cppLstinline{has<T::Polygon_2>} fails, and in turn the instance of the \cppLstinline{Target<>} specialization is discarded from the overloaded resolution set. Otherwise, \cppLstinline{has<T::Polygon_2>} successfully evaluates (to \cppLstinline{void}). In this case the \cppLstinline{Target<>} specialization remains a viable option, and it is selected over the primary implementation, since specializations are ranked higher. Observe that the type delegated by the \cppLstinline{has<>} class template and the type of the unnamed template parameter of the primary implementation of \cppLstinline{target<>} must match for the ordering to apply. These types are arbitrarily chosen to be \cppLstinline{void}. The polygon-partition function returns an output iterator that points to next to the last element of the container. Passing an argument, the type of which matches the type of the returned value of the polygon-partition function, to the function \cppLstinline{bind_mink_sum_triplet()} is complicated, as this type is not a simple type, such as the return types of \cppLstinline{CGAL::do_intersect()} (which is always \cppLstinline{bool}). Instead, we use the technique applied for the wrapping of the function templates \cppLstinline{CGAL::intersection()}. We introduce two unnamed template parameters with default values, that evaluate to the return type of the polygon-partition function when applied to a polygon of type \cppLstinline{PT1} or type \cppLstinline{PT2}, respectively; see Lines~16 and 17. As with the wrapping of the template functions in the previous two sections, the outcome of the evaluation is irrelevant. The only thing that matters is whether the evaluation succeeds---it succeeds only if the matching function is defined. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize, label=lst:minkSumResolution, caption={Automatic generation of binding for \cppLstinline{CGAL::minkowski_sum_2} exploiting SFINAE.}] template <typename T> class has { typedef void type; }; template <typename T, typename = void> struct target { typedef typename std::list<T>::iterator type; }; template <typename T> struct target<T, typename has<typename T::Polygon_2>::type> { typedef typename std::list<typename T::Polygon_2>::iterator type; }; template <typename T1, typename T2, typename T3> void bind_mink_sum_triplet(...) {} template <typename PT1, typename PT2, typename PP, typename = decltype(PP()(PT1(), typename target<PT1>::type())), typename = decltype(PP()(PT2(), typename target<PT2>::type()))> void bind_mink_sum_triplet(bool) { bp::def<Polygon_with_holes_2(const PT1&, const PT2&, const PP&)> ("minkowski_sum_2", &CGAL::minkowski_sum_2<Kernel, Point_2_container, PP>); } \end{lstlisting} \end{lstfloat} \noindent% We exploit SFINAE to generate bindings of other types as described in the following sections. \subsection{Arrangement Extension} \label{sec:code:ae} In many applications it is necessary to extend the type that represents certain {\sc Cgal}{} data structures with some types that represent new properties. In {\sc Cgal}{} it is more convenient, and thus more common to extend the types that represent the topological features of the data structures (rather than the types that represent the geometric features), e.g., the DCEL of the arrangement data structure; see Section~\ref{ssec:modules:aos2}. When developing code in pure C++, there is no restriction on the property types used to extend the data structure. However, when the data structure interface is wrapped with Python bindings, the property type must be known when the bindings are compiled. Nevertheless, we support extensions with generic Python objects. If a certain feature must be extended with a certain property, the type of which is defined in the C++ code, it is always possible to use an external property map, where the properties are indexed by a Python object, such as an integer or a string. When generating the bindings the user must set the flag that enables the extension; see Table~\ref{tab:aos}. Attaching an index to and extracting an index from a feature is done via the \cppLstinline{set_data()} and \cppLstinline{data()} exposed functions. Each cell type, namely, \cppLstinline{Vertex}, \cppLstinline{Halfedge}, or \cppLstinline{Face}, can be extended independently, which implies that there are eight plausible combinations that the user can select from to form the final DCEL type of the arrangement. Extending the arrangement features is useful for many applications, but essential for applications that compute the overlay of arrangements as discussed in the next Section. \subsection{Arrangement Overlay Traits} \label{sec:code:overlay} The map overlay of two arrangements ${\cal A}_1$ and ${\cal A}_2$, conveniently referred to as the \textcolor{red}{red} and \textcolor{blue}{blue} arrangements, is a third arrangement ${\cal A}$, such that there is a cell $c$ in ${\cal A}$ iff there are cells $c_1$ and $c_2$ in ${\cal A}_1$ and ${\cal A}_2$, respectively, and $c$ is a maximal connected component of $c_1 \cap c_2$. Computing the overlay of two arrangements is useful for many applications, including Boolean operations; see Section~\ref{ssec:modules:bso2}. Indeed, the \cgalPackage{2D Arrangements}{} package provides function templates that computes the overlay of two arrangements, namely overloaded \cppLstinline{CGAL::overlay()}. In particular, the call \cppLstinline{CGAL::overlay(arr_r, arr_b, arr)} computes the overlay of the arrangements \cppLstinline{arr_r} and \cppLstinline{arr_b} and stores the result in the arrangement \cppLstinline{arr}. All three types must be instances of the \cppLstinline{Arrangement_2<Traits, Dcel>} class template; see Section~\ref{ssec:modules:aos2}. When the function is used in pure C++ code, the geometry-traits classes that substitute the \cppLstinline{Traits} template parameters of the input arrangements must be convertible to the geometry-traits class of the resulting arrangement. We only wrap instances of the overlay function with Python bindings, where all three arrangements use the exact same geometry-traits classes and the same DCEL structures, and thus the types of the three arrangements of the exposed \cppLstinline{CGAL::overlay()} function are identical. The \cppLstinline{CGAL::overlay()} function template is overloaded with a variant that accepts four arguments. The last argument, referred to as the overlay traits, enables the update of cells of the output arrangement, and in particular their properties. Using the overlay traits is typically accompanied with the extension of one or more types of the arrangement cells that hold the properties. The overlay traits must model the \cppLstinline{OverlayTraits} concept, which requires the provision of ten functions that handle all possible overlapping cases as listed below. Let $v_r$, $e_r$, and $f_r$ denote input \textcolor{red}{red} cells, i.e.,~a vertex, an edge, and a face, respectively, $v_b$, $e_b$, and $f_b$ denote input \textcolor{blue}{blue} cells, and $v$, $e$, and $f$ denote output cells. \begin{compactenum} \item A new vertex $v$ is induced by coinciding vertices $v_r$ and $v_b$. \item A new vertex $v$ is induced by a vertex $v_r$ that lies on an edge $e_b$. \item An analogous case of a vertex $v_b$ that lies on an edge $e_r$. \item A new vertex $v$ is induced by a vertex $v_r$ that is contained in a face $f_b$. \item An analogous case of a vertex $v_b$ contained in a face $f_r$. \item A new vertex $v$ is induced by the intersection of two edges $e_r$ and $e_b$. \item A new edge $e$ is induced by the (possibly partial) overlap of two edges $e_r$ and $e_b$. \item A new edge $e$ is induced by the an edge $e_r$ that is contained in a face $f_b$. \item An analogous case of an edge $e_b$ contained in a face $f_r$. \item A new face $f$ is induced by the overlap of two faces $f_r$ and $f_b$. \end{compactenum} Evidently a custom C++ overlay traits cannot be defined in Python; more precisely, the traits type must be known when the bindings are compiled. We introduce and expose with Python bindings two models of the \cppLstinline{OverlayTraits} concept. The most general between the two, called \cppLstinline{Arr_overlay_traits}, defines ten functions that correspond to the list above, each accepting three arguments, namely, two objects that represent input cells, and one object that represents an output cell. By default these functions do nothing. A user (that is, a Python programmer) can override any subset of these functions. One constructor of this model accepts all the ten functions at once. Another constructor accepts a single function, which corresponds to Function (10) in the list above. In the following we assume that the face type of the arrangement is extended. The code excerpt in Listing~\ref{lst:twoFaceExtend} constructs two arrangements with two faces each. For each arrangement the properties of the unbounded face and the bounded face are initialized with Python integer objects~$0$ and~$1$, respectively. The code excerpt in Listing~\ref{lst:overlayTraits} computes the overlay of the two arrangements constructed by the code in Listing~\ref{lst:twoFaceExtend} using the overlay traits. The property of each face of the resulting arrangement is updated as part of the overlay computation to indicate the number of overlapping bounded faces; see Figure~\ref{fig:faceExt}. Observe that while the computation of the overlay is carried out by the compiled C++ code, the summation is carried out by a Python \pyLstinline{lambda} function, which accepts as the third argument the face to be updated. By default, arguments are copied into new Python objects. We pass the new face by reference, overriding the default, to enforce persistent updates. \begin{lstfloat} \defkd_tree.py{overlay.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, firstline=14,lastline=39, label={lst:twoFaceExtend}, caption={Constructing two arrangements with their faces extended and initializing their data.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\normalsize, label={lst:overlayTraits}, caption={Computing the map overlay of two arrangements using the general overlay traits.}] traits = Aos2.Arr_overlay_traits(lambda f1,f2,f: f.set_data(f1.data()+f2.data())) Aos2.overlay(arr1, arr2, result, traits) \end{lstlisting} \end{lstfloat} \begin{figure}[!htp] \captionsetup[subfigure]{justification=centering} \centering% \subfloat[]{\label{fig:faceExt} \begin{tikzpicture} \fill[polyALightColor] (0,0) rectangle (2,2); \fill[polyBLightColor,opacity=0.5] (1,1) rectangle (3,3); \draw[thick,polyADarkColor] (0,0) rectangle (2,2); \draw[thick,polyBDarkColor] (1,1) rectangle (3,3); \node at (2.5,0.5) {[0]}; \node at (0.5,0.5) {[1]}; \node at (2.5,2.5) {[1]}; \node at (1.5,1.5) {[2]}; \node[point] at (0,0) {}; \node[point] at (2,0) {}; \node[point] at (0,2) {}; \node[point] at (2,2) {}; \node[point] at (1,1) {}; \node[point] at (3,1) {}; \node[point] at (1,3) {}; \node[point] at (3,3) {}; \node[point] at (2,1) {}; \node[point] at (1,2) {}; \end{tikzpicture}}\quad\quad \subfloat[]{\label{fig:vertexExt} \begin{tikzpicture}[scale=0.2] \draw[thick,polyADarkColor] (3,4) circle (5); \draw[thick,polyADarkColor] (-3,-4) circle (5); \draw[thick,polyBDarkColor] (4,-3) circle (5); \draw[thick,polyBDarkColor] (-4,3) circle (5); \node[point=red!50!white,label={[label distance=-1pt]180:4}] at (-8, -4) {}; \node[point=green,label={[label distance=-1pt]180:6}] at (-7, -1) {}; \node[point=red!50!white,label={[label distance=-1pt]180:2}] at (-9, 3) {}; \node[point=red!50!white,label={[label distance=-1pt]180:4}] at (-2, 4) {}; \node[point=green,label={[label distance=-1pt]90:6}] at (-1, 7) {}; \node[point=red!50!white,label={[label distance=-1pt]180:2}] at (-1, -3) {}; \node[point=blue,label={[label distance=-1pt]0:12}] at (0, 0) {}; \node[point=green,label={[label distance=-1pt]-90:6}] at (1, -7) {}; \node[point=red!50!white,label={[label distance=-1pt]0:2}] at (1, 3) {}; \node[point=red!50!white,label={[label distance=-1pt]0:4}] at (2, -4) {}; \node[point=green,label={[label distance=-1pt]0:6}] at (7, 1) {}; \node[point=red!50!white,label={[label distance=-1pt]0:4}] at (8, 4) {}; \node[point=red!50!white,label={[label distance=-1pt]0:2}] at (9, -3) {}; \end{tikzpicture}} \caption[]{% (\subref{fig:faceExt}) The arrangement faces are extended with integers that indicate the number of overlapping bounded faces, shown in brackets. (\subref{fig:vertexExt}) The arrangement vertices are extended with integers that indicate the weighted degree of the vertices.} \label{fig:extend} \end{figure} In many cases, such as in the example above, the property of the new cell depends solely on the properties of the overlapping two cells. To this end we introduce (and expose) a second model of the \cppLstinline{OverlayTraits} concept called \cppLstinline{Arr_overlay_function_traits}. This model also defines ten functions that correspond to the list above. However, here each function accepts the two Python objects that extend the overlapping cells as input arguments and returns the Python object that extends the resulting cell. The code excerpt in Listing~\ref{lst:overlayFunctionTraits} has the same effect the code in Listing~\ref{lst:overlayTraits} has, but is more compact. \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\normalsize, label={lst:overlayFunctionTraits}, caption={Computing the map overlay of two arrangements using the functional overlay traits.}] traits = Aos2.Arr_overlay_function_traits(lambda x, y: x+y) os2.overlay(arr1, arr2, result, traits) \end{lstlisting} \end{lstfloat} Each one of the ten functions supported by the \cppLstinline{Arr_overlay_function_traits} model returns a Python object that is passed back to the compiled C++ code. Then, the object is stored with the new cell. Thus, there is no need to pass arguments by reference (even though it could be more efficient in certain cases); however, the implementation of this model presents a new coding challenge---if a certain cell is not extended, attempting to access its non-existing extension would cause a compilation error. Assume that only the vertex type of the \cppLstinline{Arrangement_2} instance is extended. The Python code excerpt in Listing~\ref{lst::overlayCircleSegment} computes the overlay of two arrangements and updates the property of each vertex of the resulting arrangement to indicate the weighted degree of the vertex, where blue incident edges weigh twice as much as red incident edges; see Figure~\ref{fig:vertexExt}. We set all the six functions that update output vertices in the \cppLstinline{Arr_overlay_function_traits} object using dedicated setters. The name of a setter matches the pattern \lstinline[language={C++},mathescape=true,columns=fixed]{set_$c_rc_b$_$c$()}, where each of $c_r$, $c_b$, and $c$ can be substituted with \cppLstinline{v}, \cppLstinline{e}, or \cppLstinline{f}. $c_r$ and $c_b$ determine the input red and blue cell types, respectively, and $c$ determines the output cell type. \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\normalsize, label={lst::overlayCircleSegment}, caption={Constructing two arrangements with their vertices extended and computing their map overlay using the overlay function traits.}] Aos2.insert(arr1,[Curve(Circle(Point(3,4),25)),Curve(Circle(Point(-3,-4),25))]) Aos2.insert(arr2, [Curve(Circle(Point(3,4),25)), Curve(Circle(Point(3,4),25))]) for arr in [arr1, arr2]: for v in arr.vertices(): v.set_data(v.degree()) traits = Aos2.Arr_overlay_function_traits() traits.set_vv_v(lambda x, y: 2*x+y) traits.set_ve_v(lambda x, y: 2*x+2) traits.set_vf_v(lambda x, y: 2*x) traits.set_ev_v(lambda x, y: 4+y) traits.set_fv_v(lambda x, y: y) traits.set_ee_v(lambda x, y: 6) Aos2.overlay(arr1, arr2, result, traits) \end{lstlisting} \end{lstfloat} Consider a generic function called \cppLstinline{apply()} that accepts two objects that represent input cells, namely \cppLstinline{r} and \cppLstinline{b}, one object that represents an output cell, namely \cppLstinline{o}, and a function called \cppLstinline{f}. The objective of \cppLstinline{apply()} is to apply \cppLstinline{f} to the properties of the cells \cppLstinline{r} and \cppLstinline{b} and store the return value as the property of the cell \cppLstinline{o}. Recall that a property of a cell \cppLstinline{c} is obtained and set via the calls \cppLstinline{c.data()} and \cppLstinline{c.set_data()}, respectively. If the type of the output cell is not extended, however, \cppLstinline{apply()} should become idle. Similarly, if the type of an input cell is not extended, the \pyLstinline{None} Python object (represented by \cppLstinline{bp::object}) should be passed to \cppLstinline{f} instead. We use SFINAE yet again, twice, to address the above. First, we introduce an overload of \cppLstinline{apply()} that is idle and serves as a fall-through; see Line~9 in Listing~\ref{lst:data}. When a call to \cppLstinline{apply()} is made, the idle overload is selected by the overload resolution process if the output cell does not have a member called \cppLstinline{set_data()}. If the output cell does have this member the other implementation is selected and calls \cppLstinline{data(r)} and \cppLstinline{data(b)} to obtain the properties of the \textcolor{red}{red} and \textcolor{blue}{blue} input cells, respectively. Second, we introduce an overload of \cppLstinline{data()} that serves as a fall-through (Line~2). It does nothing but return the \pyLstinline{None} Python object. It is selected if the corresponding cell does not have a member called \cppLstinline{data()}. If the cell does have this member the other implementation is selected; it returns the property of the cell. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize, label={lst:data}, caption={Automatic generation of bindings for the overlay function traits exploiting SFINAE.}] // Fall-through; A::data() does not exist template <typename A> bp::object data(...) { return bp::object(); } // A::data() exists template <typename A, typename = decltype(std::declval<A>().data())> const bp::object& data(const A* a) { return a->data(); } // Fall-through; O::set_data() does not exist template <typename R, typename B, typename O, typename F> void apply(...) {} // O::set_data() does exist template <typename R, typename B, typename O, typename F, typename = decltype(std::declval<O>().set_data(std::declval<typename O::Data>()))> void apply(const R* r, const B* b, O* o, F f) { o->set_data(f(data<R>(r), data<B>(b))); } \end{lstlisting} \end{lstfloat} \subsection{Miscellaneous} \label{sec:code:misc} In this section we list additional techniques used by the binding code. \subsubsection{Handle, iterators, and Circulators} \label{sec:code:misc:iters} The \cppLstinline{Handle} concept, provided by the \cgalPackage{Handles and Circulators}{} package~\cite{cgal:dksy-hc-21a}, describes types that are akin to pointers to objects. A handle provides the dereference operator (\cppLstinline{operator*()}) and the member access operator (\cppLstinline{->()}). Since Python does not have any kind of pointers, both a handle to an object in {\sc Cgal}{} and the object itself are converted to the same Python object. For example, both types \cppLstinline{Arrangement_2::Vertex} and \cppLstinline{Arrangement_2::Vertex_handle} are converted to the Python type \pyLstinline{Vertex}, which is an attribute of the Python type \pyLstinline{Arrangement_2}. The \cppLstinline{Iterator} concept and its refinements describe types that can be used to identify and traverse the elements of container that contains sequential data.\footnote{For more information about STL iterators, see, e.g., \url{https://en.cppreference.com/w/cpp/iterator}.} An iterator provides the increment or decrement operators. In {\sc Cgal}{} quite often an iterator is convertible to a handle, for example, \cppLstinline{Arrangement_2::Vertex_iterator} is convertible to \cppLstinline{Arrangement_2::Vertex_handle}. Therefore, also \cppLstinline{Arrangement_2::Vertex_iterator} is converted to the python class \pyLstinline{Vertex}. Every converted iterator is supplied with both magic functions \pyLstinline{__iter__} and \pyLstinline{__next__}, thus made a \emph{Python iterator}.\footnote{For more information about Python iterators, See, e.g., \url{https://docs.python.org/3/c-api/iterator.html}.} The \pyLstinline{__iter__} function simply returns the input object, and the \pyLstinline{__next__} function returns the next object in the traversal order of the corresponding iterator. Similar to the \cppLstinline{Iterator} concept and its refinements, the \cppLstinline{Circulator} concept and its refinements, also provided by the \cgalPackage{Handles and Circulators}{} package, describe types that can be used to identify and traverse the elements of container that contains circular data, for example, the halfedges incident to a face or the halfedges incident to a vertex in an arrangement. A circulator object does not have a past-the-end value. Instead, the range $[a, b)$ of two circulators $a$ and $b$ denotes either the empty range, or the sequence of all elements in the container. Boost.Python supports several features that aid in the wrapping if iterators. Circulators are artificially converted to iterators to leverage on those features. In addition, while traversing a circulator, an stop-iteration exception is thrown when a circular refers to an item that has been traversed already. \subsubsection{Functions Accepting Collections of Elements} \label{sec:code:input} The Standard Template Library (STL) provides various type-safe containers for storing collections of related objects. The \cppLstinline{Container} concept describes types of objects that store collections of other objects (their elements).\footnote{For more information about STL containers, see, e.g., \url{https://en.cppreference.com/w/cpp/container}.} Container models are implemented as class templates, which enables great flexibility in the elements types and in the implemented algorithms that operate on container objects. Traditionally, implementations of algorithms in C++ manipulate iterators pointing into the containers they operate on. To date it is popular to pass a collection of elements to a function via two generic input iterators, where the first points at the first element of a container and the second points past the end of the container. An input iterator object, the type of which is a model of the the \cppLstinline{InputIterator} concept, \footnote{For more information of output iterators, see, e.g., \url{https://en.cppreference.com/w/cpp/iterator/input_iterator}.} supports reading from the location obtained via the dereference operator and can be pre- and post incremented. The Boost.Range library provides an alternative modern method, which uses \emph{ranges}, for applying algorithms on collections of objects. In particular, it utilizes a new family of concepts that refine a basic concept called \cppLstinline{Range}. The \cppLstinline{Range} concept is similar to the \cppLstinline{Container} concept; it requires the provision of iterators for accessing a half-open range of elements and provides information about the number of elements in the range. The new method results in code that is more efficient and more expressive (and thus more comprehensible).\footnote{See \url{https://www.boost.org/doc/libs/1_78_0/libs/range/doc/html/index.html} for the documentation of Boost.Range.} Soon, (C++20) ranges will become part of the standard.\footnote{For more information about STR ranges, see, e.g., \url{https://en.cppreference.com/w/cpp/ranges}.} The \cgalPackage{Handles and Circulators}{} package of {\sc Cgal}{} provides a variant of a \cppLstinline{Range} concept suitable for {\sc Cgal}{}. Many functions in {\sc Cgal}{} accept as input collections of elements, and some of them already use this concept. The use of ranges is expected to grow. For every function in {\sc Cgal}{} that operates on one or more collections of elements, and regardless of the interface of the function, that is, whether a pair of generic input iterators, or a range, is used to represent each collection, we introduce and expose a wrapper function that accepts a Python list (of type \cppLstinline{bp::list}) as an argument;\footnote{For more information on Python lists, see, e.g., \url{https://docs.python.org/3/tutorial/datastructures.html\#more-on-lists}.} the wrapper function calls the original function, properly passing the input collection; see Listing~\ref{lst:insert} for an example of such a function that uses iterators; the wrapper function is shown in Listing~\ref{lst:insertWrapper}; an excerpt code in Python that exploits the above is shown in Listing~\ref{lst:insertPython}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:insert},% caption={The signature of the free function that inserts a collections of curves into an arrangement.}] template <typename InputIterator> CGAL::insert(Arrangement_2& arr, InputIterator first, InputIterator past_the_end) \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:insertWrapper},% caption={A function that wraps the function shown in Listing~\ref{lst:insert} and accepts a Python list that contains the input curves.}] void insert_curves(Arrangement_2& arr, bp::list& lst) { if (! lst) return; if (bp::extract<X_monotone_curve_2>(lst[0]).check()) { auto begin = bp::stl_input_iterator< X_monotone_curve_2 >(lst); auto end = bp::stl_input_iterator< X_monotone_curve_2 >(); CGAL::insert(arr, begin, end); } else if (bp::extract<Curve_2>(lst[0]).check()) { auto begin = bp::stl_input_iterator< Curve_2 >(lst); auto end = bp::stl_input_iterator< Curve_2 >(); CGAL::insert(arr, begin, end); } } \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\normalsize,% label={lst:insertPython},% caption={A code sample in Python that inserts three curves into an arrangement.}] arr = Arrangement_2() c1 = X_monotone_curve_2(Point_2(0, 0), Point_2(1, 0)) c2 = X_monotone_curve_2(Point_2(1, 0), Point_2(0, 1)) c3 = X_monotone_curve_2(Point_2(0, 1), Point_2(1, 1)) Aos2.insert(arr, [c1, c2, c3]) \end{lstlisting} \end{lstfloat} \subsubsection{Functions Resulting in Collections of Elements} \label{sec:code:output} Functions may compute collections of elements as results. Using output iterators enables an efficient and flexible method for passing output collections from functions. An output iterator object, the type of which is a model of the the \cppLstinline{OutputIterator} concept,\footnote{For more information of output iterators, see, e.g., \url{https://en.cppreference.com/w/cpp/iterator/output_iterator}.} supports writing to the location obtained by the dereference operator and can be pre- and post-incremented. A function that computes a collection of elements accepts an output iterator as an argument and populates the underlying collection. Modern C++ compilers support the efficient transfer of resources from one object of a certain type to another object of the same type, referred to as \emph{move semantics}.\footnote{For more information of move semantics, see, e.g., \url{https://en.cppreference.com/w/cpp/language/move_constructor}.} If the underlying collection supports move semantics, a function that computes a collection of elements can simply return the collection, resulting in an elegant yet efficient code. For every function in {\sc Cgal}{} that results in a collection of elements, and regardless of the interface of the function, that is, whether an output iterator is used or the collection is returned, we introduce and expose a wrapper function that returns a Python list (of type \cppLstinline{bp::list}); the wrapper function calls the original function, properly populating a Python list with the output collection, and finally it returns the list. The free function template \cppLstinline{CGAL::decompose()} accepts an arrangement $\mathcal{A}$ and computes a collection of polymorphic elements via an output iterator. For each vertex $v$ of $\mathcal{A}$ the output collection contains a pair of features---one that directly lies below $v$ and another that directly lies above $v$. Let $v$ be a vertex of $\mathcal{A}$. The feature above (respectively below) $v$ may be one of the following: \begin{compactitem} \item Another vertex $u$ having the same $x$-coordinate as $v$. \item An arrangement edge associated with an $x$-monotone curve that contains $v$ in its $x$-range. \item An unbounded face in case $v$ is incident to an unbounded face, and there is no curve lying above (respectively below) it. \item An empty object, in case $v$ is the lower (respectively upper) endpoint of a vertical edge in the arrangement. \end{compactitem} Listing~\ref{lst:decompose} shows the signature of the function. Dereferencing the output iterator must yield an object the type of which is \cppLstinline{Decompose_result} shown in Listing~\ref{lst:decomposeResult}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:decompose},% caption={The signature of the free function that decomposes an arrangement into pseudo trapezoids.}] template <typename OutputIterator> CGAL::decompose(Arrangement_2& arr, OutputIterator oi); \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:decomposeResult},% caption={The type of an output element of the \cppLstinline{CGAL::decompose()} function shown in Listing~\ref{lst:decompose}.}] typedef std::pair<Arrangement_2::Vertex_const_handle, std::pair<boost::optional<variant>, boost::optional<variant>>> Decompose_result; \end{lstlisting} \end{lstfloat} Populating a standard container, say \cppLstinline{container}, the elements of which are of the \cppLstinline{Decompose_result} polymorphic type, with the data computed by \cppLstinline{CGAL::decompose()} function in C++, can be done, for example, by passing an object of type \cppLstinline{std::back_insert_iterator<Decompose_result>} obtained by the call \cppLstinline{std::back_inserter(container)}, as the output iterator argument to the function. We introduce a similar iterator called \cppLstinline{apply_iterator} shown in Listing~\ref{lst:applyIterator} that can be used to efficiently populate a Python list instead of a container. The constructor of this function object accepts a generic unary function and stores it for later use. It applies the operator on every element that needs to be appended to the outout Python list. Each element of the list is a Python tuple of two items, the first is a vertex and the second is another Python tuple of two items, the first is the cell above the vertex or \pyLstinline{bp::Object} is none exists and the first is the cell below the vertex or \pyLstinline{bp::Object} is none exists. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:applyIterator},% caption={An output iterator that applies an operation on every output element.}] template <typename UnaryOperation> class apply_iterator { private: UnaryOperation m_op; public: apply_iterator(UnaryOperation op) : m_op(op) {} // Make sure the assignment operator is available apply_iterator& operator=(const apply_iterator& other) { m_op = other.m_op; return *this; } template <typename T> const T& operator=(const T& t) const { m_op(t); return t; } apply_iterator& operator*() { return *this; } apply_iterator& operator++() { return *this; } apply_iterator operator++(int) { return *this; } }; \end{lstlisting} \end{lstfloat} The wrapper function of the \cppLstinline{CGAL::decompose()} function is shown in Listing~\ref{lst:decomposeWrapper}. It utilizes a helper function called \cppLstinline{decompose_helper()} (not listed) that appends the output elements to the outout Python list. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:decomposeWrapper},% caption={A function that wraps the function shown in Listing~\ref{lst:decompose} and returns a Python list that represents a vertical decomposition.}] bp::list decompose(Arrangement_2& arr) { typedef std::pair<Arrangement_2::Vertex_const_handle, std::pair<boost::optional<variant>, boost::optional<variant>>> Decompose_result; bp::list lst; auto op = [&] (const Decompose_result& res) { decompose_helper(res, lst); }; CGAL::decompose(arr, apply_iterator<decltype(op)>(op)); return lst; } \end{lstlisting} \end{lstfloat} The Python code example shown in Listing~\ref{lst:py:decompose} exploits the above and computes the vertical decomposition shown in Figure~\ref{fig:decompose}. \begin{lstfloat} \defkd_tree.py{vertical_decomposition.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize,% label={lst:py:decompose},% firstline=15, caption={A code sample in Python that decomposes an arrangement.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \begin{figure}[!htp] \centerline{% \begin{tikzpicture} \draw node[point=white] (x) at (4,2) {}; % \draw node[point] (u1) at (0,0) {}; \draw node[point=cyan] (u2) at (2,2) {}; \draw node[point] (u3) at (3,3) {}; \draw node[point=cyan] (u4) at (5,1) {}; \draw node[point] (u5) at (6,0) {}; \draw[blue,thick] (u1)--(u2)--(u3)--(x)--(u4)--(u5); % \draw node[point] (v1) at (2,0) {}; \draw node[point=cyan] (v2) at (3,1) {}; \draw node[point] (v3) at (5,3) {}; \draw node[point=cyan] (v4) at (6,2) {}; \draw node[point] (v5) at (8,0) {}; \draw[blue,thick] (v1)--(v2)--(x)--(v3)--(v4)--(v5); % \draw[dots=10 per 1cm,very thick] (0,-1)--(u1)--(0,4); \draw[dots=10 per 1cm,very thick] (2,-1)--(v1)--(u2)--(2,4); \draw[dots=10 per 1cm,very thick] (3,-1)--(v2)--(u3)--(3,4); \draw[dots=10 per 1cm,very thick] (4,-1)--(x)--(4,4); \draw[dots=10 per 1cm,very thick] (5,-1)--(u4)--(v3)--(5,4); \draw[dots=10 per 1cm,very thick] (6,-1)--(u5)--(v4)--(6,4); \draw[dots=10 per 1cm,very thick] (8,-1)--(v5)--(8,4); \end{tikzpicture}} \caption{An arrangement of four line segments and its vertical decomposition into pseudo trapezoids, as constructed by the Python code shown in Listing~\ref{lst:py:decompose}. The segments of the arrangement are drawn in solid blue lines and the segments of the vertical decomposition are drawn in dark dotted lines.} \label{fig:decompose} \end{figure} \section{Comparison} \label{sec:comp} There are several different tools and options for generating Python bindings. The following is by no means an exhaustive list of such tools; however, it gives a taste of the rich possibilities one faces when there is a need to make C++ code accessible to Python developers. One goal that all these tools share is transforming Python/C API into a relatively more user-friendly interface. Most listed tools are designed to wrap C++ interfaces non-intrusively; that is, the C++ code of an entity does not change when it is wrapped. \subsection{Various Tools} \label{ssec:comp:tools} \pyLstinline{ctypes} is a foreign function module for Python that provides C compatible data types.\footnote{See \url{https://docs.python.org/3/library/ctypes.html\#module-ctypes}.} It supports the loading of shared libraries and marshaling data between Python and C.\footnote{Marshaling is the process of transforming the memory representation of an object into a data format suitable for storage or transmission; see \url{https://en.wikipedia.org/wiki/Marshalling\_(computer\_science)}.} The \pyLstinline{ctypes} module is part of the Python standard library; thus, it can be used to wrap shared libraries in pure Python. Using the \pyLstinline{ctypes} module requires manual programming labour and detailed knowledge of the \pyLstinline{ctypes} interface. However, it does not require writing C code (in addition to existing C code that needs to be wrapped). \pyLstinline{cffi} is another Python module that generates Python bindings (it stands for C Foreign Function Interface). It interacts with almost any C code from Python, based on C-like declarations that can often be copy-pasted from header files. It is compatible with both PyPy and CPython; Moreover, in the PyPy (see~\ref{ssec:intro:bind}) reference implementation it is a first class citizen (and provided by defaut), thus, exhibits outstanding preformance. Compared to \pyLstinline{ctypes}, the \pyLstinline{cffi} module takes a more automated approach to generate Python bindings and it minimized the extra bits of API that need to be mastered; thus, it scales better to larger projects than \pyLstinline{ctypes}. Like \pyLstinline{ctypes}, using \pyLstinline{cffi} directly interfaced with C libraries only. Warapping C++ libraries with any one of these modules requires the provision of another layer of C wrapper around the C++ code. \pyLstinline{cppyy} is yet another external module for generating bindings.\footnote{See \url{https://cppyy.readthedocs.io}.} It is an automatic, run-time, C++ Python bindings generator, for calling C++ from Python and Python from C++.\footnote{See \url{https://cppyy.readthedocs.io}.} Run-time generation enables detailed specialization for higher performance, lazy loading for reduced memory use in large scale projects, Python-side cross-inheritance and callbacks for working with C++ frameworks, run-time template instantiation, automatic object downcasting, exception mapping, and interactive exploration of C++ libraries. \pyLstinline{cppyy} delivers this without any language extensions, intermediate languages, or the need for boiler-plate hand-written code. For design and performance, see~\cite{ld-hppcn-16}, albeit that the \pyLstinline{cppyy} performance has been vastly improved since. Like \pyLstinline{cffi}, \pyLstinline{cppyy} was designed to ease binding development for the Python programmer, minimizing the need for extra C++ code; it is also compatible with both CPython and PyPy. A completely different approach is adopted by Cython~\cite{bbcds-cbbw-11}, which refers to a programming language and to an optimising static compiler for the Cython language.\footnote{See \url{https://cython.org/}.} The Cython language is a superset of the Python language. It extends Python with explicit type declarations of native C/C++ types. Cython is a compiled language used to generate CPython extension modules. The Cython compiler generates C/C++ code from Cython code, which in turn compiles with any C/C++ compiler, and is automatically wrapped in interface code, producing extension modules that can be loaded and used by regular Python code using the \pyLstinline{import} statement, but with significantly less computational overhead at run time. Cython also facilitates wrapping independent C or C++ code into python-importable modules. With Cython it is possible to call back and forth between Python code, Cython code, and native library code origianally developed in Fortran, C, or C++. SIP is a collection of tools that makes it easy to create Python bindings for C and C++ libraries.\footnote{See \url{https://pypi.org/project/sip/}.} It was originally developed in 1998 to create PyQt, the Python bindings for the Qt toolkit, but can be used to create bindings for any C or C++ library. SIP comprises a set of build tools and a module called sip. The build tools process a set of specification files and generates C or C++ code, which is then compiled to create the bindings extension module. Several extension modules may be installed in the same Python package. Extension modules can be built so that they are are independent of the version of Python being used. SWIG is a software development tool that connects programs written in C and C++ with a variety of high-level programming languages.\footnote{See \url{http://www.swig.org/}.} It is different than any of the others tools listed here. SWIG is used to create bindings to C and C++ code for different types of target languages, and not only Python, including common scripting languages such as Javascript, Perl, PHP, Python, Tcl, or Ruby. The list of supported languages also includes non-scripting languages such as C\#, D, Go language, Java including Android, Lua, OCaml, Octave, Scilab and R. Also several interpreted and compiled Scheme implementations (Guile, MzScheme/Racket) are supported. SWIG is most commonly used to create high-level interpreted or compiled programming environments, user interfaces, and as a tool for testing and prototyping C/C++ software. SWIG is typically used to parse C/C++ interfaces and generate the 'glue code' required for the above target languages to call into the C/C++ code. SWIG can also export its parse tree in the form of XML. SWIG is free software and the code that SWIG generates is compatible with both commercial and non-commercial projects. Boost is a large and sophisticated suite of utility libraries that works with almost every C++ compiler in existence. Boost.Python~\cite{bhsbp-ag-03} is a member of the Boost suit that enables seamless interoperability between C++ and the Python programming language.\footnote{See \url{https://www.boost.org/doc/libs/1_70_0/libs/python/doc/html/index.html}.} similar to \pyLstinline{cppyy}, Boost.Python focuses at C++; unlike \pyLstinline{cppyy} it uses C++ to specify and build bindings, taking advantage of the metaprogramming tools and polymorphism in C++. The library includes support for: \begin{compactitem} \item References and shared pointers (which are handled extremely gracefully) \item Globally Registered Type Coercions \item Automatic Cross-Module Type Conversions \item Efficient Function Overloading \item C++ to Python Exception Translation \item Default Arguments \item Keyword Arguments \item Manipulating Python objects in C++ \item Exporting C++ Iterators as Python Iterators \item Documentation Strings \end{compactitem} pybind11 is a lightweight header-only library that exposes C++ types in Python and vice versa, mainly to create Python bindings of existing C++ code.\footnote{See \url{https://github.com/pybind/pybind11}.} Its goal, like the goal of Boost.Python, is to minimize boilerplate code in traditional extension modules by inferring type information using compile-time introspection. Its syntax is also similar to the syntax of Boost.Python. In fact, it is a tiny self-contained version of Boost.Python with everything stripped away that isn't relevant for binding generation. Without comments, the core header files only require approximately 4K lines of code and depend on Python and the C++ standard library. This compact implementation was possible thanks to some of the new C++11 language features (specifically, tuples, lambda functions and variadic templates). Since its creation, this library has grown beyond Boost.Python in several ways, leading to simpler binding code in many common situations. We have concentrated on three tools, namely (i) SWIG, (ii) PyBind11, and (iii) Boost.Python and conducted several experiments to compare the performance of the respective generated bindings; see Section~\ref{ssec:comp:exp}. \subsection{Experiments} \label{ssec:comp:exp} C++ Python bindings for a certain subset of {\sc Cgal}{} packages are available as part of an experimental project that uses SWIG. While the project has been conceived more than a decade ago, it contains bindings only for a limited subset of {\sc Cgal}{} packages. Naturally, embarking on the existing venture might have saved time in developing new bindings, on the one hand, and in exploiting the new bindings by our users on the other. Another advantage of using SWIG, and probably the reason for choosing SWIG in the first place in the aforementioned project, is the support for multiple languages. Once bindings have been developed for one language, generating bindings for additional languages does not require additional development resources. However, as our experiments show, this profiteering has its cost---the generated bindings are not as time or space efficient as their counterparts generated with other tools. The PyBind11 tool is relatively new. Both the PyBind11 and the Boost.Python tools are widely spread and tested, and actively maintained and enhanced. They are developed using advanced features of C++11 and higher versions. These two tools share the same interface; that is, the C++ code used to generate the bindings using both tools is similar and in some cases even identical. Switching between using bindings generated by PyBind11 and bindings generated by Boost.Python is seamless---it amounts to replacing one library by another. As we are very much familiar with developing code that exploits advanced feature of C++, developing bindings using these tools does not present a major hurdle for us. On the other hand, developing bindings using SWIG, requires writing code that describe the bindings in a proprietary language. Some developers may avoid using Boost.Python, because it requires dealing with a large and complex system. This does not present a drawback for us, because {\sc Cgal}{} itself depends on several other libraries of Boost; thus, we are familiar with Boost and must deal with it anyway. The compatibility of Boost with almost every C++ compiler in general has its cost; arcane template tricks and workarounds are necessary to support the oldest and buggiest of compiler specimens. Now that C++11-compatible compilers are widely available, the heavy machinery required to support the wide range of compilers may take some toll. However, our main concern was the efficiency of the generated bindings in terms of execution time and memory space. We have conducted two sets of experiments. In the first set we compared the time it took to refer to C++ objects from Python code and in the second set we compared the time it took to call C++ functions from Python code. The first set was further divided into two subsets. In the first subset we compared the time it took to make many references to many objects and in the second subset we compared the time it took to make many references to a single object; see Table~\ref{tab:res:refs} for the results. The second set was further divided into too subsets as well. In the first subset we compared the time it took to call many small functions, and in the second subset we compared the time it took to call few large functions. We also used the second set of experiments to measure the time it took to compute the various tasks in native Python; see Table~\ref{tab:res:calls} for the results. All benchmark programs were executed on a machine equipped with an Intel Core~i5 clocked at~3.5GHz with~16GB of RAM. The results we obtained left nothing in doubt. We picked Boost.python for its high efficiency in every category. \begin{table} \caption{Time consumption of references measured in seconds.} \label{tab:res:refs} \centering\begin{tabular}{|l|r|r|r|} \hline & \textbf{pybind11} & \textbf{boost} & \textbf{SWIG}\\ \hline \hline Many references to many objects & 6.031 & 4.453 & 15.687\\ \hline Many references to a single object & 4.906 & 2.796 & 9.640\\ \hline \end{tabular} \end{table} \begin{table} \caption{Time consumption of function calls measured in seconds.} \label{tab:res:calls} \centering\begin{tabular}{|l|r|r|r|r|} \hline & \textbf{pybind11} & \textbf{boost} & \textbf{SWIG} & \textbf{Native}\\ \hline \hline Many small tasks & 26.718 & 13.656 & 13.140 & 13.359\\ \hline One large task & 0.718 & 0.718 & 0.734 & 17.843\\ \hline \end{tabular} \end{table} \section{Concepts-Binding Coupling} \label{sec:concepts} Generic programming enables the implementation of generic algorithms, which work on collections of different types, can be easily maintained, extended, and customized, and are type safe and easier to read. As mentioned in the introduction, {\sc Cgal}{} rigorously adheres to the generic programming paradigm. As a consequence, most components of {\sc Cgal}{} are either class or function templates. Many of the parameters of these templates are described in terms of models of concepts. When a class or a function template is instantiated, each one of its template parameters is substituted with a model of one or more concepts associated with the template parameter. Close to~750 concepts can be identified in {\sc Cgal}{} at the time this article is written. Most hierarchy graphs of concepts are small. Few graphs, such as the graph of concepts of the geometry traits of the \cgalPackage{2D Arrangements}{} package, are quite large with intricate refinement relations. We use clusters of closely related concepts to describe the refinement relations among them; see, e.g., Figure~\ref{fig:atc}. We have introduced tight coupling between concepts and (i) binding generations and (ii) type annotation. We describe these relations in the following sections. \subsection{Following Generic Concepts} \label{sec:code:concepts} For each concept we have introduced a template function that generates bindings for all the type and function members required by the concept. We call this function for every model of the concept. This systematic approach guaranties that all the documented functions and types, but nothing else, are exposed. Consider for example the cluster of geometry traits concepts depicted in Figure~\ref{fig:atc:central}. The template functions \cppLstinline{export_AosBasicTraits\_2()}, \cppLstinline{export_AosXMonotoneTraits\_2()}, and \cppLstinline{export_AosTraits\_2()} accept binding class objects\footnote{A binding class object of type \cppLstinline{bp:class_<T>} is used to expose the C++ type \cppLstinline{T} to Python.} for particular geometry traits models and populate it with all attributes that correspond to the requirements of the concepts \cppLstinline{AosBasicTraits\_2}, \cppLstinline{AosXMonotoneTraits\_2}, and \cppLstinline{AosTraits\_2}, respectively. If a concept \cppLstinline{B} refines a concept \cppLstinline{A}, then the function \cppLstinline{export_B()} calls the function \cppLstinline{export_A()}. The bindings of different traits models are generated in separate compilation units. As nodes in the concept refinement graphs may have more than a single parent, we ensure that a function that corresponds to a concept is not invoked more than once in a given compilation unit; see Lines~3--4 in the definition of the function \cppLstinline{export_AosBasicTraits\_2()} in Listing~\ref{lst:cpp:exportBasic}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:cpp:exportBasic},% caption={Exposing attributes that correspond to the concept \cppLstinline{AosBasicTraits_2}.}] template <typename GeometryTraits_2, typename ClassObject, typename Concepts> void export_AosBasicTraits_2(ClassObject c, Concepts& concepts) { // Sentinel static bool exported = false; if (exported) return; // Expose attributes that correspond to the traits auto& classes = concepts.m_basic_traits_classes; classes.m_point_2 = bp::class_<Point_2>("Point_2") .def(bp::init<>()) .def(bp::init<const Point_2&>()); ~~$\cdots$~~ } \end{lstlisting} \end{lstfloat} Typically, a concept in our case requires the provision of nested types that are themselves models of other concepts. For example, the concept \cppLstinline{AosBasicTraits\_2} requires the provision of the nested type \cppLstinline{Point_2} used to represent a two-dimensional point. The type \cppLstinline{Point_2} must be \cppLstinline{DefaultConstructible} and \cppLstinline{CopyConstructible}. Let \cppLstinline{p} be an object of type \cppLstinline{Point_2} required by the \cppLstinline{AosBasicTraits\_2} concept. Most traits models also support the calls \cppLstinline{p.x()} and \cppLstinline{p.y()}; they return the $x$ and $y$ coordinates of the points $p$, respectively. The number type used to represent the coordinates depends on the traits instance; for example, the type \cppLstinline{Kernel::FT} is used for the \cppLstinline{Arr_segment_traits<Kernel>} traits instance. However, the \cppLstinline{Point_2} type nested in the traits model \cppLstinline{Arr_Bezier_curve_traits\_2} does not maintain an exact representation of the coordinates. Thus, it instead supports the call \cppLstinline{p.approximate()}, which returns a pair of floating point numbers that only approximate the real coordinates. The function \cppLstinline{export_AosBasicTraits\_2()} constructs a class object for the \cppLstinline{Point\_2} type, but adds nothing but Python attributes that expose the default and copy constructors of this type; see Lines~10--11 in the definition of the function \cppLstinline{export_AosBasicTraits\_2()} in the listing. It also saves the class object of the \cppLstinline{Point_2} type (see Line~8), so that later on the functions responsible for the bindings of the various traits models can add additional Python attributes. For example, the function that exposes the \cppLstinline{Arr_segment_traits<Kernel>} instance adds the attributes \pyLstinline{x} and \pyLstinline{y}, which expose the member functions \cppLstinline{x()}, \cppLstinline{y()}, respectively, to the Python object that exposes the type \cppLstinline{Point_2}. Similarly, the function that exposes the \cppLstinline{Arr_Bezier_curve_traits\_2} instance adds the attribute \pyLstinline{approximate}, which exposes the member function \cppLstinline{approximate()} to the Python object that exposes the type \cppLstinline{Point_2}. The concept \cppLstinline{AosHorizontalSideTraits\_2} requires the provision of the \cppLstinline{Compare\_x\_on\_boundary\_2} functor\footnote{A functor is a class that has one or more \cppLstinline{operator()} members; thus, it acts as a function.} that has two implementations of \cppLstinline{operator()} as follows; one overload accepts two ends of open or unbounded curves (refer to the manual for the precise encoding of a curve end) and another overload accepts a point and an end of a curve that is open or unbounded at that end. The former compares the $x$-coordinates of the curves at their respective limits or ends and the latter compares the $x$-coordinates of the point and the $x$-coordinates of the curve at its respective limit or end. The concept \cppLstinline{AosIdentifiedHorizontalTraits\_2} indirectly refines the concept \cppLstinline{AosHorizontalSideTraits\_2} mentioned above. (The former would be used to define a traits model that handles arcs on a sphere with poles on the left and right sides; Figure~\ref{fig:atc:sphericalBoundary} depicts a cluster of concepts for models that handle arcs on a sphere with poles on the top and bottom sides.) In addition to the two implementations of the overloaded members \cppLstinline{operator()} of the functor \cppLstinline{Compare\_x\_on\_boundary\_2} it requires the provision of a third implementation that accepts two points and compares their $x$ coordinates. Similar to the case described in the previous paragraph, where the class object that handles the bindings for the \cppLstinline{Point_2} type must be available in two separate functions, also here the class object that handles the bindings for the functor \cppLstinline{Compare\_x\_on\_boundary\_2} must be available in both functions \cppLstinline{export_AosHorizontalSideTraits\_2()} and \cppLstinline{export_AosIdentifiedHorizontalTraits\_2()}. Saving the class object in one function so that it can be reused latter on in the other addresses this necessity. \subsection{Type Annotation} \label{ssec:concepts:annotation} {\sc Cgal}{} is a large library to start with. It is divided into approximately~150 packages with countless function and class templates. The vast number of function and type instances that can be defined using these templates can be overwhelming. The development of non critical code that is based on {\sc Cgal}{} can be expedited using Python and {\sc Cgal}{} Python bindings. Using code completion (which is based on type annotations) offered by several Python IDEs can accelerate the development process much further. Type annotation in Python refers to annotations of Python functions, arguments, and variables in a way that can be used by various tools. It is an optional feature of Python that has been introduced in Version~3.5 and enhanced in successive versions. With this feature implemented a type checker, a tool separate from the Python interpreter, can be used to statically analyze code base to find bugs during early development stages and spelunk code of large projects. Naturally, it can be used by IDEs to interactively provide hints and suggestions to programmers and type check the code as it is being developed. Annotations can and should be placed near the code if possible. Observe that the Python interpreter ignores these annotations. Annotations can also be placed in external files (which have the extension \lstinline{.pyi}), referred to as stubs, for cases where the code base is inaccessible, such as the case with bindings. Stub files contain the signatures of the annotated functions with the body of the functions discarded. They also list the attributes of annotated types. In our case they contain the annotated interface of the {\sc Cgal}{} bindings. Stub files have the same syntax as regular Python modules. There is one feature of the typing module that is different in stub files, namely, the \pyLstinline{@overload} decorator. This decorator allows describing functions that have different combinations of argument types. Consider, for example, the overloaded free C++ functions \cppLstinline{overlay()}; see Section~\ref{sec:code:overlay}. The annotation for the corresponding Python function \pyLstinline{overlay()} in the stub file is shown in Listing~\ref{lst:py:overloading}. \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\normalsize,% label={lst:py:overloading},% caption={Type annotation of the overloaded overlay function.}] @overload def overlay(r:Arrangement_2, b:Arrangement_2, o:Arrangement_2) -> None: pass @overload def overlay(r:Arrangement_2, b:Arrangement_2, o:Arrangement_2, t:Arr_overlay_traits) -> None: pass @overload def overlay(r:Arrangement_2, b:Arrangement_2, o:Arrangement_2, t:Arr_overlay_function_traits) -> None: pass \end{lstlisting} \end{lstfloat} Annotating a Python type that wraps a C++ type, which is a model of some concepts is guided by the concepts. Similar to the C++ code that generates the bindings, we have introduced a tight coupling between concepts and Python type annotations; see Section~\ref{sec:code:concepts}. As opposed to the C++ binding code, we have introduced a framework for the automatic generation of the annotation stubs. The framework includes a Python script called \bashLstinline{generate.py} that accepts as input static data files in json format that describe the concepts, their refinement relations, the exposed C++ classes, and their modeling relations with concepts. The script generates annotation stubs for the bindings of modules selected by the user. As mentioned in Section~\ref{sec:gen}, {\sc CMake}{} is used to generate the native build environment. We have augmented the scope of {\sc CMake}, and now {\sc CMake}{} is also used to generate the annotation stubs. Before we delve into the details of our annotation stub generation system, we describe in the following two paragraphs an unsuccessful attempt, which resembles the C++ binding code. It reached a dead-end because of limitations of Python. Imagine that for each C++ concept we introduce a Python annotation class that annotates all the requirements of the concept. The annotated Python classes do not exist; these annotation classes are introduced to facilitate the creation of the annotation classes of real Python classes. Every annotation-class that annotates a certain model type, say \cppLstinline{T}, inherits from all the annotation-classes that correspond to the concepts that \cppLstinline{T} models. For example, the type annotation for the concept \cppLstinline{AosBasicTraits_2} contains the annotations the nested type \cppLstinline{Point_2}, which in turn, contains annotations for the default constructor and copy constructor of the type \cppLstinline{Point_2} defined by every model of the concept \cppLstinline{AosBasicTraits_2}; see Listing~\ref{lst:py:aosBasicTraitsErr} for partial annotations. Observe that the annotated Python class does not exist in reality, thus the \pyLstinline{_} prefix in the name of the annotation class \pyLstinline{_AosBasicTraits_2} in the listing. Assume that bindings are generated for the \cppLstinline{Arrangement_2<GeometryGtaits_2, Dcel>} type instantiated with a geometry traits type that is an instance of the \cppLstinline{Arr_segment_traits_2} class template. This type models several concepts; see, e.g., Figure~\ref{fig:atc:central}. Partial erroneous Python type annotation for the type \pyLstinline{Arr_segment_traits_2} is shown in Listing~\ref{lst:py:aosSegmentTraitsErr}. \begin{lstfloat} \begin{draft} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\scriptsize,% label={lst:py:aosBasicTraitsErr},% caption={Erroneous partial type annotation for the attributes that correspond to the concept \cppLstinline{AosBasicTraits_2}.}] class _AosBasicTraits_2(): class Point_2(): def __init__(): ... def __init__(const Point_2&): ... class Equal_2(): @overload def __call__(self, p: _AosBasicTraits_2.Point_2, q: _AosBasicTraits_2.Point_2) -> bool: ... @overload def __call__(self, p: _AosBasicTraits_2.X_monotone_curve_2, q: _AosBasicTraits_2.X_monotone_curve_2) -> bool: ... def equal_2_object(self) -> _AosBasicTraits_2.Equal_2: ... \end{lstlisting} \end{draft} \end{lstfloat} \begin{lstfloat} \begin{draft} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\scriptsize,% label={lst:py:aosSegmentTraitsErr},% caption={Erroneous partial Python type annotation for the type \pyLstinline{Arr_segment_traits_2}.}] class Arr_segment_traits_2(AosBasicTraits_2._AosBasicTraits_2, AosXMonotoneTraits_2._AosXMonotoneTraits_2, AosTraits_2._AosTraits_2, AosLandmarkTraits_2._AosLandmarkTraits_2, AosVerticalSideTraits_2._AosVerticalSideTraits_2, AosVerticalSideTraits_2._AosHorizontalSideTraits_2) : class Point_2(AosBasicTraits_2._AosBasicTraits_2.Point_2): def x(self) -> Ker.FT: ... def y(self) -> Ker.FT: ... \end{lstlisting} \end{draft} \end{lstfloat} Unfortunately, the code presented in Listing~\ref{lst:py:aosBasicTraitsErr} and Listing~\ref{lst:py:aosSegmentTraitsErr} does not work. Python and static type checkers for Python (e.g., mypy)\footnote{See, e.g., \url{https://mypy.readthedocs.io/en/stable/}.} have made significant progress since Python was conceived. However, even with the introduction of the \pyLstinline{Typing} module, and in particular the \pyLstinline{Generic} class within,\footnote{See \url{https://docs.python.org/3/library/typing.html\#module-typing}.} there are still barriers that cannot be bridged. The barrier that we encountered is related to deep nesting. The culprit lies in Line~7 and Line~9 of Listing~\ref{lst:py:aosBasicTraitsErr}. In Line~7, for example, the class \pyLstinline{Point_2} nested in the utility class \pyLstinline{_AosBasicTraits_2} is refered to from a method of the class \pyLstinline{Equal_2}, which is nested in \pyLstinline{_AosBasicTraits_2}. An object of type \pyLstinline{Arr_segment_traits_2.Equal_2} was not recognized (probably because \pyLstinline{Arr_segment_traits_2.Equal_2} is not substituted by \pyLstinline{_AosBasicTraits_2.Equal_2} even though \pyLstinline{Arr_segment_traits_2} is derived from \pyLstinline{_AosBasicTraits_2}.) and our ambitious attempt failed flat. Assume that two users select the \cgalPackage{2D Arrangements}{} module for binding generation. In particular, one user chooses to generate bindings for the \cppLstinline{Arrangement_2<GeometryGtaits_2, Dcel>} type instantiated, where the template parameter \cppLstinline{GeometryGtaits_2} is substituted with an instance of the \cppLstinline{Arr_segment_traits_2} class template and the other user chooses to generate bindings for the \cppLstinline{Arrangement_2<GeometryGtaits_2, Dcel>} type, where \cppLstinline{GeometryGtaits_2} is substituted with an instance of the \cppLstinline{Arr_Bezier_curve_traits_2} class template; see Listing~\ref{lst:py:aosSegmentTraits} and Listing~\ref{lst:py:aosBezierTraits} for the corresponding partial valid Python type annotations generated by our system. The input data files describe the concepts and the classes. More specifically, for each concept $C$, there exists a record that lists the requirements of the concept $C$ and the concepts the $C$ refines. For each type $T$, there exists a record that lists the concepts that $T$ models and the additional members and types nested in $T$ that are not covered by the concepts. Type annotations are, naturally, generated only for the types. An important feature of the system is the ability to merge methods of a class that appears both as a nested type of another class and as a type required by a concept. An example of such a scenario is the \cppLstinline{Point_2} type required by the concept \cppLstinline{Aosbasictraits_2} and nested in every geometry traits class, e.g., \cppLstinline{Arr_segment_traits_2} and \cppLstinline{Arr_Bezier_curve_2}. \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\scriptsize,% label={lst:py:aosSegmentTraits},% caption={Valid Python type annotation for the type \pyLstinline{Arr_segment_traits_2}.}] from typing import Iterator, overload class Arr_segment_traits_2(): class Point_2(): @overload def __init__(self) -> None: ... @overload def __init__(self, p: Point_2) -> None: ... @overload def __init__(self, x: float, y: float) -> None: ... def x(self) -> FT: ... def y(self) -> FT: ... class Equal_2(): def __call__(self, p: Point_2, Q: Point_2) -> Boolean: ... def equal_2_object(self) -> Equal_2: ... \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=pythonFramedStyle,basicstyle=\scriptsize,% label={lst:py:aosBezierTraits},% caption={Valid Python type annotation for the type \pyLstinline{Arr_segment_traits_2}.}] from typing import Iterator, overload class Arr_Bezier_curve_traits_2(): class Point_2(): @overload def __init__(self) -> None: ... @overload def __init__(self, p: Point_2) -> None: ... def approximate(self) -> list[float]: ... class Equal_2(): def __call__(self, p: Point_2, Q: Point_2) -> Boolean: ... def equal_2_object(self) -> Equal_2: ... \end{lstlisting} \end{lstfloat} While using a code-generation approach adds a level of complexity to our binding system, it achieves the goal, it is flexible, and it posses an additional advantage. Once the input data files for specific concepts and models are in place, they can be used to automatically generate the documentation for those models and concept; we certainly plan to pursue this goal in the future. The use of the type-annotation subsystem, and in particular the \bashLstinline{generate.py} script or the script that generates the documentation that we intend to develop are not limited to {\sc Cgal}{}---they can be used by any binding generation system that generates Python bindings for generic C++ code. \section{Extenders} \label{sec:extenders} In several places in our binding code we are given a type that models certain concepts and based on several conditions, this type must be replaced with a new type that models additional concepts. Instead of using old style code in the form of \cppLstinline{#if,#elif,#else,#endif} directives, we exploit generic programming and implement these extenders using modern code that is type safe. In the following we present four such scenarios. \subsection{2D Arrangement Traits Extender} \label{sec:extenders:arrTraits} When the user enables the generation of bindings for the \cgalPackage{2D Arrangements}{} package, the binding for an instance of the class template \cppLstinline{Arrangement_2<Traits, Dcel>} is generated. When this class template is instantiated the \cppLstinline{Traits} template parameter must be substituted with a specific traits model. By default an instance of the \cppLstinline{Arr_segment_traits_2<Kernel>} is used; however, the user can override this selection and choose any one of the supported geometry traits. We refer to this traits as the basic geometry traits. If the user also enables the generation of bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package, the basic traits must be extended, because it must also model the \cppLstinline{GeneralPolygonSetTraits_2} concept (see Figure~\ref{fig:atc:gps}); see Section~\ref{ssec:modules:aos2}. The extension however differs for different basic traits. It is automatically done via a dedicated class template and four specializations shown in Listing~\ref{lst:arrTraitsExtender}. The final traits is obtained using this extender as shown in Listing~\ref{lst:arrFinalTraits}. Here, \cppLstinline{boolean_set_operations_2_bindings()} is a constant binary function (evaluated at compile time) that determines whether the generation of bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package is enabled, and \cppLstinline{BGT} is the basic geometry traits. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrTraitsExtender},% caption={2D Arrangement Traits Extender.}] // Traits extender template <bool b, typename Base> struct Tr {}; // Specialization for the case where bindings for Bso2 are not generated template <typename Base> struct Tr<false, Base> { typedef Base type; }; // Specialization for the general case where bindings for Bso2 are generated template <typename Base> struct Tr<true, Base> { typedef CGAL::Gps_traits_2<Base> type; }; // Specialization for the segment traits template <> struct Tr<true, CGAL::Arr_segment_traits_2<Kernel>> { typedef CGAL::Gps_segment_traits_2<Kernel, Point_2_container> type; }; // Specialization for the circle segment traits template <> struct Tr<true, CGAL::Arr_circle_segment_traits_2<Kernel>> { typedef CGAL::Gps_circle_segment_traits_2<Kernel> type; }; \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrFinalTraits},% caption={The final 2D Arrangement traits type definition.}] typedef Tr<boolean_set_operations_2_bindings(), BGT>::type Geometry_traits; \end{lstlisting} \end{lstfloat} \subsection{2D Arrangement DCEL Cell Extenders} \label{sec:extenders:arrDcel} When the user enables the generation of bindings for the \cgalPackage{2D Arrangements}{} package, the binding for an instance of the class template \cppLstinline{Arrangement_2<Traits, Dcel>} is generated. When this class template is instantiated the \cppLstinline{Dcel} template-parameter should be substituted with a type that models the \cppLstinline{ArrangementDcel} concept. We substitute this parameter with an instance of the template \cppLstinline{CGAL::Arr_dcel_base<V, H, F>}, where \cppLstinline{V}, \cppLstinline{H}, and \cppLstinline{F} must model the concepts \cppLstinline{ArrangementDcelVertex}, \cppLstinline{ArrangementDcelHalfedge}, and \cppLstinline{ArrangementDcelFace}, respectively. By default, we substitute these parameters with the instances \cppLstinline{Arr_vertex_base<Traits::Point_2>}, \cppLstinline{Arr_halfedge_base<Traits::X_monotone_curve_2>}, and \cppLstinline{Arr_face_base}, respectively, referred to as the basic types of cells. If the user chooses to extend the vertex type, then we substitute \cppLstinline{V} with the instance \cppLstinline{Arr_extended_ vertex<Vb, bp::object>}, where \cppLstinline{Vb} is the basic vertex type above. This conditional extension is carried out via a dedicated class template and two specializations shown in Listing~\ref{lst:arrDcelVertexExtender}. The final vertex type is obtained using this extender as shown in Listing~\ref{lst:arrFinalVertex}. Here, \cppLstinline{is_vertex_extended()} is a constant binary function that determines whether the user extension of vertices is enabled. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrDcelVertexExtender},% caption={2D Arrangement DCEL user extended vertex type extender.}] // Vertex extender template <bool b, typename Vb> struct Vertex_extender {}; // Specialization template <typename Vb> struct Vertex_extender<false, Vb> { typedef Vb type; }; // Specialization template <typename Vb> struct Vertex_extender<true> { typedef CGAL::Arr_extended_vertex<Vb, bp::object> type; }; \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrFinalVertex},% caption={The final 2D Arrangement vertex type definition.}] CGAL::Arr_vertex_base<Geometry_traits::Point_2> Vb; typedef Vertex_extended<is_vertex_extended(), Vb, bp::object>::type V; \end{lstlisting} \end{lstfloat} If the user also enables the generation of bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package, the template parameters \cppLstinline{H} and \cppLstinline{F} must be substituted with types that also model the \cppLstinline{GeneralPolygonSetDcelHalfedge} and \cppLstinline{GeneralPolygonSetDcelFace} concepts, respectively; see Section~\ref{ssec:modules:bso2}. In addition, similar to the case of vertex extension, if the user chooses to extend the halfedge or face types, then we substitute \cppLstinline{V} with the instances \cppLstinline{Arr_extended_halfedge<Hb, bp::object>} or \cppLstinline{Arr_extended_ face<Fb, bp::object>}, respectively, where \cppLstinline{Hb} and \cppLstinline{Fb} are the types above. The conditional extensions of the halfedge type are carried out via dedicated class templates and corresponding specializations shown in Listing~\ref{lst:arrDcelBasicHalfedgeExtender} and Listing~\ref{lst:arrDcelHalfedgeExtender}. The final halfedge type is obtained using these extenders as shown in Listing~\ref{lst:arrFinalHalfedge}. Here, \cppLstinline{boolean_set_operations_2_bindings()} is a constant binary function that determines whether the generation of bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package is enabled, and \cppLstinline{is_halfedge_extended()} is a constant binary function that determines whether the user extension of halfedges is enabled. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrDcelBasicHalfedgeExtender},% caption={2D Arrangement DCEL Halfedge extender for 2D Regularized Boolean set operations.}] // Basic halfedge extender template <bool b> struct Halfedge_gps {}; // Specialization template <> struct Halfedge_gps<false> { typedef CGAL::Arr_halfedge_base<Geometry_traits::X_monotone_curve_2> type; }; // Specialization template <> struct Halfedge_gps<true> { typedef CGAL::Gps_halfedge_base<Geometry_traits::X_monotone_curve_2> type; }; \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrDcelHalfedgeExtender},% caption={2D Arrangement DCEL user extended halfedge type extender.}] // Halfedge extender template <bool b, typename Hb> struct Halfedge_extender {}; // Specialization template <typename Hb> struct Halfedge_extender<false, Hb> { typedef Hb type; }; // Specialization template <typename Hb> struct Halfedge_extender<true, Hb> { typedef CGAL::Arr_extended_halfedge<Hb, bp::object> type; }; \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrFinalHalfedge},% caption={The final 2D Arrangement DCEL halfedge type definition.}] typedef Halfedge_gps<boolean_set_operations_2_bindings()>::type Hb; typedef Halfedge_extended<is_halfedge_extended(), Hb, bp::object>::type H; \end{lstlisting} \end{lstfloat} Similarly, the conditional extensions of the face type are carried out via dedicated class templates and corresponding specializations shown in Listing~\ref{lst:arrDcelBasicFaceExtender} and Listing~\ref{lst:arrDcelFaceExtender}. The final face type is obtained using these extenders as shown in Listing~\ref{lst:arrFinalFace}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrDcelBasicFaceExtender},% caption={2D Arrangement DCEL Face extender for 2D Regularized Boolean set operations.}] // Basic face extender template <bool b> struct Face_gps {}; // Specialization template <> struct Face_gps<false> { typedef CGAL::Arr_face_base type; }; // Specialization template <> struct Face_gps<true> { typedef CGAL::Gps_face_base type; }; \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrDcelFaceExtender},% caption={2D Arrangement DCEL user extended face type extender.}] // Face extender template <bool b, typename Fb> struct Face_extender {}; // Specialization template <typename Fb> struct Face_extender<false, Fb> { typedef Fb type; }; // Specialization template <typename Fb> struct Face_extender<true, Fb> { typedef CGAL::Arr_extended_face<Fb, bp::object> type; }; \end{lstlisting} \end{lstfloat} \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:arrFinalFace},% caption={The final 2D Arrangement DCEL face type definition.}] typedef Face_gps<boolean_set_operations_2_bindings()>::type Fb; typedef Face_extended<is_face_extended(), Fb, bp::object>::type F; \end{lstlisting} \end{lstfloat} \subsection{2D Triangulation Cell Extenders} \label{sec:extenders:iitri} When the user enables the generation of bindings for the \cgalPackage{2D Triangulations}{} package, the binding for an instance of one of the 2D triangulation class templates is generated. Each of these class templates has a template parameter that must be substituted with a model of the concept \cppLstinline{TriangulationDataStructure_2} when the triangulation class template is instantiated. We substitute this parameter with an instance of the class template \cppLstinline{Triangulation_data_structure_2<V, F>}. The type that substitutes the \cppLstinline{V} template parameter when the class template \cppLstinline{Triangulation_data_structure_ 2<V, F>} is instantiated must model the \cppLstinline{TriangulationDSVertexBase_2} concepts. If the binding is generated for a periodic triangulation, this parameter must be substituted with a type that also models the concept \cppLstinline{Periodic_2TriangulationDSVertexBase_2}. The extension is automatically done via a dedicated class template and three specializations shown in Listing~\ref{lst:iitriBaseVertexExtender}. Here \cppLstinline{Traits} is the geometry traits type; see Section~\ref{ssec:modules:tri2} for an explanation on how this type is determined. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:iitriBaseVertexExtender},% caption={The 2D Triangulation base vertex type extender.}] // Vertex base selection template <bool b, int i> struct Vertex_base_name {}; // Specialization template <int i> struct Vertex_base_name<false, i> { typedef CGAL::Triangulation_vertex_base_2<Traits> type; }; // Specialization template <> struct Vertex_base_name<false, CGALPY_TRI2_REGULAR> { typedef CGAL::Regular_triangulation_vertex_base_2<Traits> type; }; // Specialization template <int i> struct Vertex_base_name<true, i> { typedef CGAL::Periodic_2_triangulation_vertex_base_2<Traits> type; }; \end{lstlisting} \end{lstfloat} If the user chooses to extend the vertex type, the type that substitutes the \cppLstinline{V} template parameter is further extended. This is automatically done via yet another dedicated class template and two specializations shown in Listing~\ref{lst:iitriExtendedVertexExtender}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:iitriExtendedVertexExtender},% caption={The 2D Triangulation user extended vertex type extender.}] // Vertex with info template <bool b, typename Vb> struct Vertex_with_info {}; // Specialization template <typename Vb> struct Vertex_with_info<false, Vb> { typedef Vb type; }; // Specialization template <typename Vb> struct Vertex_with_info<true, Vb> { typedef CGAL::Triangulation_vertex_base_with_info_2<bp::object, Traits, Vb> type; }; \end{lstlisting} \end{lstfloat} If the triangulation is used to define an alpha shape type, the template parameter \cppLstinline{V} must be substituted with a type that also models the concept \cppLstinline{AlphaShapeVertex_2}; see Section~\ref{ssec:modules:as2}. This is automatically done via yet another class template shown in Listing~\ref{lst:iitriASVertexExtender}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:iitriASVertexExtender},% caption={The 2D Triangulation for alpha shapes vertex type extender.}] // Vertex alpha shape template <bool b, typename Vb, typename ExactComparison> struct Vertex_alpha_shape {}; // Specialization template <typename Vb, typename ExactComparison> struct Vertex_alpha_shape<false, Vb, ExactComparison> { typedef Vb type; }; // Specialization template <typename Vb, typename ExactComparison> struct Vertex_alpha_shape<true, Vb, ExactComparison> { typedef CGAL::Alpha_shape_vertex_base_2<Traits, Vb, ExactComparison> type; }; \end{lstlisting} \end{lstfloat} Finally, if the binding is generated for a hierarchy triangulation, e.g., an instance of the template parameter \cppLstinline{Triangulation_hierarchy_2<Triangulation_2>}, the \cppLstinline{V} template parameter must be substituted with a type that also models the concept \cppLstinline{TriangulationHierarchyVertexBase_2}. (Observe that there is no special requirements on the type that substitutes the \cppLstinline{F} parameter in this case.) This is automatically done via yet another class template shown in Listing~\ref{lst:iitriHierarchyVertexExtender}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:iitriHierarchyVertexExtender},% caption={The 2D Triangulation hierarchy vertex type extender.}] // Vertex triangulation hierarchy template <bool b, typename Vb> struct Vertex_hierarchy {}; // Specialization template <typename Vb> struct Vertex_hierarchy<false, Vb> { typedef Vb type; }; // Specialization template <typename Vb> struct Vertex_hierarchy<true, Vb> { typedef CGAL::Triangulation_hierarchy_vertex_base_2<Vb> type; }; \end{lstlisting} \end{lstfloat} The type \cppLstinline{Vb} is defined as the vertex base type. If bindings are generated for a periodic triangulation, the type \cppLstinline{Vb} is defined as \cppLstinline{Periodic_2_triangulation_vertex_base_2<Traits>}; otherwise, if bindings are generated for an instance of \cppLstinline{Regular_triangulation_2<Traits, Tds>}, the type \cppLstinline{Vb} is defined as \cppLstinline{Regular_triangulation_ vertex_base_2<Traits>}; otherwise, the type \cppLstinline{Vb} is defined as \cppLstinline{Triangulation_vertex_ base_2<Traits>}; If the user enables vertex-type extension, the type \cppLstinline{Vbi} is defined as \cppLstinline{Triangulation_vertex_base_with_ info_2<bp::object, Kernel, Vb>}; otherwise the type \cppLstinline{Vbi} is defined as \cppLstinline{Vb}. If the triangulation is used to define an alpha shape type, the type \cppLstinline{Vbia} is defined as \cppLstinline{Alpha_shape_vertex_base_2<Traits, Vb, ExactComparison>}, where \cppLstinline{ExactComparison} is substituted with either \cppLstinline{true} or \cppLstinline{false} based on the setting of the {\sc CMake}{} flag \cmakeLstinline{CGALPY_AS2_EXACT_COMPARISON}; see Table~\ref{tab:as2}. Otherwise, \cppLstinline{V} is defined as \cppLstinline{Vbi}. If the binding is generated for a hierarchy triangulation, the final vertex type \cppLstinline{V} is defined as \cppLstinline{Triangulation_hierarchy_vertex_ base_2<Vbi>}; otherwise the final vertex type \cppLstinline{V} is defined as \cppLstinline{Vbia}; see Listing~\ref{lst:iitriFinalVertex}. Here, \cppLstinline{is_periodic()}, \cppLstinline{vertex_with_ info()}, \cppLstinline{alpha_shape_2_bingings()}, and \cppLstinline{hierarchy()} are constant binary functions. \cppLstinline{is_periodic()} that determines whether the triangulation, binding for which is generated, is periodic. \cppLstinline{vertex_with_info()} determines whether the user extension of vertices is enabled. \cppLstinline{alpha_shape_2_bingings()} indicates whether bindings for the \cgalPackage{2D Alpha Shapes}{} package. \cppLstinline{hierarchy()} indicates whether the binding is generated for a hierarchy triangulation. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:iitriFinalVertex},% caption={The final 2D Triangulation vertex type definition.}] typedef Vertex_base_name<is_periodic(), CGALPY_TRI2>::type Vb; typedef Vertex_with_info<vertex_with_info(), Vb>::type Vbi; typedef Vertex_alpha_shape<alpha_shape_2_bindings(), Vbi, Ec>::type Vbia; typedef Vertex_hierarchy<hierarchy(), Vbia>::type V; \end{lstlisting} \end{lstfloat} The final face type is determined in a similar fashion. The only difference between the selections of the vertex and face types is that the setting of the {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI2_HIERARCHY} does not have an effect on the face type selection. \subsection{3D Triangulation Cell Extenders} \label{sec:extenders:iiitri} When the user enables the generation of bindings for the \cgalPackage{3D Triangulations}{} package, the binding for an instance of one of the 3D triangulation class templates is generated; see Section~\ref{ssec:modules:tri3}. The scenario here is similar to the scenario of the \cgalPackage{2D Triangulations}{} package described in Section~\ref{sec:extenders:iitri}. We skip the description of the extenders and jump to the description of their application. If bindings are generated for a periodic triangulation, the type \cppLstinline{Vbp} is defined as \cppLstinline{Periodic_3_triangulation_ ds_vertex_base_3<>}; otherwise, \cppLstinline{Vbp} is defined as \cppLstinline{Triangulation_ds_vertex_base_3<>}. If bindings are generated for an instance of either \cppLstinline{Regular_triangulation_vertex_base_3<Kernel>} or \cppLstinline{Periodic_3_ Regular_triangulation_vertex_base_3<Kernel>}, the type \cppLstinline{Vb} is defined as \cppLstinline{Regular_triangulation_ vertex_base_3<Traits, Vbp>}; otherwise, the type \cppLstinline{Vb} is defined as \cppLstinline{Triangulation_vertex_base_3<Traits, Vbp>}. If the vertex type is extended, the type \cppLstinline{Vbi} is defined as \cppLstinline{Triangulation_vertex_base_ with_info_3<bp::object, Traits, Vb>}; otherwise, the type \cppLstinline{Vbi} is defined as \cppLstinline{Vb}. If the binding is generated for a hierarchy triangulation, the type \cppLstinline{Vbih} is defined as \cppLstinline{Triangulation_hierarchy_vertex_base_3<Vbi>}; otherwise the type \cppLstinline{Vbih} is defined as \cppLstinline{Vbi}. If the triangulation is used to define an alpha shape type, the final type \cppLstinline{V} (that substitutes the \cppLstinline{V} parameter) is defined as either \cppLstinline{Alpha_shape_vertex_base_3<Traits, Vbih, ExactComparison>} or \cppLstinline{Fixed_Alpha_shape_vertex_base_3<Traits, Vbih, ExactComparison>} based on the selection of the alpha shape class (either fixed or plain); see Table~\ref{tab:as3}; \cppLstinline{ExactComparison} is substituted with either \cppLstinline{true} or \cppLstinline{false} based on the user selection of exact comparisons; see Table~\ref{tab:as3}. Otherwise, \cppLstinline{V} is defined as \cppLstinline{Vbih}; see Listing~\ref{lst:iiitriFinalVertex}. (Observe that while 3D periodic regular triangulations are supported in the form of the class template \cppLstinline{Periodic_3_regular_triangulation_3}, corresponding 2D triangulations are not; thus the difference between the structures of the code in Listing~\ref{lst:iitriFinalVertex} and Listing~\ref{lst:iiitriFinalVertex}. \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize,% label={lst:iiitriFinalVertex},% caption={The final 3D Triangulation vertex type definition.}] typedef Vertex_periodic<is_periodic()>::type Vb; typedef Vertex_regular<is_regular(), Vb>::type Vbr; typedef Vertex_with_info<vertex_with_info(), Vbr>::type Vbri; typedef Vertex_alpha_shape<alpha_shape_3_bindings(), Vbri, Ec>::type Vbria; typedef Vertex_hierarchy<hierarchy(), Vbria>::type V; \end{lstlisting} \end{lstfloat} The final cell type is determined in a similar fashion. The only difference between the selections of the vertex and cell types is that the setting of the {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI3_HIERARCHY} does not have an effect on the cell type selection. \section{Binding Generation} \label{sec:gen} The most simple form of building an application written in C++ that depends on {\sc Cgal}{} consists of the stages below. Let \myLstinline{\$APP\_SRC\_DIR} point at the root directory of the application source tree. \begin{compactenum} \item Obtain the sources of {\sc Cgal}{}; let \myLstinline{\$CGAL\_SRC\_DIR} point at the root directory of the {\sc Cgal}{} source tree. % \item Create a build directory for {\sc Cgal}{}; let \myLstinline{\$CGAL\_DIR} point at this build directory. % \item Change directory to \myLstinline{\$CGAL_DIR} and run '\myLstinline{cmake [options] \$CGAL\_SRC\_DIR}'. % \item Create a build directory for the application; let \myLstinline{\$APP\_DIR} point at this build directory. % \item Change directory to \myLstinline{\$APP\_DIR} and run '\myLstinline{cmake [options] \$APP\_SRC\_DIR}' followed by \myLstinline{make}. \end{compactenum} \noindent In the procedure above \myLstinline{options} refer to optional arguments passed to \myLstinline{cmake}, which govern the generation of the native build environment. When running an application written in Python that depends on {\sc Cgal}{} instead of building the application, the user must build the bindings. Here, \myLstinline{\$APP\_SRC\_DIR} needs to point at the root directory of the binding source tree, and \myLstinline{\$APP\_DIR} needs to point at the build directory for the bindings. The optional arguments passed to \myLstinline{cmake} in stage~5 mainly consist of variables that determine (i) the object types to be bound and the unique identifier of each such object, and (ii) the name of the libraries that comprise the bindings, in case the default library name is overridden. \subsection{Bindings Components} \label{sec:gen:components} Our binding code is divided into modules, which correspond to {\sc Cgal}{} packages. Each module has a long (and meaningful) name and a short name; see Table~\ref{tab:moduleName} for the list of relevant modules. Each module is associated with a {\sc CMake}{} Boolean flag that determines whether to generate bindings for that particular module. Each module may be associated with zero or more additional flags that specify selections for bindings of entities of the corresponding {\sc Cgal}{} packages. For example, the long name of the \cgalPackage{2D Arrangements}{} module is \myLstinline{ARRANGEMENT\_ON\_SURFACE\_2}; its short name is \myLstinline{AOS2}; \myLstinline{CGALPY\_ARRANGEMENT\_ON\_SURFACE\_2\_BINDINGS} is the {\sc CMake}{} Boolean flag that indicates whether to generate bindings for this module. This module is associated with the Boolean flag \myLstinline{CGALPY\_AOS2\_POINT\_ LOCATION\_BINDINGS}, which indicates whether to generate bindings for point location queries supported by the \cgalPackage{2D Arrangements}{} package. This module is also associated with the string flags \myLstinline{CGALPY\_AOS2\_GEOMETRY\_TRAITS\_ NAME} and \myLstinline{CGALPY\_AOS2\_DCEL\_NAME}, which specify the name of the geometry traits and Dcel, respectively, used to instantiate the \cppLstinline{Arrangement\_2<GeometryTraits_2, Dcel>} class template; see Section~\ref{ssec:modules:aos2} for more details on the \cgalPackage{2D Arrangements}{} module. \begin{table}[!htp] \caption{Module names and short names} \centering\begin{tikzpicture} \matrix (first) [tableModuleName] { Module & Name & Short Name\\ \cgalPackage{2D and 3D Geometry Kernel} & \myLstinline{KERNEL} & \myLstinline{KER}\\ \cgalPackage{dD Geometry Kernel} & \myLstinline{KERNEL\_D} & \myLstinline{KERD}\\ \cgalPackage{2D Arrangements} & \myLstinline{ARRANGEMENT\_ON\_SURFACE\_2} & \myLstinline{AOS2}\\ \cgalPackage{2D Alpha Shapes} & \myLstinline{ALPHA\_SHAPE\_2} & \myLstinline{AS2}\\ \cgalPackage{3D Alpha Shapes} & \myLstinline{ALPHA\_SHAPE\_3} & \myLstinline{AS3}\\ \cgalPackage{2D Regularized Boolean Set-Operations} & \myLstinline{BOOLEAN\_SET\_OPERATIONS\_2} & \myLstinline{BSO2}\\ Bounding Volumes & \myLstinline{BOUNDING\_VOLUMES} & \myLstinline{BV}\\ \cgalPackage{2D Convex Hulls and Extreme Points} & \myLstinline{CONVEX\_HULL\_2} & \myLstinline{CH2}\\ \cgalPackage{3D Convex Hulls} & \myLstinline{CONVEX\_HULL\_3} & \myLstinline{CH3}\\ \cgalPackage{2D Polygons} & \myLstinline{POLYGON\_2} & \myLstinline{POL2}\\ \cgalPackage{2D Polygon Partitioning} & \myLstinline{POLYGON\_PARTITIONING} & \myLstinline{PP}\\ \cgalPackage{2D Minkowski Sums} & \myLstinline{MINKOWSKI\_SUM\_2} & \myLstinline{MS2}\\ \cgalPackage{dD Spatial Searching} & \myLstinline{SPATIAL\_SEARCHING} & \myLstinline{SS}\\ \cgalPackage{2D Triangulations} & \myLstinline{TRIANGULATION\_2} & \myLstinline{TRI2}\\ \cgalPackage{3D Triangulations} & \myLstinline{TRIANGULATION\_3} & \myLstinline{TRI3}\\ }; \end{tikzpicture} \label{tab:moduleName} \end{table} The exposed names of the bound entities of different modules are gathered in distinct Python namespaces to prevent name conflicts. The namespace is the short name of the module in lower-case except for the first letter (which is in upper-case); for example, the namespaces of the bound types and free functions of the \cgalPackage{2D and 3D Geometry Kernel}{} and the \cgalPackage{2D Regularized Boolean Set-Operations}{} packages are \pyLstinline{Ker} and \pyLstinline{Bso2}, respectively. Each of these two namespaces has the attribute \myLstinline{intersection} (i.e., \myLstinline{Ker.intersection()} and \myLstinline{Bso2.intersection()}). We introduce as many (Python) namespaces as modules, and nest every exposed name of a bound entity in the appropriate (Python) namespace according to the module of the entity. We provide implementation details in the next section. \subsection{Bindings Scopes} \label{sec:gen:scopes} The above is conveniently achieved with the use of the \cppLstinline{bp::scope} class of Boost.Python. Constructing an object of this class, essentially, changes the Python namespace in which new extension classes and wrapped functions are defined as attributes. An object of the \cppLstinline{bp::scope} class is associated with a global Python object, which is bound to a Python namespace. The global Python object associated with default-constructed scopes is bound to the global Python namespace, and the global Python object associated with a scope constructed with an argument is bound to the Python namespace held by the argument. When a scope object is constructed its associated global Python object is pushed onto a stack. When the lifetime of the scope ends, the associated global Python object is popped from the stack. This mechanism conveniently reflects nesting of constructs in C++ in Python code. For example, consider the following constructs in C++:\footnote{This example is a simplified version of the example shown at \url{https://www.boost.org/doc/libs/1_76_0/libs/python/doc/html/reference/high_level_components/boost_python_scope_hpp.html}.} \begin{lstlisting}[style=cppNumberedStyle] struct X { struct Y { int g() { return 42; } }; }; \end{lstlisting} \noindent Using the following binding code: \begin{lstlisting}[style=cppNumberedStyle] BOOST_PYTHON_MODULE(nested) { scope outer = class_<X>("X"); class_<X::Y>("Y").def("g", &X::Y::g); } \end{lstlisting} \noindent enables the following in Python: \begin{lstlisting}[style=pythonStyle] >>> y = nested.X.Y() >>> y.g() 42 \end{lstlisting} \noindent We use this mechanism to reflect nesting in C++ code that uses {\sc Cgal}. For example, assume that the binding module is called \myLstinline{CGALPY} and it includes bindings for an instance of the class template \cppLstinline{Arrangement\_2<GeometryTraits, Dcel>}, where the \cppLstinline{GeometryTraits} template parameter is substituted with a traits class that handles segments, and the \cppLstinline{Dcel} template parameter is substituted with the default Dcel; see Section~\ref{ssec:modules:aos2}. The following code excerpt constructs the segment $(0,0),(1,0)$. \begin{lstlisting}[style=pythonStyle] >>> import CGALPY >>> Aos2 = CGALPY.Aos2 # define the module namespace >>> Arr = Aos2.Arrangement_2 # define the arrangement type in the module namespace >>> Point = Arr.Point_2 # define the point type in the arrangement class >>> Segment = Arr.Curve_2 # define the curve type in the arrangement class >>> seg = Segment(Point(0, 0), Point(1, 0)) \end{lstlisting} The Boost.Python mechanism that depends on \cppLstinline{bp::scope} is used to (i) reflect nesting in C++ code that uses {\sc Cgal}, and (ii) prevent name conflicts between bound entities in distinct modules; see Section~\ref{sec:gen:scopes}. The latter requires a slight intervention on our part as explained next. The code that binds all functions and classes of different modules is nested in distinct C++ forced scopes. Within a (C++) scope we first set the Python namespace to match the name of a module. Then, we bind all functions and classes of {\sc Cgal}{} packages associated with the module. The following code except shows how it is done for the \cgalPackage{2D and 3D Geometry Kernel}{} module: \begin{lstlisting}[style=cppNumberedStyle] { SET_SCOPE("Ker") export_kernel(); #ifdef CGALPY_KERNEL_INTERSECTION_BINDINGS export_kernel_intersections_2(); export_kernel_intersections_3(); #endif } \end{lstlisting} For every module there exists a function called \cppLstinline{export_<name>}, where \cppLstinline{<name>} is the name of the module. This function contains the binding code for the essential functions and classes of the module. The \cgalPackage{2D and 3D Geometry Kernel}{} module is associated with the {\sc CMake}{} \myLstinline{CGALPY_KERNEL\_INTERSECTION\_BINDINGS} flag (see Table~\ref{tab:ker}), which determines whether to generate bindings for intersections; hence, the compile-time conditional calls to the functions \cppLstinline{export_kernel_intersections_2()} and \cppLstinline{export_kernel_intersections_3()}, which contain the binding code for intersections. For more information on kernel bindings see Section~\ref{ssec:modules:kernel}; for more information of software techniques used to generate bindings for intersections in 2D or 3D see Section~\ref{sec:code:intersectionDetection}. \subsection{Binding Library Name} \label{sec:gen:libraryName} By default, the base name of the generated library is \myLstinline{CGALPY}. However, the user can override the name with a generated string that maps to the set of bound types. This is imperative when more then one instance of the same template must be bound. Each execution of \myLstinline{cmake} followed by make generates a single library. The {\sc CMake}{} flag \myLstinline{CGALPY\_FIXED\_LIBRARY\_NAME} determines whether the base name of the generated library is \myLstinline{CGALPY} or not. If not, it has the prefix \myLstinline{CGALPY_} followed by as many as substrings as modules, the bindings of which are enabled, separated by an underscore (\myLstinline{_}). Each such substring starts with the short name of the module in lower case followed by strings that map to the selections for bindings within the module. Each such string is a single word that starts with a capital letter. For example, the name \myLstinline{GALPY_kernelEpecInt_Aos2SegPlainPl} of a generated library, names a library that contains bindings for (i) the Exact-Predicate-Exact-Construction (EPEC) \cgalPackage{2D and 3D Geometry Kernel}{} module and intersections, and (ii) the \cgalPackage{2D Arrangements}{} module, where the \myLstinline{Arrangement\_2<>} class template is instantiated with a traits class that handles segments and the default DCEL (see Section~\ref{ssec:modules:aos2}), and point location queries. The generated library is dynamically linked---it must be so. However, the library itself can be compiled of either static or dynamic (dependent) libraries. If you intend to generate and use just a single library that contains the bindings, you have the freedom to choose between generating a library compiled of static libraries or dynamic libraries. However, if you intend to generate several libraries and use them all in a single Python module, it is recommended using binding libraries compiled of dynamic libraries. (Otherwise, different generated libraries might be compiled of conflicting static libraries.) The cmake flag \myLstinline{CGALPY\_USE\_SHARED\_LIBS} indicates whether the generated library is compiled of static or dynamic libraries; it is true by default. The content of the library and its name are governed by flags provided to \myLstinline{cmake}. All flags have the prefix \myLstinline{CGALPY_}. In Tables~\ref{tab:args}, \ref{tab:sel}, \ref{tab:ker}, \ref{tab:kerd}, \ref{tab:aos}, \ref{tab:tri2}, \ref{tab:as2}, \ref{tab:tri3}, \ref{tab:as3}, and \ref{tab:ss} this prefix is omitted. \begin{table}[!htp] \caption{General Arguments} \centering\tikzset{% tableGA/.style={table,nodes={minimum height=1.6em}, row 4/.style={nodes={minimum height=2.8em}}, column 1/.style={nodes={text width=11em}}, column 2/.style={nodes={text width=4.8em}}, column 3/.style={nodes={text width=3.8em}}, column 4/.style={nodes={text width=28em}}}} \centering\begin{tikzpicture} \matrix (first) [tableGA] { Name & Type & Default & Description\\ \myLstinline{USE\_SHARED\_LIBS} & \myLstinline{Boolean} & \myLstinline{true} & Determines whether to compile shared libraries\\ \myLstinline{BUILD\_SHARED\_LIBS} & \myLstinline{Boolean} & \myLstinline{true} & Determines whether to generate shared libraries\\ \myLstinline{FIXED\_LIBRARY\_NAME} & \myLstinline{Boolean} & \myLstinline{true} & Determines whether the library name is fixed \myLstinline{cgalpy.so} or set based on other selections\\ }; \end{tikzpicture} \label{tab:args} \end{table} \begin{table}[!htp] \caption{Binding Selection} \centering\begin{tikzpicture} \matrix (first) [tableBindingSelection] { Name & Type & Default & Description\\ \cmakeLstinline{KERNEL\_BINDINGS} & Boolean & \myLstinline{true} & Determines whether to generate bindings for 2D and 3D Kernel types\\ \cmakeLstinline{KERNEL\_D\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for dD Kernel types\\ \cmakeLstinline{ARRANGEMENT\_ON\_SURFACE\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D arrangement instances\\ \cmakeLstinline{ALPHA\_SHAPE\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D Alpha shape instances\\ \cmakeLstinline{ALPHA\_SHAPE\_3\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 3D Alpha shape instances\\ \cmakeLstinline{BOOLEAN\_SET\_OPERATIONS\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D Boolean set operation instances\\ \cmakeLstinline{BOUNDING\_VOLUMES\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for bounding volume instances\\ \cmakeLstinline{CONVEX\_HULL\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D convex hull instances\\ \cmakeLstinline{CONVEX\_HULL\_3\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 3D convex hull instances\\ \cmakeLstinline{POLYGON\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D polygon instances\\ \cmakeLstinline{POLYGON\_PARTITIONING\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D polygon partitioning instances\\ \cmakeLstinline{MINKOWSKI\_SUM\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D Minkowski sum instances\\ \cmakeLstinline{SPATIAL\_SEARCHING\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for spatial searching instances\\ \cmakeLstinline{TRIANGULATION\_2\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 2D triangulation instances\\ \cmakeLstinline{TRIANGULATION\_3\_BINDINGS} & Boolean & \myLstinline{false} & Determines whether to generate bindings for 3D triangulation instances\\ }; \end{tikzpicture} \label{tab:sel} \end{table} \section{Introduction} \label{sec:intro} {\sc Cgal}{} (Computational Geometry Algorithm Library) is an open source software project that provides access to efficient and reliable implementations of geometric algorithms in the form of a C++ library~\cite{cgal:eb-21a}. {\sc Cgal}{} has evolved through the years and now represents the state of the art in computational geometry software. {\sc Cgal}{} is used in a diverse range of domains requiring geometric computation such as computer graphics, scientific visualization, computer aided design and modeling, geographic information systems, molecular biology, medical imaging, and many more. {\sc Cgal}{} provides a large number of components that cover a wide range of areas. The bindings for most components are supported now. The principles for the bindings described in this paper applies to all packages of {\sc Cgal}{} (and perhaps to other generic C++ libraries as well), and can be easily adopted to support the bindings of the few components that are still missing. There is a large community of users of {\sc Cgal}{} packages in academia and industry, and these packages seem to be helpful in many diverse projects. In all the projects that we are aware of, the packages have been used by C++ experts or by users who have been strongly supported by such experts from the {\sc Cgal}{} developer community, including GeometryFactory.\footnote{GeometryFactory is the company established to market and support the usage of {\sc Cgal}{} packages.} In our experience, incorporating {\sc Cgal}{} in education or in academic projects lacking C++ experts has been rugged. We attribute the difficulties that arise in such settings to the highly sophisticated usage of C++ in {\sc Cgal}. The binding project that we describe in this paper is meant to resolve these difficulties and make all {\sc Cgal}{} packages more accessible to a wider audience of programmers. We already see, and report below on, first signs that the project is on a good trajectory toward achieving this goal. The software modules of {\sc Cgal}{} rigorously adhere to the generic programming paradigm---a discipline that consists of the gradual lifting of concrete algorithms abstracting over details, while retaining the algorithm semantics and efficiency. The software modules of {\sc Cgal}{} also follow the exact geometric-computation paradigm, which simply amounts to ensuring that errors in predicate evaluations do not occur; it guarantees robustness of the applied algorithms. As a result, the software of {\sc Cgal}{} is robust despite the use of (inexact) floating point arithmetic, found in standard hardware, it is complete as it handles all degenerate cases, which typically are in abundance, and it is efficient---all at the same time. Generic programming identifies an abstraction that consists of a formal hierarchy of polymorphic abstract requirements on data types, referred to as \emph{concepts}, and a set of classes that conform precisely to the specified requirements, referred to as \emph{models}~\cite{a-gps-99}. A hierarchy of related concepts can be viewed as a directed acyclic graph, where a node of the graph represents a concept and an arc represents a refinement relation. An arc directed from concept A to concept B indicates that concept B refines concept A. When a class template is instantiated, each one of its template parameters is substituted with a model of one or more concepts associated with the template parameter. \subsection{C++ Python Bindings} \label{ssec:intro:bind} Python, like many other languages, was originally defined by a reference implementation. The original reference implementation of the Python programming language is CPython. To date, CPython is still the default and commonly used reference implementation of the language, although new rivals are emerging, see, e.g., PyPy.\footnote{PyPy is a replacement for CPython; see \url{https://www.pypy.org}.} As the Python language evolved, its definition has tightened and a well defined specification has materialized. Bindings are essentially wrapper libraries that bridge two programming languages, so that a software module developed in one language can be used in code written in another language, exploiting (i) the strengths of both languages, and (ii) the availability of modules developed in the former language. C++ Python bindings enable (i) the invocation of C++ functions, and (ii)~the access to C++ variables from Python code, taking advantage of Python's quick development cycles and C++'s high performance. Python is sufficiently efficient for many tasks; nevertheless low-level code written in Python tends to be too slow, largely due to Python's extremely dynamic nature. In particular, low-level computational loops are simply infeasible. In addition, the magnitude of existing and well-tested code in Fortran, C, or C++, is enormous. The Python/C API, the module that enables the usage of external modules developed in Fortran, C, or C++, from Python code, or embedding Python code in code written in other languages, is very rich. Indeed, the Python/C API module of CPython exposes a vast amount of details of CPython internals. It enables the efficient exploitation of existing code in Fortran, C, or C++, as well as the replacement of critical sections written in Python when speed is essential. Wrapping existing code has traditionally been the domain of Python experts due to the steep learning curve, which characterizes its Python/C API. Although using such wrappers is possible without ever knowing their internals, providing such wrappers creates a sharp line between developers using Python and developers using C or C++ with the Python/C API. Several tools that facilitate the creation of such wrappers have been introduced; A sample of such tools are listed In Section~\ref{sec:comp}. When running Python code that uses bindings for some C++ modules, one or more libraries that provide the bindings must be accessible. A software module in C++ that adheres to the generic programming paradigm consists of function and class templates; these templates are instantiated at compile time of the binding libraries. In other words, the types of the C++ objects that are bound, that is, instances (instantiated types) of C++ function and class templates, must be known when the bindings are generated. \subsection{{\sc CMake}} \label{ssec:intro:cmake} {\sc CMake}{}~\cite{mh-mc-08} is an open-source, cross-platform suite of tools designed to build, test, and package software. The suite of {\sc CMake}{} tools were created to address the need for cross-platform build environments for open-source projects. However, since it was conceived over two decades ago, it has grown and become powerful, rich, and flexible. It is now considered a modern tool; it is widely spread and used by major commercial software products for their build and test environments. {\sc CMake}{}, for the most part, is a cross-platform build system generator. It is used to control the software build process using simple platform and compiler independent configuration files, and it generates native build environments of the user choice. Users build a project by using {\sc CMake}{} to generate a build system for native tools on their platforms. {\sc CMake}{} supports an interpreted, functional, scripting language. The build process of a project is specified with platform-independent {\sc CMake}{} text files, named \myLstinline{CMakeLists.txt}, written in the {\sc CMake}{} language, included in each directory of the source tree of the project. For example, once the {\sc CMake}{} configuration files are in place for a certain project, {\sc CMake}{} can be used to generate \myLstinline{Makefile} files required by the \myLstinline{make} utility of the GNU suite to compile a project on a Unix system using \myLstinline{g++}. The command-line interface of the cross-platform build system generator of {\sc CMake}{} is an executable called \myLstinline{cmake}. It has a counterpart called \myLstinline{cmake-gui}, which includes a graphical user interface (GUI). To generate native project build files, the user invokes \myLstinline{cmake} in a terminal and specifies the directory that contains the root \myLstinline{CMakeLists.txt} file. A key feature of {\sc CMake}{} is the ability to (optionally) place compiler outputs (such as object files) outside the source tree. This enables multiple and concurrent builds from the same source tree and cross-compilation. It also keeps the source tree clean and ensures that removing a build directory will not remove the source files. We exploit this feature, and the scripting capabilities to conveniently generate the C++ Python bindings for several {\sc Cgal}{} objects concurrently. \subsection{Bindings for {\sc Cgal}} \label{ssec:intro:cgal} Instantiated types in {\sc Cgal}{} are characterized by long instantiation chains of C++ class templates. An instantiated type is a template that has one or more template parameters and every parameter is substituted by another type that is typically an instance of another template. While the number of models of most concepts is small, the number of potential types of objects that could be bound, and thus must be supported by the bindings, is enormous. Offering bindings for all these types in advance is practically impossible. Moreover, in some cases models need to be extended with types provided by the user. Naturally, bindings for user-extended models must be generated dynamically. {\sc Cgal}{} uses {\sc CMake}~\cite{mh-mc-08} for the build process. Since version~5.0, {\sc Cgal}{} is header-only by default, which means that an application that depends on {\sc Cgal}{} only depends on (i) the source code of {\sc Cgal}{} that resides in header files, (the names of which typically end with the suffix \myLstinline{.hpp}), and (ii) native configuration files generated by {\sc CMake}{} (in particular, the execution of \myLstinline{cmake}). In other words, there is no need to compile any library before an application that depends on {\sc Cgal}{} and written in C++ is built.\footnote{Some dependencies of {\sc Cgal}{} might need to be installed in advance.} On the other hand, when running an application written in Python that depends on {\sc Cgal}{} the libraries that contain the bindings must be accessible. Typically, those bindings are generated ahead of time with little knowledge about the application itself. This would impose a severe limitation in cases like ours, where the number of objects to be bound is large. In cases where the types of the objects to be bound are closely tied with the application itself, generating bindings ahead of time is, naturally, impossible. Our system enables easy and convenient (re)generation of bindings, thus alleviating the burden caused by these problems. \subsection{Contribution} \label{ssec:intro:results} We introduce C++ Python bindings that enable the convenient, efficient, and reliable use of {\sc Cgal}{} software modules in Python code. There are different tools that facilitate the creation of C++ Python bindings. We present a short study that compares several tools, which leads to the method of choice. The binding themselves are implemented in C++ and their implementation exploits advanced features in C++, which we explicate. This results with elegant and compact code that is easy to maintain and extend with additional bindings. We present a system that rapidly generates bindings of desired objects according to user prescriptions, which enables the convenient use of any subset of bound object types concurrently. With our system it is possible to generate a single library that contains bindings for instances of different {\sc Cgal}{} templates, e.g., an instance of the 2D arrangement class template and an instance of the 2D triangulation class template, or several libraries when one is insufficient. If several instances of the same class template must be bound, several corresponding libraries must be generated, one for each instance. \subsection{Outline} \label{ssec:intro:outline} The rest of this paper is organized as follows. A study that compares several methods for implementing C++ Python bindings is presented in Section~\ref{sec:comp}. General instructions for rapidly generating bindings with our system are presented in Section~\ref{sec:gen}. The description of the bindings generated by our system for various modules are given in Section~\ref{sec:modules}. A sample of highlighted modern C++ techniques and idioms used in the binding implementation are described in Section~\ref{sec:code}. The tight coupling between concepts and binding generation is described in Section~\ref{sec:concepts}. Applications of the new tools, which are geared toward making the CGAL code more accessible are presented in Section~\ref{sec:app}. \subsection{Conventions} \label{ssec:intro:conventions} The paper is packed with code samples written either in the {\sc CMake}{}, Python, or C++ languages. We use several conventions to improve readability. Code excerpt written in C++ is always numbered, while short code excerpts written in Python is sometimes preceded with \pyLstinline{>>>}. The C++ identifier \cppLstinline{bp} is an alias for the namespace \cppLstinline{boost::python}. \section{Binding Modules} \label{sec:modules} We describe the bindings generated by our system for various {\sc Cgal}{} packages and exemplify the use of the generated bindings. When developing code in Python that uses the bindings, the statement that imports the binding library, that is, \begin{lstlisting}[style=pythonStyle] >>> import CGALPY \end{lstlisting} (assuming the default binding library name is retained) must precede any statement that use the binding. This statement is omitted in all examples hereafter. \subsection{Two- and Three-Dimensional Kernel Bindings} \label{ssec:modules:kernel} The \cgalPackage{2D and 3D Geometry Kernel}{} package~\cite{cgal:bfghhkps-lgk23-21a} of {\sc Cgal}{} consists of constant-size non-modifiable geometric primitive objects and operations on these objects. The objects are sets of points in $d$-dimensional affine Euclidean space, where $d = 2,3$. Each point is uniquely represented either by Cartesian coordinates or by homogeneous coordinates. An object type can be defined either precatively as a member of a kernel type or imperatively as a global class-template parameterized by a kernel type, defined in the C++ \cppLstinline{CGAL} namespace. For example, assume that \cppLstinline{Kernel} is a kernel type; the type that represents a two-dimensional point of this kernel is either \cppLstinline{Kernel::Point_2} or \cppLstinline{CGAL::Point_2<Kernel>}. The generated bindings better reflects the latter types; that is, defining a two-dimensional point in Python amounts to the code below.\footnote{When writing code in C++ the precative style is advantageous, as it enables the extension of kernel object types, which is irrelevant when generating bindings.} \begin{lstlisting}[style=pythonStyle,basicstyle=\normalsize] >>> Ker = CGALPY.Ker # define the module namespace >>> Point_2 = Ker.Point_2 # define the point type in the module namespace >>> p = Point_2(0, 0); \end{lstlisting} Table~\ref{tab:ker} lists the {\sc CMake}{} flags associated with the \cgalPackage{2D and 3D Geometry Kernel}{} module. The kernel type is an instance of a chain of C++ class templates. For convenience, {\sc Cgal}{} provides the following predefined types of generally useful kernels: \begin{compactenum} \item \cppLstinline{Exact_predicates_inexact_constructions_kernel}---provides exact geometric predicates, but geometric constructions may be inexact due to round-off errors. % \item \cppLstinline{Exact_predicates_exact_constructions_kernel}---provides exact geometric constructions, in addition to exact geometric predicates. % \item \cppLstinline{Exact_predicates_exact_constructions_kernel_with_sqrt}---same as \cppLstinline{Exact_predicates_exact _constructions_kernel}, but the number type is a model of the concept that requires operations that perform square roots, namely \cppLstinline{FieldWithSqrt}.\footnote{See \url{https://doc.cgal.org/latest/Algebraic_foundations/classFieldWithSqrt.html}.} % \item \cppLstinline{Exact_predicates_exact_constructions_kernel_with_kth_root}---same as \cppLstinline{Exact_predicates_ exact_constructions_kernel}, but the number type is a model of the concept that requires operations that perform $k$-th roots, namely \cppLstinline{FieldWithKthRoot}.\footnote{See \url{https://doc.cgal.org/latest/Algebraic_foundations/classFieldWithKthRoot.html}} % \item \cppLstinline{Exact_predicates_exact_constructions_kernel_with_root_of}---same as \cppLstinline{Exact_predicates_ exact_constructions_kernel}, but the number type is a model of the concept that requires operations that computes the root of univariate polynomial, namely \cppLstinline{FieldWithRootOf}.\footnote{See \url{https://doc.cgal.org/latest/Algebraic_foundations/classFieldWithRootOf.html}.} \end{compactenum} \begin{table}[!htp] \caption{\cgalPackage{2D and 3D Geometry Kernel}{} module flags} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 1/.style={nodes={text width=17em}}, column 2/.style={nodes={text width=3.5em}}, column 3/.style={nodes={text width=4em}}, column 4/.style={nodes={text width=23.5em}}, row 3/.style={nodes={minimum height=2.8em}} ] { Name & Type & Default & Description\\ \cmakeLstinline{KERNEL_NAME} & String & \myLstinline{epic} & The kernel type used\\ \cmakeLstinline{KERNEL_INTERSECTION_BINDINGS} & Boolean & \myLstinline{true} & Determines whether to generate bindings for intersections\\ }; \end{tikzpicture} \label{tab:ker} \end{table} All the predefined types are of Cartesian kernels. The {\sc CMake}{} flag \cmakeLstinline{CGALPY_KERNEL_NAME} specifies which kernel type should be used for the generated bindings. Currently, only three predefined types and two specific types are supported; see Table~\ref{tab:ker:name}. \begin{table}[!htp] \caption{Kernel name options.} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=8em}}, column 2/.style={nodes={text width=34em}} ] { \cmakeLstinline{KERNEL_NAME} & Predefined Type\\ \myLstinline{epic} & \cppLstinline{Exact_predicates_inexact_constructions_kernel}\\ \myLstinline{epec} & \cppLstinline{Exact_predicates_exact_constructions_kernel}\\ \myLstinline{epecws} & \cppLstinline{Exact_predicates_exact_constructions_kernel_with_sqrt}\\ }; \end{tikzpicture} \centering\begin{tikzpicture} \matrix (first) [tableName, row 2/.append style={nodes={minimum height=2.8em}}, row 3/.append style={nodes={minimum height=2.8em}}, column 1/.style={nodes={text width=19em}}, column 2/.style={nodes={text width=23em}} ] { \cmakeLstinline{KERNEL_NAME} & Predefined Type\\ \myLstinline{filteredSimpleCartesianDouble} & \setlength{\tabcolsep}{0pt}\renewcommand{\arraystretch}{0} \begin{tabular}{l} \cppLstinline{NT = double}\\[5pt] \cppLstinline{Filtered_kernel<Simple_cartesian<NT>>} \end{tabular}\\ \myLstinline{filteredSimpleCartesianLazyGmpq} & \setlength{\tabcolsep}{0pt}\renewcommand{\arraystretch}{0} \begin{tabular}{l} \cppLstinline{NT = Lazy_exact_nt<Gmpq>}\\[5pt] \cppLstinline{Filtered_kernel<Simple_cartesian<NT>>} \end{tabular}\\ }; \end{tikzpicture} \label{tab:ker:name} \end{table} The kernel type determines the underlying number type used to represent coefficients and coordinates of kernel objects and for evaluating mathematical expressions that involve these coefficients and coordinates. The Python attribute \pyLstinline{FT}, nested in the Python namespace \pyLstinline{Ker}, exposes the C++ underlying number type when it is not a primitive data type; that is, when the selected kernel is nor \cppLstinline{Exact_predicates_inexact_constructions_kernel} neither \cppLstinline{Filtered_kernel<Simple_cartesian<double>>}. (In both cases the underlying number type is \cppLstinline{double}.) Similar to the Python code above, the code below defines a two-dimensional point; here, the coordinates are explicitly converted to the underlying number type. \begin{lstlisting}[style=pythonStyle] >>> p = Point_2(Ker.FT(0), Ker.FT(0)) \end{lstlisting} The code excerpt shown in Listing~\ref{lst:cmake:epecFixed}, in the {\sc CMake}{} language, sets the {\sc CMake}{} flags for our first example. When \myLstinline{cmake} is applied with these settings followed by the native build commands (e.g., \bashLstinline{make} on Linux platforms) a library called \myLstinline{CGALPY} is generated. This library consists of the bindings necessary to run the Python example shown in Listing~\ref{lst:py:kerIntersection}, which computes the intersection point of two segments using the generated binding. Observe that bindings of the \cgalPackage{2D and 3D Geometry Kernel}{} module are generated by default, whereas bindings for all other modules must be specifically requested. \begin{lstfloat} \defkd_tree.py{epec_fixed_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,basicstyle=\normalsize, label={lst:cmake:epecFixed}, caption={{\sc CMake}{} flag settings used to generate bindings for the exact-predicates and exact-constructions kernel.}] {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \defkd_tree.py{ker_intersection.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, firstline=14, label={lst:py:kerIntersection}, caption={Computing the intersection between two line segments.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \subsection{$d$-Dimensional Kernel Bindings} \label{ssec:modules:kerneld} {\sc Cgal}{} includes a separate package that consists of constant-size non-modifiable geometric primitive objects in arbitrary dimensions, and operations on these objects, called \cgalPackage{dD Geometry Kernel}{}~\cite{cgal:s-gkd-21a}. Similar to the two- and three-dimensional kernels, the objects of the $d$-dimensional kernels are sets of points in some $d$-dimensional affine Euclidean space, where the dimension $d$ is either static across a kernel type or dynamic; see below for more details. Each point is uniquely represented either by Cartesian coordinates or by homogeneous coordinates. For convenience, {\sc Cgal}{} provides the following predefined types of generally useful kernels: \begin{compactenum} \item \cppLstinline{Epick_d<DimensionTag>}---provides exact geometric predicates, but geometric constructions may be inexact due to round-off errors. % \item \cppLstinline{Epeck_d<DimensionTag>}---provides exact geometric constructions, in addition to exact geometric predicates. % \end{compactenum} Table~\ref{tab:kerd} lists the {\sc CMake}{} flags associated with the \cgalPackage{dD Geometry Kernel}{} module. \begin{table}[!htp] \caption{\cgalPackage{dD Geometry Kernel}{} module flags} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 3/.style={nodes={text width=4.5em}}, column 4/.style={nodes={text width=20.8em}} ] { Name & Type & Default & Description\\ \cmakeLstinline{KERNEL_D_NAME} & String & \myLstinline{epicd} & The kernel type used\\ \cmakeLstinline{KERNEL_D_DIMENSION_TAG} & String & dynamic & Determines whether the dimension is dynamic\\ \cmakeLstinline{KERNEL_D_DIMENSION} & Integer & \myLstinline{2} & The dimension of the ambient Euclidean space\\ }; \end{tikzpicture} \label{tab:kerd} \end{table} The {\sc CMake}{} flag \cmakeLstinline{CGALPY_KERNEL_D_NAME} specifies which kernel type should be used for the generated bindings; see Table~\ref{tab:kerd:name}. \begin{table}[!htp] \caption{$d$-dimensional Kernel name options.} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=19em}}, column 2/.style={nodes={text width=30em}} ] { \cmakeLstinline{KERNEL_D_NAME} & Predefined Type\\ \cmakeLstinline{epicd} & \cppLstinline{Epick_d<DimensionTag>}\\ \cmakeLstinline{epecd} & \cppLstinline{Epeck_d<DimensionTag>}\\ \cmakeLstinline{cartesiandDouble} & \cppLstinline{Cartesian_d<double>}\\ \cmakeLstinline{cartesiandLazyGmpq} & \cppLstinline{Cartesian_d<Lazy_exact_nt<Gmpq>>}\\ }; \end{tikzpicture} \label{tab:kerd:name} \end{table} When either \cppLstinline{Epick_d<DimensionTag>} or \cppLstinline{Epeck_d<DimensionTag>} are instantiated the template parameter must be substituted with a type that represents the dimension of the ambient Euclidean space. It may be either \cppLstinline{Dimension_tag<d>} where $d$ is an integer or \cppLstinline{Dynamic_dimension_tag}. In the latter case, the dimension of the space is specified for each point when it is constructed, so it does not need to be known at compile-time of the bindings. The {\sc CMake}{} \cmakeLstinline{CGALPY_KERNEL_D_DIMENSION_TAG} flag specifies whether the dimension is static or dynamic. If it is static, the dimension is extracted from the {\sc CMake}{} \cmakeLstinline{CGALPY_KERNEL_D_DIMENSION} {\sc CMake}{} flag; ; see Table~\ref{tab:kerd:dim}. \begin{table}[!htp] \caption{$d$-dimensional Kernel dimension tag options.} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=19em}}, column 2/.style={nodes={text width=30em}} ] { \cmakeLstinline{KERNEL_D_DIMENSION_TAG} & Predefined Type\\ \cmakeLstinline{static} & \cppLstinline{Dimension_tag<d>}\\ \cmakeLstinline{dynamic} & \cppLstinline{Dynamic_dimension_tag}\\ }; \end{tikzpicture} \label{tab:kerd:dim} \end{table} The kernel type determines the underlying number type. It is possible to have different underlying number types for the \cgalPackage{2D and 3D Geometry Kernel}{} and the \cgalPackage{dD Geometry Kernel}{} models. However, when the number types differ, expensive conversions might be necessary to combine operations from both kernels, or it may not be possible at all using binding code developed thus far. The code excerpt in the {\sc CMake}{} language shown in Listing~\ref{lst:cmake:cdlg}, sets the {\sc CMake}{} flags for our second example. When \myLstinline{cmake} is applied with these settings followed by the native build commands a library called \myLstinline{CGALPY_kerdCdlgDynamic} is generated. This library consists of the bindings necessary to run the Python example shown in Listing~\ref{lst:py:kerdDoIntersect}, which determines whether two segments in four dimensions intersect using the generated binding. \begin{lstfloat} \defkd_tree.py{cdlg_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,basicstyle=\normalsize, label={lst:cmake:cdlg}, caption={{\sc CMake}{} flag settings used to generate bindings for the $d$-dimensional kernel.}] {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \defkd_tree.py{kerd_do_intersect.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, firstline=14, label={lst:py:kerdDoIntersect}, caption={Determining whether two segments in 4D itersect.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \subsection{2D Arrangement Bindings} \label{ssec:modules:aos2} The {\sc Cgal}{} \emph{arrangements} packages constitute a large component of the {\sc Cgal}{} library. This component is particularly intricate, partly due to the interplay between combinatorial algorithms and algebra~\cite{fhw-caass-12}. Arrangements are space subdivisions induced by curves and surfaces, which have been intensively studied in discrete and computational geometry~\cite{hs-a-18}, and have applications in various domains, from robotics~\cite{my-hs-atarr-95} and assembly planning~\cite{hlw-gfapm-00} through Geographic Information Systems (GIS)~\cite{DBLP:conf/gis/KreveldSW04} to protein structure determination~\cite{DBLP:journals/jcb/MartinYBZD11}, to mention just a few uses. The arrangements packages of {\sc Cgal}{} have been developed since the early days of {\sc Cgal}, first for planar arrangements and maps~\cite{DBLP:journals/jea/FlatoHHNE00, DBLP:journals/comgeo/WeinFZH07}, Boolean operations, and Minkowski sums~\cite{bfhhm-epsph-15}. Then, envelopes of surfaces in three-dimensions have been added~\cite{m-rgece-06}. Finally, a major effort has been undertaken to supports two-dimensional arrangements on (not necessarily planar) surfaces~\cite{bfhks-apsca-10,bfhmw-apsgf-10}. Given a surface $S$ in \Rx{3}\xspace{} and a set ${\cal C}$ of curves embedded in this surface, the curves subdivide $S$ into cells of dimension~$0$ (vertices),~$1$ (edges), and~$2$ (faces). This subdivision is the arrangement ${\cal A}({\cal C})$ induced by ${\cal C}$ on $S$~\cite{fhw-caass-12}. Arrangements embedded in curved surfaces in \Rx{3}\xspace{} are generalizations of arrangements embedded in the plane. The \cgalPackage{2D Arrangements}{} package~\cite{cgal:wfzh-a2-21a} can be used to construct, maintain, alter, and display 2D arrangements embedded in ruled curved surfaces, such as, spheres, ellipses, tori, cones, paraboloids, and the plane. It also supports queries on such arrangements, such as point location and vertical ray shooting. One of the main components of the \cgalPackage{2D Arrangements}{} package is the \cppLstinline{Arrangement_2<Traits, Dcel>} class template. An instance of this template is used to represent an arrangement embedded in the plane. Table~\ref{tab:aos} lists the {\sc CMake}{} flags associated with the \cgalPackage{2D Arrangements}{} module. A description of the two template parameters of this class template follows. \begin{table}[!htp] \caption{\cgalPackage{2D Arrangements}{} module flags} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 1/.style={nodes={text width=17.4em}}, column 2/.style={nodes={text width=4.6em}}, column 3/.style={nodes={text width=4.6em}}, column 4/.style={nodes={text width=21.5em}}, row 6/.style={nodes={minimum height=2.8em}} ] { Name & Type & Default & Description\\ \cmakeLstinline{AOS2_GEOMETRY_TRAITS_NAME} & \cmakeLstinline{String} & \myLstinline{segment} & The basic geometry traits\\ \myLstinline{AOS2_EXTEND_VERTEX} & \cmakeLstinline{Boolean} & \myLstinline{false} & Determines whether to extend the vertex type\\ \myLstinline{AOS2_EXTEND_HALFEDGE} & \cmakeLstinline{Boolean} & \myLstinline{false} & Determines whether to extend the halfedge type\\ \myLstinline{AOS2_EXTEND_FACE} & \cmakeLstinline{Boolean} & \myLstinline{false} & Determines whether to extend the face type\\ \myLstinline{AOS2_POINT_LOCATION_BINDINGS} & \cmakeLstinline{Boolean} & \myLstinline{true} & Determines whether to generate bindings for point location and vertical ray shooting queries\\ }; \end{tikzpicture} \label{tab:aos} \end{table} \begin{itemize} \item The \cppLstinline{Traits} template-parameter determines the family of curves that induce the arrangement. The parameter should be substituted with a model of the basic arrangement traits concept or one or more concepts that refine the basic concept. A model of the basic traits concept defines the types of x-monotone curves and two-dimensional points and supports basic geometric predicates on them. A rather large directed acyclic graph is required to capture the entire hierarchy of the geometry traits-class concepts; therefore, we typically use subgraphs to describe the refinement relations among closely related concepts, and refer to these subgraph as clusters. Figure~\ref{fig:atc} depicts four clusters. The list of supported traits class templates follows. For each class template we describe the family of curves it handles. % \begin{compactenum} \item \cppLstinline{Arr_non_caching_segment_basic_traits_2<>}---handles segments. \item \cppLstinline{Arr_segment_traits_2<>}---handles segments, where each segment is represented a by its supporting line in addition to its two endpoints. \item \cppLstinline{Arr_linear_traits_2<>}---handles linear curves, i.e., segments, rays, and lines. \item \cppLstinline{Arr_polyline_traits_2<>}---handles polylines. \item \cppLstinline{Arr_circle_segment_traits_2<>}---handles segments and circular arcs. \item \cppLstinline{Arr_conic_traits_2<>}---handle conic arcs. \item \cppLstinline{Arr_rational_function_traits_2<>}---handle rational functions. \item \cppLstinline{Arr_Bezier_curve_traits_2<>}---handles B\'ezier curves of arbitrary degrees. \item \cppLstinline{Arr_algebraic_segment_traits_2<>}---handles algebraic curves of arbitrary degrees. \item \cppLstinline{Arr_polycurve_traits_2<>}---handle polycurves, which are piecewise curves that are not necessarily linear. \end{compactenum} The {\sc CMake}{} flag \cmakeLstinline{CGALPY_AOS2_GEOMETRY_TRAITS_NAME} specifies which geometry traits should be used for the generated bindings; see Table~\ref{tab:aos:gt}. Observe that instances of the class templates \cppLstinline{General_polygon_set_2<>} and \cppLstinline{Polygon_set_2<>} (see Section~\ref{ssec:modules:bso2}) employ 2D arrangement types. Bindings for instances of \cppLstinline{Polygon_set_2<>} and \cppLstinline{General_polygon_set_2<>} are enabled as part of the bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package. When bindings for \cgalPackage{2D Regularized Boolean Set-Operations}{} package are enabled bindings of the \cgalPackage{2D Arrangements}{} package must be explicitly enabled as well. The traits type that substitutes the traits parameter determines the type of curves that bound the polygons or generalized polygons, and the type must be explicitly indicated too (unless the segment type is selected, which is the default). The traits type must also model the \cppLstinline{GeneralPolygonSetTraits_2} concept; see Figure~\ref{fig:atc:gps} for the relevant traits-concept cluster. The final traits type that is used for the bindings is automatically extended to respect this requirement. The details of this extension is given in Section~\ref{sec:extenders:arrTraits} of the appendix. % \item The \cppLstinline{Dcel} template-parameter should be substituted with a type that models the \cppLstinline{ArrangementDcel} concept, which is used to represent the topological layout of the arrangement.\footnote{See \url{https://doc.cgal.org/latest/Arrangement_on_surface_2/classArrangementDcel.html}.} This layout is, in particular, represented by a doubly-connected edge list data-structure (DCEL for short), which consists of containers of vertices, edges and faces and maintains the incidence relations among these objects. We substitute this type with an instance of the template \cppLstinline{CGAL::Arr_dcel_base<V, H, F>}, where \cppLstinline{V}, \cppLstinline{H}, and \cppLstinline{F} are models of the concepts\linebreak \cppLstinline{ArrangementDcelVertex}, \cppLstinline{ArrangementDcelHalfedge}, and \cppLstinline{ArrangementDcelFace}, respectively; by default they are substituted with \cppLstinline{Arr_vertex_base<Traits::Point_2>}, \cppLstinline{Arr_halfedge_base<Traits::X_monotone_curve_2>}, and \cppLstinline{Arr_face_base}, respectively. In many applications it is necessary to extend the types of the DCEL main features. This is governed by three {\sc CMake}{} Boolean flags as follows. If any one of the {\sc CMake}{} variables \cmakeLstinline{CGALPY_AOS2_VERTEX_EXTENDED}, \cmakeLstinline{CGALPY_AOS2_HALFEDGE_EXTENDED}, or \cmakeLstinline{CGALPY_AOS2_FACE_EXTENDED} is set to true, the corresponding template parameter, \cppLstinline{V}, \cppLstinline{H}, or \cppLstinline{F}, is substituted with instances of \cppLstinline{Arr_extended_vertex<Vb, VertexData>}, \cppLstinline{Arr_extended_halfedge<Hb, HalfedgeData>}, or \cppLstinline{Arr_extended_face<Fb, FaceData>}, respectively, where \cppLstinline{Vb}, \cppLstinline{Hb}, and \cppLstinline{Fb} are the basic types above. It is impossible to define a custom C++ type from Python code. Therefore, when the bindings are generated each one of the \cppLstinline{VertexData}, \cppLstinline{HalfedgeData}, and \cppLstinline{FaceData} template parameters must be substituted with a C++ type known at the time the bindings were implemented. Flexibility is nevertheless retained by substituting every one of these parameters with the generic Python object \cppLstinline{bp::object} when the respective cell is extended.\footnote{For more information on Python objects, see, e.g., \url{https://docs.python.org/3/library/functions.html?highlight=object\#object}.} This object provides a general interface to Python objects. % If bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package is enabled, the template parameters \cppLstinline{H} and \cppLstinline{F} above are substituted with types that also model the concepts \cppLstinline{GeneralPolygonSetDcelHalfedge}, and \cppLstinline{GeneralPolygonSetDcelFace}, respectively; see Section~\ref{ssec:modules:bso2}. The final types that are used for the bindings are automatically extended to respect this requirement. The details of this extension is given in Section~\ref{sec:extenders:arrDcel} of the appendix. \end{itemize} \begin{figure}[!htp] \def\name#1{\scriptsize\cppLstinline{#1}} \tikzset{concept/.style={rectangle split,rectangle split parts=1,draw, fill=white,blur shadow,rounded corners,align=center}} \captionsetup[subfigure]{justification=centering} \centering% \subfloat[]{\label{fig:atc:central} \begin{forest} [\name{AosBasicTraits_2},for tree={concept,edge={-latex}} [\name{AosXMonotoneTraits_2} [\name{AosTraits_2}] ] ] \end{forest}}\quad \subfloat[]{\label{fig:atc:landmark} \begin{forest} [\name{AosBasicTraits_2},name=abt,for tree={concept,edge={-latex}} [\name{AosApproximateTraits_2} [,phantom] [\name{AosLandmarkTraits_2},name=alt,before drawing tree={x=0}] ] [\name{AosConstructXMonotoneCurveTraits_2},name=acxmt] ] \draw[-latex] (acxmt) to (alt); \end{forest}}\\ % \subfloat[]{\label{fig:atc:openBoundary} \begin{forest} [\name{AosBasicTraits_2},name=abt,before drawing tree={x=0pt},for tree={concept,edge={-latex}} [\name{AosVerticalSideTraits_2} [\name{AosLeftSideTraits_2} [\name{AosOpenLeftTraits_2},name=olt [,phantom] [\name{AosOpenBoundaryTraits_2},name=oyt,before drawing tree={x=0pt}] ] ] [\name{AosRightSideTraits_2} [\name{AosOpenRightTraits_2},name=ort] ] ] [\name{AosHorizontalSideTraits_2} [\name{AosBottomSideTraits_2} [\name{AosOpenBottomTraits_2},name=obt] ] [\name{AosTopSideTraits_2} [\name{AosOpenTopTraits_2},name=ott] ] ] ] \draw[-latex] (ort) to (oyt); \draw[-latex] (obt) to (oyt); \draw[-latex] (ott) to (oyt); \end{forest}}\\ % \subfloat[]{\label{fig:atc:sphericalBoundary} \begin{forest} [\name{AosBasicTraits_2},name=abt,before drawing tree={x=0pt},for tree={concept,edge={-latex}} [\name{AosVerticalSideTraits_2} [\name{AosLeftSideTraits_2} [,phantom] [\name{AosIdentifiedVerticalTraits_2},name=ivt [,phantom] [\name{AosSphericalBoundaryTraits_2},name=sbt,before drawing tree={x=0pt}] ] ] [\name{AosRightSideTraits_2},name=rst] ] [\name{AosHorizontalSideTraits_2} [\name{AosBottomSideTraits_2} [\name{AosContractedBottomCurveTraits_2},name=cbt] ] [\name{AosTopSideTraits_2} [\name{AosContractedTopCurveTraits_2},name=ctt] ] ] ] \draw[-latex] (cbt) to (sbt); \draw[-latex] (ctt) to (sbt); \draw[-latex] (rst) to (ivt); \end{forest}} \caption[]{% \subref{fig:atc:central}~The central cluster.% \subref{fig:atc:landmark}~The landmark cluster.% \subref{fig:atc:openBoundary}~The open boundary cluster.% \subref{fig:atc:sphericalBoundary}~The spherical boundary cluster.} \label{fig:atc} \end{figure} \begin{table}[!htp] \caption{2D arrangement geometry traits options} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=18em}}, column 2/.style={nodes={text width=31em}} ] { \cmakeLstinline{AOS2_GEOMETRY_TRAITS_NAME} & Type\\ \myLstinline{nonCachingSegment} & \cppLstinline{Arr_non_caching_segment_basic_traits_2<Kernel>}\\ \myLstinline{segment} & \cppLstinline{Arr_segment_traits_2<Kernel>}\\ \myLstinline{linear} & \cppLstinline{Arr_linear_traits_2<Kernel>}\\ \myLstinline{conic} & \cppLstinline{Arr_conic_traits_2<RatKernel, AlgKernel, NtTraits>}\\ \myLstinline{circleSegment} & \cppLstinline{Arr_circle_segment_traits_2<Kernel>}\\ \myLstinline{algebraic} & \cppLstinline{Arr_algebraic_segment_traits_2<Coefficient>}\\ }; \end{tikzpicture} \label{tab:aos:gt} \end{table} The code excerpt shown in Listing~\ref{lst:cmake:aos2EpecFaceExtended} in the {\sc CMake}{} language sets the {\sc CMake}{} flags for our next example shown in Listing~\ref{lst:py:aos2Fex}. This example constructs an arrangement with two faces. The arrangement is induced by line segments and its face type is extended. The properties of the bounded face and the unbounded face are initialized with Python integer objects '0' and '1', respectively. \begin{lstfloat} \defkd_tree.py{aos2_epec_face_extended_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,% basicstyle=\normalsize,% label={lst:cmake:aos2EpecFaceExtended},% caption={{\sc CMake}{} flag settings used to generate bindings for 2D arrangements with their faces extended.}]% {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \defkd_tree.py{aos2_fex.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, firstline=14, label={lst:py:aos2Fex}, caption={Constructing an arrangement with its faces extended and initializing their data.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \subsection{2D Regularized Boolean Set Operation Bindings} \label{ssec:modules:bso2} The {\sc Cgal}{} package \cgalPackage{2D Regularized Boolean Set-Operations}{} consists of the implementation of regularized Boolean set-operations, intersection predicates, and point containment predicates on point sets bounded by weakly $x$-monotone curves in two-dimensional Euclidean space~\cite{cgal:fwzh-rbso2-21a}. The \cgalPackage{2D Regularized Boolean Set-Operations}{} module is not associated with {\sc CMake}{} flags (besides the flag \cmakeLstinline{CGALPY_BOOLEAN_SET_OPERATIONS_2_BINDINGS}, which indicates whether to generate bindings for this module). The Boolean set operations supported by this package depend on the \cgalPackage{2D Arrangements}{} package. If the operations are applied on (linear) polygons they also depend on the \cgalPackage{2D Polygons}{} package. Recall, that both further depend on the \cgalPackage{2D and 3D Geometry Kernel}{} package. Therefore, bindings for these packages must be explicitly enabled as well when bindings for the \cgalPackage{2D Regularized Boolean Set-Operations}{} package are enabled. The code excerpt shown in Listing~\ref{lst:cmake:bso2EpecCs} in the {\sc CMake}{} language sets the {\sc CMake}{} flags for our next example. Applying these settings followed by the native build commands generates a library, the basename of which is \myLstinline{CGALPY_kerEpec_ aos2Cs_bso2_pol2}. It supports bindings for the types below and operations on these types, but nothing else. \begin{compactitem} \item kernel types, \item line segment and circular arc, \item arrangement in the plane induced by curves of the above types, \item generalized polygon and generalized polygon with holes bounded by curves of the above types, and \item Boolean operations on generalized polygons of the above types. \end{compactitem} \begin{lstfloat} \defkd_tree.py{bso2_epec_cs_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,% basicstyle=\normalsize,% label={lst:cmake:bso2EpecCs},% caption={{\sc CMake}{} flag settings used to generate bindings for 2D regularized Boolean operations on generalized polygons bounded by line segments and circular arcs.}]% {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} This library can be used to execute the Python example shown in Listing~\ref{lst:py:circleSegmentPolygons}; the example constructs a general polygon-set that represents the point set depicted in Figure~\ref{fig:csp}. It is the result of the union of four disjoint circles and four rectangles. Each circle is represented as a generalized polygon bounded by two x-monotone circular arcs. The union is computed incrementally, resulting with a single generalized polygon with a single hole. Note that as the four circles are disjoint, their union is computed with the \cppLstinline{insert()} function, while the union with the rectangles is computed with the \cppLstinline{join()} function. \begin{lstfloat} \defkd_tree.py{circle_segment_polygons.py}% \lstinputlisting[style=pythonFramedStyle,% basicstyle=\normalsize,% firstline=15,lastline=61,% label={lst:py:circleSegmentPolygons},% caption={Constructing a general polygon-set that represents the point set depicted in Figure~\ref{fig:csp}.}]% {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \begin{figure}[!htp] \def\name#1{\scriptsize\cppLstinline{#1}} \tikzset{concept/.style={rectangle split,rectangle split parts=1,draw, fill=white,blur shadow,rounded corners,align=center}} \captionsetup[subfigure]{justification=centering} \centering% \subfloat[]{\label{fig:csp} \begin{tikzpicture} \fill[lightgray] (0.5,0) rectangle (2.5,1); \fill[lightgray] (0.5,2) rectangle (2.5,3); \fill[lightgray] (0,0.5) rectangle (1,2.5); \fill[lightgray] (2,0.5) rectangle (3,2.5); \filldraw[fill=gray,draw=black](0.5,0.5) circle (0.5); \filldraw[fill=gray,draw=black](2.5,0.5) circle (0.5); \filldraw[fill=gray,draw=black](0.5,2.5) circle (0.5); \filldraw[fill=gray,draw=black](2.5,2.5) circle (0.5); \draw[black] (0.5,0) rectangle (2.5,1); \draw[black] (0.5,2) rectangle (2.5,3); \draw[black] (0,0.5) rectangle (1,2.5); \draw[black] (2,0.5) rectangle (3,2.5); \end{tikzpicture}}\quad \subfloat[]{\label{fig:atc:gps} \begin{forest} [\name{AosXMonotoneTraits_2},for tree={concept,edge={-latex}} [\name{AosDirectionalXMonotoneTraits_2} [\name{GeneralPolygonSetTraits_2}] ] ] \end{forest}} \caption[]{% \subref{fig:csp}~A generalized polygon with holes bounded by circular arcs and line segments. \subref{fig:atc:gps}~The general point-set cluster.} \label{fig:bso2} \end{figure} An arrangement data structure is internally used to represent the point set maintained by the general polygon-set; it is possible to obtain it and apply further operations on it, as demonstrated by the code excerpt shown in Listing~\ref{lst:py:circleSegmentPolygonsArr}. \begin{lstfloat} \defkd_tree.py{circle_segment_polygons.py}% \lstinputlisting[style=pythonFramedStyle,% basicstyle=\normalsize,% firstline=62,% label={lst:py:circleSegmentPolygonsArr},% caption={Extracting the arrangement from a point set.}]% {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} The bindings for the \cgalPackage{2D Arrangements}{} package includes bindings for the geometry traits and the DCEL suitable for Boolean operations. In particular, the traits must model the concept \cppLstinline{GeneralPolygonSetTraits_2}; see Figure~\ref{fig:atc:gps}. \subsection{2D Minkowski Sums} \label{ssec:modules:ms2} Given two sets of points ${\cal A}, {\cal B} \in \Rx{d}\xspace$ their Minkowski sum, denoted by ${\cal A} \oplus {\cal B}$, is their point-wise sum, namely the set $\{a+b|\, a \in {\cal A},b \in {\cal B}\}$. The {\sc Cgal}{} package \cgalPackage{2D Minkowski Sums}{} contains functions that compute the planar Minkowski sum of two polygons and the planar Minkowski sum of a simple polygon and a disc---an operation also referred to as offsetting or dilating a polygon. The package also supports inner offsetting a polygon (also referred to as insetting), which is equivalent to the complement of the offset of (i) a disk and (ii) the complement of a polygon~\cite{cgal:w-rms2-21a}. The \cgalPackage{2D Minkowski Sums}{} module is not associated with any {\sc CMake}{} flags (besides the flag \cmakeLstinline{CGALPY_MINKOWSKI_SUM_2_BINDINGS}, which indicates whether to generate bindings for this module). Similar to the case of generating bindings of Boolean operations on (linear) polygons supported by the \cgalPackage{2D Regularized Boolean Set-Operations}{} package, the operations supported by this package depend on the \cgalPackage{2D and 3D Geometry Kernel}{}, \cgalPackage{2D Arrangements}{}, and \cgalPackage{2D Polygons}{} packages. Therefore, bindings for these packages must be explicitly enabled as well when bindings for the \cgalPackage{2D Minkowski Sums}{} package are enabled. The result of the inset and offset operations is a generalized polygon bounded by line segments and circular arc. Binding for a type that represents such polygons, that is, an instance of \cppLstinline{CGAL::General_polygon_with_holes_2<>} is generated as well. The function \cppLstinline{CGAL::minkowski_sum()} is extremely overloaded. It can be used to compute the Minkowski sum of two polygons either applying the \emph{convex-decomposition} approach or the \emph{reduced-convolution} approach. When applying the \emph{convex-decomposition} approach we first decompose each summand into convex sub-polygons. The function template \cppLstinline{CGAL::minkowski_sum_by_full_convolution_2()} applies a third approach, namely \emph{full convolution}. For more information on the various approaches refer to the manual. There are two overloaded function templates \cppLstinline{CGAL::minkowski_sum()} that apply the \emph{reduced-convolution} approach; both accepts the two input polygons as input; one also accepts a specific geometry traits as input (while the other constructs and uses a default traits object). Each type of the summands must represent either a simple polygon or a polygon with holes. The signature of the former is shown in Listing~\ref{lst:cpp:minkSum}, where each of \cppLstinline{PolygonType1} and \cppLstinline{PolygonType2} can be substituted either with \cppLstinline{Polygon_2} or with \cppLstinline{Polygon_with_holes_2}. Thus, given a specific kernel and container types, we get eight overloaded instances that apply the \emph{reduced-convolution} approach in total. (The Container type determines the representation of the polygon's extreme points in memory.) \begin{lstfloat} \begin{lstlisting}[style=cppFramedStyle,basicstyle=\normalsize, label={lst:cpp:minkSum}, caption={The signature of one of the \cppLstinline{CGAL::minkowski_sum_2} overloaded function templates.}] template <typename Kernel, typename Container> Polygon_with_holes_2<Kernel, Container> minkowski_sum_2(const PolygonType1<Kernel, Container>& p, const PolygonType2<Kernel, Container>& q) \end{lstlisting} \end{lstfloat} There are two sets of function templates \cppLstinline{CGAL::minkowski_sum()} that apply the \emph{convex-decomposition} approach; all functions accepts the two input polygons as input; functions in one set also accept a specific geometry traits as input. As with the functions that apply the \emph{reduced-convolution} approach, each type of the summands must be substituted either with a type that represents a simple polygon or a type that represents a polygon with holes. Each set consists of two function templates; one is parameterized with the type that represents a single decomposition strategy that should be applied to both summands and another one that is parameterized with two types that represents two decomposition strategies that should be applied to the two summands, respectively. The package provides four types of decomposition strategies; however, only two can be applied to a polygon with holes. Listing~\ref{lst:minkSumConvexDecomposition} shows the signatures of the two function templates that do not accept a traits parameter. We get 10~overloaded instances of functions that apply the \emph{convex-decomposition} approach, do not accept a traits parameter, and are parameterized with a single decomposition strategy. We get 36~overloaded instances of functions that apply the \emph{convex-decomposition} approach, do not accept a traits parameter, and are parameterized with two decomposition strategies. Thus, given a specific kernel and container types, we get $2 \times (10 + 36) = 92$ overloaded instances of functions that apply the \emph{convex-decomposition} approach. The \cppLstinline{approximated_inset_2(P, r, eps, oi)} function template accepts a polygon $P$, an inset radius $r$, (a floating-point number\index{number!floating-point}) $\epsilon > 0$, and an output iterator\index{iterator!output} \cppLstinline{oi}; dereferencing the iterator must yield an instance of the class template \cppLstinline{Gps_circle_segment_traits_2::Polygon_2}. It constructs an approximation of the inset of $P$ by the radius $r$, where the approximation error is bounded by $\epsilon$. The function returns the polygons that approximate the inset polygon through the output iterator \cppLstinline{oi}. The code excerpt shown in Listing~\ref{lst:py:approxInset} demonstrates the construction of an approximated inner offset; see Figure~\ref{fig:ms2:inset}. \begin{lstfloat} \defkd_tree.py{approx_inset.py}% \lstinputlisting[style=pythonFramedStyle,% basicstyle=\normalsize,% firstline=35,% label={lst:py:approxInset},% caption={Computing the approximated inner offset.}]% {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \begin{SCfigure}[][!htp] \begin{tikzpicture}[scale=0.4] \coordinate (c1) at (8,3); \coordinate (p11) at (8.94868,3.31623); \coordinate (p12) at (7.05132,3.31623); % \coordinate (c2) at (6,7); \coordinate (p21) at (6.78087,6.3753); \coordinate (p22) at (7,7); % \filldraw [color=polyADarkColor,fill=polyALightColor,thick] (4, 0)--(7,0)--(8,3)--(9,0)--(13,0)--(13,8)--(7,8)--(7,9)-- (13,9)--(13,14)--(0,14)--(0,12)--(6,9)--(6,7)--(2,2)--cycle; \filldraw [color=polyCDarkColor,fill=polyCLightColor,thick] let \p1 = ($(p11) - (c1)$), \p2 = ($(p12) - (c1)$), \n0 = {veclen(\x1,\y1)}, \n1 = {atan2(\y1,\x1)}, \n2 = {atan2(\y2,\x2)}, \p3 = ($(p21) - (c2)$), \p4 = ($(p22) - (c2)$), \n3 = {veclen(\x3,\y4)}, \n4 = {atan2(\y3,\x4)}, \n5 = {atan2(\y3,\x4)} in (7,7)--(12,7)--(12,1)--(9.72076,1)--(9.29057,2.29057)--(p11)arc(\n1:\n2:\n0)-- (6.3932,1.34189)--(6.27924,1)--(4.41421,1)--(3.34,2.07422)--(3.53148,2.31357)-- (p21)arc(\n4:\n5:\n3)--cycle; \filldraw [color=polyCDarkColor,fill=polyCLightColor,thick] (1,13)--(12,13)--(12,10)--(7,10)-- (6.5,9.86603)-- (6.44721,9.89443)--(4.78885,10.7236)--(1,12.618)--(1,13)--cycle; \end{tikzpicture} \caption{% The inset (yellow) of a polygon (blue) with a tight corridor consists of two generalized polygons bounded by line segments and circular arcs.} \label{fig:ms2:inset} \end{SCfigure} \subsection{2D Triangulation Bindings} \label{ssec:modules:tri2} Triangulation is perhaps the most common term in the lexicon of computational geometry. Triangulations are ubiquitous geometric data structures, which are used in numerous areas, such as, GIS, robotics, geometric modeling and meshing to name a few; see, e.g.,~\cite{by-ag-98} for a survey on triangulations. The triangulation packages of {\sc Cgal}{} are integral parts of the library and have constantly improved and enhanced since the early days of {\sc Cgal}{}. In two-dimensions {\sc Cgal}{} offers basic, Delaunay and regular triangulations, as well as constrained triangulations and constrained Delaunay triangulations. In three dimensions {\sc Cgal}{} offers basic, Delaunay, and regular triangulations. {\sc Cgal}{} also offers periodic triangulations both in the plane and in space~\cite{ct-cpt-09}. A triangulation of a set of points ${\cal P}$ in \Rx{2}\xspace is a partition of the convex hull of ${\cal P}$ into triangles whose vertices are the points of ${\cal P}$. Together with the unbounded face having the convex hull boundary as its frontier, the triangulation forms a partition of \Rx{2}\xspace. Any two facets (2-face) are either disjoint or share a common edge (1-face) or vertex (0-face). A triangulation can be described as a simplicial complex. The binding module \cgalPackage{2D Triangulations}{} consists of bindings of types provided by the {\sc Cgal}{} packages \cgalPackage{2D Triangulations}{} and \cgalPackage{2D Periodic Triangulations}{}. Table~\ref{tab:tri2} lists the {\sc CMake}{} flags associated with the \cgalPackage{2D Triangulations}{} module. \begin{table}[!htp] \caption{\cgalPackage{2D Triangulations}{} module flags.} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 1/.style={nodes={text width=16.0em}}, column 3/.style={nodes={text width=5.7em}}, column 4/.style={nodes={text width=21.6em}}, row 6/.append style={nodes={minimum height=2.8em}} ] { Name & Type & Default & Description\\ \cmakeLstinline{TRI2_NAME} & String & \myLstinline{plain} & The 2D triangulation type\\ \cmakeLstinline{TRI2_VERTEX_WITH_INFO} & Boolean & \myLstinline{false} & Determines whether the vertex type is extended\\ \cmakeLstinline{TRI2_FACE_WITH_INFO} & Boolean & \myLstinline{false} & Determines whether the face type is extended\\ \cmakeLstinline{TRI2_INTERSECTION_TAG_NAME} & String & \myLstinline{ncirc} & The intersection tag\\ \cmakeLstinline{TRI2_HIERARCHY} & Boolean & \myLstinline{false} & Determines whether to generate the binding for a hierarchy triangulation\\ }; \end{tikzpicture} \label{tab:tri2} \end{table} The \cgalPackage{2D Triangulations}{} package~\cite{cgal:y-t2-21a} provides several class templates, instances of which can be used to represent a variety of 2D triangulations. In particular, the package provides the following class templates: \begin{compactenum} \item \cppLstinline{Triangulation_2<Traits, Tds>}, \item \cppLstinline{Regular_triangulation_2<Traits, Tds>}, \item \cppLstinline{Delaunay_triangulation_2<Traits, Tds>}, \item \cppLstinline{Constrained_triangulation_2<Traits, Tds, Itag>}, \item \cppLstinline{Constrained_Delaunay_triangulation_2<Traits, Tds, Itag>}, and \item \cppLstinline{Triangulation_hierarchy_2<Triangulation_2>} \end{compactenum} Instances of the \cppLstinline{Delaunay_triangulation_2<>} and \cppLstinline{Regular_triangulation_2<>} class templates can be used to represent Delaunay and regular triangulation, respectively. In a regular triangulation points have an associated weight, and some points can be hidden and do not result in vertices in the triangulation. The class template \cppLstinline{Triangulation_hierarchy_2} enables fast point location queries. When instantiated its template parameter must be substituted with an instance of any other triangulation class template. The \cgalPackage{2D Periodic Triangulations}{} package~\cite{cgal:k-pt2-13-21a} supports triangulations of sets of points in the two-dimensional flat torus~\cite{ct-cpt-09}. This package provides the class templates \begin{compactenum} \item \cppLstinline{Periodic_2_triangulation_2<Traits, Tds>}, \item \cppLstinline{Periodic_2_Delaunay_triangulation_2<Traits, Tds>}, and \item \cppLstinline{Periodic_2_triangulation_hierarchy_2<PeriodicTriangulation>} \end{compactenum} The {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI2_NAME} specifies the particular type of triangulation, bindings for which should be generated; see Table~\ref{tab:tri2:names}. \begin{table}[!htp] \caption{2D triangulation name options} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=11.5em}}, column 2/.style={nodes={text width=37.5em}} ] { \cmakeLstinline{TRI2_NAME} & Type\\ \myLstinline{plain} & \cppLstinline{Triangulation_2<Traits, Tds>}\\ \myLstinline{regular} & \cppLstinline{Regular_triangulation_2<Traits, Tds>}\\ \myLstinline{delaunay} & \cppLstinline{Delaunay_triangulation_2<Traits, Tds>}\\ \myLstinline{constrained} & \cppLstinline{Constrained_triangulation_2<Traits, Tds, Itag>}\\ \myLstinline{constrainedDelaunay} & \cppLstinline{Constrained_Delaunay_triangulation_2<Traits, Tds, Itag>}\\ \myLstinline{periodicPlain} & \cppLstinline{Periodic_2_triangulation_2<Traits, Tds>}\\ \myLstinline{periodicDelaunay} & \cppLstinline{Periodic_2_Delaunay_triangulation_2<Traits, Tds>}\\ }; \end{tikzpicture} \label{tab:tri2:names} \end{table} When any template above is instantiated the template parameter \cppLstinline{Traits} must be substituted with a model of a suitable geometric traits concept; this model is referred to as the geometric traits class; it provides the type of points to use as well as elementary operations on points of the indicated type. The type of traits used for the generated bindings is determined based on the selection of the triangulation type as explained below. It is conveniently defined in C++ as \cppLstinline{Dt::Geom_traits}, where \cppLstinline{Dt} is a triangulation instance. This type is exposed as a Python attribute with the same name under \pyLstinline{Triangulation_2} (which in turn is nested under the Python namespace \pyLstinline{Tri2}). Figure~\ref{tab:tri2:concept-hierarchy} depicts the 2D triangulation traits concept hierarchy. Any kernel instance is a model of any non-periodic traits concept; thus, when one of the templates \begin{compactenum} \item \cppLstinline{Triangulation_2<Traits, Tds>}, \item \cppLstinline{Regular_triangulation_2<Traits, Tds>}, \item \cppLstinline{Delaunay_triangulation_2<Traits, Tds>}, \item \cppLstinline{Constrained_triangulation_2<Traits, Tds, Itag>}, or \item \cppLstinline{Constrained_Delaunay_triangulation_2<Traits, Tds, Itag>} \end{compactenum} is instantiated, the \cppLstinline{Traits} parameter is substituted with the \cppLstinline{Kernel} type (the selected kernel; see Section~\ref{ssec:modules:kernel}). When one of the templates \begin{compactenum} \item \cppLstinline{Periodic_2_triangulation_2<Traits, Tds>} or \item \cppLstinline{Periodic_2_Delaunay_triangulation_2<Traits, Tds>} \end{compactenum} is instantiated, the \cppLstinline{Traits} parameter is substituted with \cppLstinline{Periodic_2_triangulation_traits_2<Kernel>} or \cppLstinline{Periodic_2_Delaunay_triangulation_traits_2<Kernel>}, respectively. Observe that when a Delaunay triangulation instance is used to define an alpha shape type (see Section~\ref{ssec:modules:as2}), the traits parameter must be substituted with a traits class that models the \cppLstinline{AlphaShapeTraits_2} concept. Similarly, when a regular triangulation instance is used to define a fixed alpha shape type (see Section~\ref{ssec:modules:as2}), the traits parameter must be substituted with a traits class that models the \cppLstinline{WeightedAlphaShapeTraits_2} concept. Also in these cases the selected kernel serves as the traits. \begin{figure}[!htp] \def\name#1{\scriptsize\cppLstinline{#1}} \tikzset{% concept/.style={rectangle,rounded corners,align=center, draw,fill=white,blur shadow } } \forestset{ my tree style/.style={ for tree={concept, parent anchor=south, child anchor=north, edge={->,>=stealth,black,thick}, edge path= \noexpand\path [draw, \forestoption{edge}] (!u.parent anchor)--(.child anchor)\forestoption{edge label}; }, if n children=3 for children= if n=2{calign with current}{} } }{}, } } } \centering% \begin{forest} my tree style [ \name{TriTr2} [ \name{RegularTriTr2} [ \name{WeightedAlphaShapeTr2} ] ] [ \name{Pr2TriTr2},name=p ] [ \name{DelaunayTriTr2},name=d [ \name{Pr2DelaunayTriTr2},name=pd [ \name{Pr2AlphaShapeTr2} ] ] [ \name{AlphaShapeTr2} ] ] [ \name{ConstrainedTriTr2} [ \name{ConstrainedDelaunayTriTr2},name=cd ] ] ] \draw[->,>=stealth] (d.parent anchor)--(cd.child anchor); \draw[->,>=stealth] (p.parent anchor)--(pd.child anchor); \end{forest} \caption{The 2D triangulation traits concept hierarchy. \cppLstinline{Triangulation}, \cppLstinline{Periodic_2} and \cppLstinline{Traits_2} are abbreviated as \cppLstinline{Tri}, \cppLstinline{Pr2}, and \cppLstinline{Tr2}, respectively.} \label{tab:tri2:concept-hierarchy} \end{figure} The {\sc CMake}{} Boolean flag \cmakeLstinline{CGALPY_TRI2_HIERARCHY} indicates whether the type of triangulation, bindings for which should be generated, is an instance of one of the triangulation hierarchy templates, namely, \begin{compactitem} \item \cppLstinline{Triangulation_hierarchy_2<Triangulation_2>} and \item \cppLstinline{Periodic_triangulation_hierarchy_2<PeriodicTriangulation_ 2>}. \end{compactitem} The template parameter in both cases is substituted with the triangulation selected via the {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI2_ NAME}, which also determines whether to use the non-periodic or periodic version above. The type that substitutes the \cppLstinline{Tds} parameter models the concept \cppLstinline{TriangulationDataStructure_2}. An object of this type stores the combinatorial structure of the triangulation; it is an instance of the class template \cppLstinline{Triangulation_data_structure_2<V, F>}. The types that substitute the \cppLstinline{V} and \cppLstinline{F} template parameters when the template \cppLstinline{Triangulation_data_structure_2<V, F>} is instantiated represent the type of the vertex and the type of the face of the triangulation, respectively; they must model the concepts \cppLstinline{TriangulationDSVertexBase_2} and \cppLstinline{TriangulationDSFaceBase_2}, respectively. If the binding is generated for a periodic triangulation, these parameters must be substituted with types that also model the concepts \cppLstinline{Periodic_2TriangulationDSVertexBase_ 2} and \cppLstinline{Periodic_2TriangulationDSFaceBase_2}, respectively. If the triangulation is used to define an alpha shape type, these parameters must be substituted with types that also model the concepts \cppLstinline{AlphaShapeVertex_2} and \cppLstinline{AlphaShapeFace_2}, respectively; see Section~\ref{ssec:modules:as2}. Finally, if the binding is generated for a hierarchy triangulation, e.g., an instance of the template parameter \cppLstinline{Triangulation_hierarchy_2<Triangulation_2>}, the \cppLstinline{V} template parameter must be substituted with a model of the concept \cppLstinline{TriangulationHierarchyVertexBase_2}. (Observe that there is no special requirements on the type that substitutes the \cppLstinline{F} parameter in this case.) Similar to the 2D arrangement data structure, it is possible to extend the vertex and face types of the triangulation. This is governed by two {\sc CMake}{} Boolean flags as follows. If any one of the {\sc CMake}{} variables \cmakeLstinline{CGALPY_TRI2_VERTEX_WITH_INFO} or \cmakeLstinline{CGALPY_TRI2_FACE_WITH_INFO} is set to true, the corresponding template parameter, \cppLstinline{V} or \cppLstinline{F}, is substituted with instances of \cppLstinline{CGAL::Triangulation_vertex_base_with_info_2<bp::object, Traits, Vb>} or \cppLstinline{CGAL::Triangulation_face_base_with_info_2<bp::object, Traits, Vb>}, respectively, where \cppLstinline{Vb} and \cppLstinline{Fb} are types that model the concepts above. The final vertex type is selected accordingly; it is explained in details in Section~\ref{sec:extenders:iitri} of the appendix. The final vertex type is conveniently defined in C++ as \cppLstinline{Dt::Vertex}, where \cppLstinline{Dt} is the triangulation instance. This type is exposed as a Python attribute with the same name under \pyLstinline{Triangulation_2}. The final face type is conveniently defined in C++ as \cppLstinline{Dt::Face}, where \cppLstinline{Dt} is the triangulation instance. This type is also exposed as a Python attribute with the same name under \pyLstinline{Triangulation_2}. \subsection{2D Alpha Shape Bindings} \label{ssec:modules:as2} The alpha shape (a.k.a.\ alpha complex) of a set of points is one of several notions of a shape formed by the set. Given a set of points sampled in a 2D body, an alpha shape is demarcated by a frontier, which is a linear approximation of the original boundary of the body. A two-dimensional alpha shape object maintains an underlying triangulation of a set of input points in the plane. There are two distinguished versions of alpha shapes as follows. Basic alpha shapes are based on the Delaunay triangulation and weighted alpha shapes are based on its generalization, the regular triangulation, where the euclidean distance is replaced by the power to weighted points. The package \cgalPackage{2D Alpha Shapes}{}~\cite{cgal:d-as2-21a} provides the class template \cppLstinline{Alpha_shape_2<Dt, ExactAlphaComparisonTag>}. In a 2D alpha shape object represented by an instance of this class template each $k$-simplex of the underlying triangulation is associated with an interval that specifies for which values of $\alpha$ the $k$-simplex belongs to the alpha shape. Table~\ref{tab:as2} lists the {\sc CMake}{} flags associated with the \cgalPackage{2D Alpha Shapes}{} module. \begin{table}[!htp] \caption{\cgalPackage{2D Alpha Shapes}{} module flags} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 1/.style={nodes={text width=16em}}, column 3/.style={nodes={text width=5.7em}}, column 4/.style={nodes={text width=21.6em}} ] { Name & Type & Default & Description\\ \myLstinline{AS2_EXACT_COMPARISON} & Boolean & \myLstinline{false} & Determines whether to apply exact comparisons\\ }; \end{tikzpicture} \label{tab:as2} \end{table} \subsection{3D Triangulation Bindings} \label{ssec:modules:tri3} A triangulation of a set of points ${\cal P}$ in \Rx{3}\xspace is a partition of the convex hull of ${\cal P}$ into tetrahedra whose vertices are the points of ${\cal P}$. Similar to the two-dimensional triangulation, together with the unbounded cell having the convex hull boundary as its frontier, the triangulation forms a partition of \Rx{3}\xspace. Any two cells (3-face) are either disjoint or share a common facet (2-face), edge (1-face) or vertex (0-face). The binding module \cgalPackage{3D Triangulations}{} consists of bindings of types provided by the {\sc Cgal}{} packages \cgalPackage{3D Triangulations}{} and \cgalPackage{3D Periodic Triangulations}{}. Table~\ref{tab:tri3} lists the {\sc CMake}{} flags associated with the \cgalPackage{3D Triangulations}{} module. \begin{table}[!htp] \caption{\cgalPackage{3D Triangulations}{} module flags.} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, row 5/.append style={nodes={minimum height=2.8em}} ] { Name & Type & Default & Description\\ \cmakeLstinline{TRI3_NAME} & String & \myLstinline{plain} & The 3D triangulation type\\ \cmakeLstinline{TRI3_CONCURRENCY_NAME} & String & \myLstinline{sequential} & The concurrency method\\ \cmakeLstinline{TRI3_LOCATION_POLICY_NAME} & String & \myLstinline{compact} & The location policy\\ \cmakeLstinline{TRI3_HIERARCHY} & Boolean & \myLstinline{false} & Determines whether to generate the binding for a hierarchy triangulation\\ }; \end{tikzpicture} \label{tab:tri3} \end{table} The \cgalPackage{3D Triangulations}{} package~\cite{cgal:pt-t3-21a} provides several class templates, instances of which can be used to represent a variety 3D triangulations. In particular, the package provides the following class templates: \begin{compactenum} \item \cppLstinline{Triangulation_3<Traits, Tds, Slds>}, \item \cppLstinline{Regular_triangulation_3<Traits, Tds, Slds>}, and \item \cppLstinline{Delaunay_triangulation_3<Traits, Tds, LocationPolicy, Slds>} \item \cppLstinline{Triangulation_hierarchy_3<Triangulation_3>} \end{compactenum} Instance of the \cppLstinline{Delaunay_triangulation_3<>} and \cppLstinline{Regular_triangulation_3<>} class templates can be used to represent Delaunay and regular triangulation, respectively. In a regular triangulation points have an associated weight, and some points can be hidden and do not result in vertices in the triangulation. \cppLstinline{Triangulation_hierarchy_3} enables fast point location queries. When instantiated its template parameter must be substituted with an instance of any other triangulation class template. The \cgalPackage{3D Periodic Triangulations}{} package~\cite{cgal:ct-pt3-21a} supports triangulations of sets of points in the three-dimensional flat torus~\cite{ct-cpt-09}. This package provides the class templates \begin{compactenum} \item \cppLstinline{Periodic_3_triangulation_3<Traits, Tds>}, \item \cppLstinline{Periodic_3_regular_triangulation_3<Traits, Tds>}, and \item \cppLstinline{Periodic_3_Delaunay_triangulation_3<Traits, Tds>} \item \cppLstinline{Periodic_3_triangulation_hierarchy_3<PeriodicTriangulation>} \end{compactenum} The {\sc CMake}{} flag \myLstinline{CGALPY_TRI3_NAME} specifies the particular types of triangulation, bindings for which should be generated; see Table~\ref{tab:tri3:names}. \begin{table}[!htp] \caption{3D triangulation name options} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=10em}}, column 2/.style={nodes={text width=39em}} ] { \myLstinline{TRI3_NAME} & Type\\ \myLstinline{plain} & \cppLstinline{Triangulation_3<Traits, Tds, Slds>}\\ \myLstinline{regular} & \cppLstinline{Regular_triangulation_3<Traits, Tds, Slds>}\\ \myLstinline{delaunay} & \cppLstinline{Delaunay_triangulation_3<Traits, Tds, LocationPolicy, Slds>}\\ \myLstinline{periodicPlain} & \cppLstinline{Periodic_3_triangulation_3<Traits, Tds>}\\ \myLstinline{periodicRegular} & \cppLstinline{Periodic_3_regular_triangulation_3<Traits, Tds>}\\ \myLstinline{periodicDelaunay} & \cppLstinline{Periodic_3_Delaunay_triangulation_3<Traits, Tds>}\\ }; \end{tikzpicture} \label{tab:tri3:names} \end{table} When any template above is instantiated the template parameter \cppLstinline{Traits} must be substituted with a model of a suitable geometric traits concept; this model is referred to as the geometric traits class; it provides the type of points to use as well as elementary operations on points of the indicated types. The type of traits used for the generated bindings is determined based on the selection of the triangulation type as explained below. It is conveniently defined in C++ as \cppLstinline{Dt::Geom_traits}, where \cppLstinline{Dt} is the triangulation instance. This type is exposed as a Python attribute with the same name under \pyLstinline{Triangulation_3} (which in turn is nested under the Python namespace \pyLstinline{Tri3}). Figure~\ref{fig:tri3:concept-hierarchy} depicts the 3D triangulation traits concept hierarchy. Any kernel instance is a model of any non-periodic traits concept; thus, when one of the templates \begin{compactenum} \item \cppLstinline{Triangulation_3<Traits, Tds>}, \item \cppLstinline{Regular_triangulation_3<Traits, Tds>}, abd \item \cppLstinline{Delaunay_triangulation_3<Traits, Tds>} \end{compactenum} is instantiated, the \cppLstinline{Traits} parameter is substituted with the \cppLstinline{Kernel} type (the selected kernel; see Section~\ref{ssec:modules:kernel}). When one of the templates \begin{compactenum} \item \cppLstinline{Periodic_3_triangulation_3<Traits, Tds>}, \item \cppLstinline{Periodic_3_regular_triangulation_3<Traits, Tds>}, or \item \cppLstinline{Periodic_3_Delaunay_triangulation_3<Traits, Tds>} \end{compactenum} is instantiated, the \cppLstinline{Traits} parameter is substituted with \cppLstinline{Periodic_3_triangulation_traits_3<Kernel>}, \cppLstinline{Periodic_3_regular_triangulation_traits_3<Kernel>}, or \cppLstinline{Periodic_3_Delaunay_triangulation_ traits_3<Kernel>}, respectively. Observe that when a Delaunay triangulation instance is used to define either a plain or a fixed alpha shape type (see Section~\ref{ssec:modules:as3}), the traits parameter must be substituted with a traits class that models either the \cppLstinline{AlphaShapeTraits_3} or the \cppLstinline{FixedAlphaShapeTraits_3} concept, respectively. Similarly, when a regular triangulation instance is used to define either a plain or a fixed alpha shape type (see Section~\ref{ssec:modules:as3}, the traits parameter must be substituted with a traits class that models either the \cppLstinline{WeightedAlphaShapeTraits_3} or the \cppLstinline{FixedWeightedAlphaShapeTraits_3} concept, respectively. Also in these cases the selected kernel serves as the traits. \begin{figure}[!htp] \def\name#1{\scriptsize\cppLstinline{#1}} \tikzset{% concept/.style={rectangle,rounded corners,align=center, draw,fill=white,blur shadow } } \forestset{ my tree style/.style={ for tree={concept, parent anchor=south, child anchor=north, edge={->,>=stealth,black,thick}, edge path= \noexpand\path [draw, \forestoption{edge}] (!u.parent anchor)--(.child anchor)\forestoption{edge label}; }, if n children=3 for children= if n=2{calign with current}{} } }{}, } } } \centering \begin{forest} my tree style [ \name{TriTr3} [ \name{RegularTriTr3},name=r [ \name{WeightedASTr3} ] [ \name{FixedWeightedASTr3} ] ] [ \name{Periodic_3TriTr3},name=p [ \name{Pr3RegularTriTr3},name=pr ] ] [ \name{DelaunayTriTr3},name=d [ \name{Pr3DelaunayTriTr3},name=pd [ \name{Pr3ASTr3} ] ] [ \name{ASTr3} ] [ \name{FixedASTr3} ] ] ] \draw[->,>=stealth] (r.parent anchor)--(pr.child anchor); \draw[->,>=stealth] (p.parent anchor)--(pd.child anchor); \end{forest} \caption{The 3D triangulation traits concept hierarchy. \cppLstinline{Triangulation}, \cppLstinline{AlphaShape}, \cppLstinline{Traits_3} and \cppLstinline{Periodic_3} are abbreviated as \cppLstinline{Tri}, \cppLstinline{AS}, \cppLstinline{Pr3}, and \cppLstinline{Tr3}, respectively.} \label{fig:tri3:concept-hierarchy} \end{figure} The {\sc CMake}{} Boolean flag \cmakeLstinline{CGALPY_TRI3_HIERARCHY} indicates whether the type of triangulation, bindings for which should be generated, is an instance of one of the triangulation hierarchy templates, namely, \begin{compactitem} \item \cppLstinline{Triangulation_hierarchy_3<Triangulation_2>} and \item \cppLstinline{Periodic_triangulation_hierarchy_3<PeriodicTriangulation_3>}. \end{compactitem} The template parameter in both cases is substituted with the triangulation selected via the {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI3_ NAME}, which also determines whether to use the non-periodic or periodic version above. The type that substitutes the \cppLstinline{Tds} parameter models the concept \cppLstinline{TriangulationDataStructure_3}. An object of this type stores the combinatorial structure of the triangulation; it is an instance of the class template \cppLstinline{Triangulation_data_structure_3<V, C, ConcurrencyTag>}. The types that substitute the \cppLstinline{V} and \cppLstinline{C} template parameters when the \cppLstinline{Triangulation_data_structure_3<V, C>} template is instantiated represent the type of the vertex and the type of the cell of the triangulation, respectively; they must model the \cppLstinline{TriangulationDS VertexBase_3} and \cppLstinline{TriangulationDSCellBase_3} concepts, respectively. If the binding is generated for a periodic triangulation, these parameters must be substituted with types that also model the concepts \cppLstinline{Periodic_3 TriangulationDSVertexBase_3} and \cppLstinline{Periodic_3TriangulationDSCellBase_3}, respectively. If the triangulation is used to define a plain alpha shape type, these parameters must be substituted with types that model the concepts \cppLstinline{AlphaShapeVertex_3} and \cppLstinline{AlphaShapeCell_3}, respectively; see Section~\ref{ssec:modules:as3}. If the triangulation is used to define a fixed alpha shape type, these parameters must be substituted with types that model the concepts \cppLstinline{FixedAlphaShapeVertex_3} and \cppLstinline{FixedAlphaShapeCell_3}, respectively. Finally, if the binding is generated for a hierarchy triangulation, e.g., an instance of the template parameter \cppLstinline{Triangulation_hierarchy_3<Triangulation_3>}, the \cppLstinline{V} template parameter must be substituted with a model of the concept \cppLstinline{Triangulation HierarchyVertexBase_3}. (Observe that there is no special requirements on the type that substitutes the \cppLstinline{C} parameter in this case.) Similar to the 2D arrangement and 2D triangulation data structures, it is possible to extend the vertex and cell types of the triangulation. This is governed by two {\sc CMake}{} Boolean flags as follows. If any one of the {\sc CMake}{} variables \cmakeLstinline{CGALPY_TRI3_VERTEX_WITH_INFO} or \cmakeLstinline{CGALPY_TRI3_CELL_WITH_INFO} is set to true, the corresponding template parameter, \cppLstinline{V} or \cppLstinline{C}, is substituted with instances of \cppLstinline{CGAL::Triangulation_vertex_base_ with_info_3<bp::object, Traits, Vb>} or \cppLstinline{CGAL::Triangulation_cell_base_with_info_3<bp::object, Traits, Cb>}, respectively, where \cppLstinline{Vb} and \cppLstinline{Cb} are types that model the concepts above. The final vertex type is selected accordingly; it is explained in details in Section~\ref{sec:extenders:iiitri} of the appendix. The final vertex type is conveniently defined in C++ as \cppLstinline{Dt::Vertex}, where \cppLstinline{Dt} is the triangulation instance. This type is exposed as a Python attribute with the same name under \pyLstinline{Triangulation_3}. The final face type is conveniently defined in C++ as \cppLstinline{Dt::Face}, where \cppLstinline{Dt} is the triangulation instance. This type is also exposed as a Python attribute with the same name under \pyLstinline{Triangulation_3}. The template parameter \cppLstinline{ConcurrencyTag} is substituted with either \cppLstinline{Sequential_tag} or \cppLstinline{Parallel_tag} when the template \cppLstinline{Triangulation_data_structure_3<V, C, ConcurrencyTag} is instantiated. It enables the use of a concurrent container to store vertices and cells. The {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI3_CONCURRENCY_NAME} determines the selection; see Table~\ref{tab:tri3:concurrency}. \begin{table}[!htp] \caption{3D triangulation concurrency options} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=18em}}, column 2/.style={nodes={text width=31em}} ] { \cmakeLstinline{TRI3_CONCURRENCY_NAME} & Type\\ \myLstinline{sequential} & \cppLstinline{Sequential_tag}\\ \myLstinline{parallel} & \cppLstinline{Parallel_tag}\\ }; \end{tikzpicture} \label{tab:tri3:concurrency} \end{table} The template parameter \cppLstinline{LocationPolicy} is substituted with either \cppLstinline{Fast_location} or \cppLstinline{Compact_location} when the template \cppLstinline{Delaunay_triangulation_3<Traits, Tds, LocationPolicy>} is instantiated. It enables a faster point location at the account of memory space. This is useful when performing point locations or random point insertions in large data sets. The {\sc CMake}{} flag \cmakeLstinline{CGALPY_TRI3_LOCATION_POLICY_NAME} determines the selection; see Table~\ref{tab:tri3:location}. \begin{table}[!htp] \caption{3D triangulation location policy options} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=18em}}, column 2/.style={nodes={text width=31em}} ] { \cmakeLstinline{TRI3_LOCATION_POLICY_NAME} & Type\\ \myLstinline{fast} & \cppLstinline{Fast_location}\\ \myLstinline{compact} & \cppLstinline{Compact_location}\\ }; \end{tikzpicture} \label{tab:tri3:location} \end{table} The code excerpt in the {\sc CMake}{} language shown in Listing~\ref{lst:cmake:tri2} sets the {\sc CMake}{} flags for our next example in Python shown in Listing~\ref{lst:py:tri3}. The example constructs a three-dimensional Delaunay triangulation from six points and verifies that the triangulation is valid. \begin{lstfloat} \defkd_tree.py{tri3_del_epic_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,basicstyle=\normalsize, label={lst:cmake:tri2}, caption={{\sc CMake}{} flag settings used to generate bindings for 3D triangulations.}] {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \defkd_tree.py{tri3_del.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, firstline=15, label={lst:py:tri3}, caption={Constructing a 3D~triangulations of six vertices.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \subsection{3D Alpha Shape Bindings} \label{ssec:modules:as3} Given a set of points sampled in a 3D body, an alpha shape (a.k.a.\ alpha complex) is demarcated by a frontier, which is a linear approximation of the original boundary of the body. Similar to the 2D alpha shape object, A 3D alpha shape object maintains an underlying 3D triangulation of a set of input points. Basic alpha shapes are based on the Delaunay triangulation and weighted alpha shapes are based on regular triangulation, where the euclidean distance is replaced by the power to weighted points. The package \cgalPackage{3D Alpha Shapes}{}~\cite{cgal:dy-as3-21a} provides the class templates \cppLstinline{Alpha_shape_3<Dt, ExactAlphaComparisonTag>} and \cppLstinline{Fixed_alpha_shape_3<Dt>}. Instances of both templates can be used to represent a large variety of alpha shapes for a given set of points. In a plain alpha shape each $k$-face of this triangulation is associated with an interval specifying for which values of $\alpha$ the face belongs to the alpha complex. In a fixed alpha shape each $k$-face is associated with a classification that specifies its status in the alpha complex, alpha being fixed. Table~\ref{tab:as3} lists the {\sc CMake}{} flags associated with the \cgalPackage{3D Alpha Shapes}{} module. \begin{table}[!htp] \caption{\cgalPackage{3D Alpha Shapes}{} module flags} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 1/.style={nodes={text width=16em}}, column 3/.style={nodes={text width=5.7em}}, column 4/.style={nodes={text width=21.6em}} ] { Name & Type & Default & Description\\ \myLstinline{AS3_NAME} & String & \myLstinline{plain} & The 3D Alpha shape type\\ \myLstinline{AS3_EXACT_COMPARISON} & Boolean & \myLstinline{false} & Determines whether to apply exact comparisons\\ }; \end{tikzpicture} \label{tab:as3} \end{table} The {\sc CMake}{} flag \myLstinline{AS3_NAME} specifies which alpha shape should be used for the generated bindings; see Table~\ref{tab:as3:types} \begin{table}[!htp] \caption{\cgalPackage{3D Alpha Shapes}{} types} \centering\begin{tikzpicture} \matrix (first) [tableName, column 1/.style={nodes={text width=12em}}, column 2/.style={nodes={text width=37em}} ] { \myLstinline{AS3_NAME} & Type\\ \myLstinline{plain} & \cppLstinline{Alpha_shape_3<Tri, Ec>}\\ \myLstinline{fixed} & \cppLstinline{Fixed_alpha_shape_3<Tri>}\\ }; \end{tikzpicture} \label{tab:as3:types} \end{table} The template parameter \cppLstinline{Dt} must be substituted with an instance of one of the following class templates that can be used to represent a triangulation: \begin{compactenum} \item \cppLstinline{Delaunay_triangulation_3}, \item \cppLstinline{Regular_triangulation_3}, \item \cppLstinline{Periodic_3_Delaunay_triangulation_3}, or \item \cppLstinline{Periodic_3_regular_triangulation_3}; \end{compactenum} see Section~\ref{ssec:modules:tri3}. Note that \cppLstinline{Dt::Geom_traits} must be model of a suitable alpha-shape traits concept, and \cppLstinline{Dt::Vertex} and \cppLstinline{Dt::Face} must be models suitable alpha-shape vertex and cell concepts, respectively; see Section~\ref{ssec:modules:tri3}. The following code excerpt in the {\sc CMake}{} language shown in Listing~\ref{lst:cmake:as3} sets the {\sc CMake}{} flags for our next Python example shown in Listing~\ref{lst:py:as3}. The examples constructs an alpha shape object. \begin{lstfloat} \defkd_tree.py{as3_del_compact_parallel_epic_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,basicstyle=\normalsize, label={lst:cmake:as3}, caption={{\sc CMake}{} flag settings used to generate bindings for 3D alpha shapes.}] {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \defkd_tree.py{as3_del_compact_epic.py}% \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, firstline=15, label={lst:py:as3}, caption={Constructing a 3D alpha shape object.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat} \subsection{Spatial Searching Bindings} \label{ssec:modules:ss} The \cgalPackage{dD Spatial Searching}{} package~\cite{cgal:tf-ssd-21a} implements exact and approximate distance browsing by providing implementations of algorithms supporting \begin{compactenum} \item both nearest and furthest neighbor searching, \item both exact and approximate searching, \item (approximate) range searching, \item (approximate) $k$-nearest and $k$-furthest neighbor searching, \item (approximate) incremental nearest and incremental furthest neighbor searching, and \item query items representing points and spatial objects. \end{compactenum} In these searching problems a set ${\cal P}$ of data points in $d$-dimensional space is given. The points in ${\cal P}$ are preprocessed into a tree data structure, so that given any query item $q$ the points of ${\cal P}$ can be browsed efficiently. The approximate \cgalPackage{dD Spatial Searching}{} package is designed for data sets that are small enough to store the search structure in main memory (in contrast to approaches from databases that assume that the data reside in secondary storage). \begin{table}[!htp] \caption{\cgalPackage{dD Spatial Searching}{} module flags} \centering\begin{tikzpicture} \matrix (first) [tableModuleFlags, column 3/.style={nodes={text width=3.5em}}, column 4/.style={nodes={text width=21.8em}} ] { Name & Type & Default & Description\\ \cmakeLstinline{SPATIAL_SEARCHING_DIMENSION} & Integer & \cppLstinline{2} & The dimension of spatial searching related classes\\ }; \end{tikzpicture} \label{tab:ss} \end{table} The code excerpt in the {\sc CMake}{} language shown in Listing~\ref{lst:cmake:ss}, sets the {\sc CMake}{} flags for our last example shown in Listing~\ref{lst:py:ss}. The example constructs a $k$D-tree{} of 2D points and applies various queries on the tree. Observe that the $k$D-tree{} dimension (and the dimension of related data structures) is set via the {\sc CMake}{} flag \myLstinline{CGALPY_SPATIAL_SEARCHING_DIMENSION} during compile time. The code in the listings assumes that the dimension is~2. In order to assert the dimension the bindings were compiled with (see Line~10 in the listing), we have introduced and exposed a free function called \myLstinline{get_spatial_searching_dimension()} that returns the dimension as an \pyLstinline{int}. \begin{lstfloat} \defkd_tree.py{ss_2_cdlg_release.cmake}% \lstinputlisting[style=cmakeFramedStyle,basicstyle=\normalsize, label={lst:cmake:ss}, caption={{\sc CMake}{} flag settings used to generate bindings for spatial searching types.}] {\baseDir\cmakeRelDirkd_tree.py} \end{lstfloat} \begin{lstfloat} \defkd_tree.py{kd_tree.py} \lstinputlisting[style=pythonFramedStyle,basicstyle=\normalsize, label={lst:py:ss}, firstline=16, lastline=69, caption={Applying various queries on a $k$D-tree of 2D points.}] {\baseDir\pythonRelDirkd_tree.py} \end{lstfloat}
{'timestamp': '2022-03-01T02:52:29', 'yymm': '2202', 'arxiv_id': '2202.13889', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13889'}
arxiv
\section{Introduction} Federated learning (FL) is a distributed learning paradigm whereby multiple devices coordinate to train a target global model, while avoiding the direct sharing of local data with the cloud \cite{park2019wireless, zhou2019edge, zhu2020toward}. Prior work on wireless FL mainly focuses on conventional \emph{frequentist} learning, which produces point estimates of model parameter vectors by minimizing empirical loss metrics \cite{sery2021over, yang2021revisiting, amiri2020machine, liu2020privacy, cao2020optimized,zhu2020one}. In many engineering applications characterized by the availability of limited data and by the need to quantify uncertainty, \emph{Bayesian} learning provides a more effective and principled framework to define the learning problem (see, e.g., \cite{khan2021bayesian}). Bayesian learning assigns a probability distribution to the model parameters, rather than collapsing any residual uncertainty in the model parameter space to a single point estimate. In this paper, we focus on the distributed implementation of Bayesian learning in wireless systems within a federated learning setting, with the main goal of leveraging the wireless channel as part of the ``compute continuum'' between devices and server \cite{alwasel2021iotsim} (see Fig \ref{fig: system model}). Scalable Bayesian learning solutions are either based on variational inference, whereby the distribution over the model parameters is optimized by minimizing a free energy metric \cite{jose2021free}; or on Monte Carlo (MC) sampling, whereby the distribution over the model parameters is represented by random samples \cite{angelino2016patterns}. It was recently pointed out in \cite{liu2021wireless} that MC solutions enable a novel interpretation of the wireless channel as part of the MC sampling process. In particular, reference \cite{liu2021wireless} proposed a Bayesian federated learning protocol based on Langevin MC (LMC), a noise-perturbed gradient-based MC strategy \cite{angelino2016patterns}, and \emph{analog} transmission. The paper demonstrated the role of the channel noise as a contributor to the LMC update, as well as a privacy mechanism (see also \cite{koda2020differentially,liu2021privacy}). In this paper, we devise an alternative strategy that implements LMC in a federated setting via \emph{digital} modulation under privacy constraints. \begin{figure*}[t] \centering \centerline{\includegraphics[scale=0.22]{system}} \vspace{-0.0cm} \caption{Differentially private quantized federated Bayesian learning system based on LMC.}\label{fig: system model} \end{figure*} Federated learning has been widely studied for implementation on wireless channels (see, e.g., \cite{gunduz2019machine}). Techniques that leverage the wireless channel for computation include over-the-air computation (AirComp), whereby superposition in non-orthogonal multiple access (NOMA) is used as a means to aggregate information from different sources \cite{nazer2007computation, cao2020optimized, liu2020aircomp}; channel noise for privacy, which enforces differential privacy (DP) guarantees via power control \cite{seif2020wireless,liu2021privacy}; and channel noise for sampling, which was introduced above \cite{liu2021wireless}. Also related to this work are DP mechanisms based on stochastic quantization \cite{gandikota2019vqsgd}. In this paper, inspired by \cite{liu2020privacy}, we study Bayesian federated learning protocols based on the digital transmission of gradients from edge devices to the edge server (see Fig. \ref{fig: system model}). Like \cite{liu2021wireless}, which considered analog transmission, we aim at leveraging channel noise for both channel-driven MC sampling and DP. The main contributions of this paper are as follows. \begin{itemize} \item[$\bullet$] \textbf{Quantized federated LMC (FLMC):} We introduce a quantized federated implementation of LMC based on stochastic quantization, binary transmission, and channel-driven sampling; \item[$\bullet$] \textbf{Power allocation policy with DP guarantees:} We analyze the DP guarantees of LMC, and we design an approach to determine power control parameter to meet the requirements of both MC sampling and DP; \item[$\bullet$] \textbf{Experiments:} We demonstrate an experimental comparison of digital and analog wireless FLMC implementations under DP constraints. \end{itemize} The remainder of this paper is organized as follows. Section \ref{sec: system model} formulates the system models and definitions. The privacy anaysis and power control design are presented in Section \ref{sec: power control}. Section \ref{sec: experiments} describes numerical results. \section{System Model}\label{sec: system model} As shown in Fig. \ref{fig: system model}, we consider a wireless federated edge learning system comprising an edge server and $K$ edge devices. The devices are connected to the server via a shared wireless channel. Each device $k$ has its own local dataset $\mathcal{D}_k$, which includes $N_k$ data samples $\mathcal{D}_k=\{ {\mathbf{d}}_{k,n} \}_{n=1}^{N_k}$. The global data set is denoted as $\mathcal{D}=\{\mathcal{D}_k\}_{k=1}^K$. The devices communicate to the server via a NOMA digital channel with BPSK modulation as in \cite{zhu2020one}. Unlike \cite{zhu2020one}, which focuses on conventional frequentist learning, here the goal is to carry out Bayesian learning by approximating the global posterior distribution $p({{\mathbf{m}} \vartheta} | \mathcal{D} )$ at the server. Furthermore, as in \cite{liu2020privacy}, which considers analog transmission, we impose privacy constraints via DP. \subsection{Federated Langevin Monte Carlo} The machine learning model adopted by the system is defined by a likelihood function $p( {\mathbf{d}} |{{\mathbf{m}} \vartheta} )$, as well as by a prior distribution $p({\mathbf{m}} \vartheta)$. Accordingly, the likelihood of the data at device $k$ is obtained by assuming identical and independent (i.i.d.) observations as \begin{align} p(\mathcal{D}_k|{{\mathbf{m}} \vartheta}) = \prod_{n=1}^{N_k} p({\mathbf{d}}_{n,k} |{{\mathbf{m}} \vartheta}). \end{align} The target global posterior is \begin{align} p({{\mathbf{m}} \vartheta}|\mathcal{D}) \propto p({{\mathbf{m}} \vartheta}) \prod_{k=1}^K p(\mathcal{D}_k | {{\mathbf{m}} \vartheta}), \label{eq: posterior} \end{align} which can be expressed in terms of the product $ p({{\mathbf{m}} \vartheta}|\mathcal{D}) \propto \prod_{k=1}^K \tilde{p}({{\mathbf{m}} \vartheta}|\mathcal{D}_k)$ of the local sub-posteriors at each device $k$ \begin{align} &\tilde{p}({{\mathbf{m}} \vartheta}|\mathcal{D}_k) \propto p({{\mathbf{m}} \vartheta})^{1/K} p(\mathcal{D}_k | {{\mathbf{m}} \vartheta}). \label{eq: local sub-posterior} \end{align} We introduce the local cost function \begin{align}\label{eq: local func} f_k({\mathbf{m}} \vartheta)=-\log p(\mathcal{D}_k|{{\mathbf{m}} \vartheta}) -\frac{1}{K}\log p({\mathbf{m}} \vartheta), \end{align} which accounts for prior and likelihood at device $k$, as well as the global cost function \begin{align}\label{eq: gb func} f({\mathbf{m}} \vartheta)= \sum_{k=1}^K f_k({\mathbf{m}} \vartheta). \end{align} LMC is a gradient-based MCMC sampling scheme. As such, it aims at producing samples from the global posterior $p({{\mathbf{m}} \vartheta}|\mathcal{D})$ in \eqref{eq: posterior} by leveraging information about the gradient of the local cost functions \eqref{eq: local func}. At each $s$-th iteration, LMC produces the next sample $\vartheta^{[s+1]}$ as \begin{align} \label{eq: LMC} \text{(LMC)} \quad {{\mathbf{m}} \vartheta}^{[s+1]}={{\mathbf{m}} \vartheta}^{[s]} -\eta \sum_{k=1}^K \nabla f_k({{\mathbf{m}} \vartheta}^{[s]}) + \sqrt{2\eta} {{\mathbf{m}} \xi}^{[s+1]}, \end{align} where $\eta$ is the step size, and $\{{{\mathbf{m}} \xi}^{[s]}\}$ is a sequence of i.i.d. random vectors following the Gaussian distribution $\mathcal{N}(0, {\mathbf{I}}_m)$, which are independent of the initialization ${{\mathbf{m}} \vartheta}^{[0]}\in \mathbb{R}^m$. To implement LMC in the described federated setting, at each $s$-th communication round, the edge server broadcasts the current sample ${{\mathbf{m}} \vartheta}^{[s]}$ to all edge devices via the downlink channel. We assume ideal downlink communication. By using the received vector ${{\mathbf{m}} \vartheta}^{[s]}$ and the local dataset $\mathcal{D}_k$, each device computes the gradient of the local cost function \eqref{eq: local func} as \begin{align}\label{eq: local gradient} {\mathbf{g}}_k^{[s]} = -\sum_{n =1}^{N_k}\nabla \log p({\mathbf{d}}_n|{{\mathbf{m}} \vartheta}^{[s]}) -\frac{1}{K} \nabla\log p({\mathbf{m}} \vartheta^{[s]}). \end{align} While \cite{liu2020privacy} explored the use of analog communication to transmit the local gradients in \eqref{eq: local gradient}, in this work we assume that the devices apply entrywise binary quantization in order to enable BPSK-based transmission. The edge server aggregates the received signals to obtain an approximation of the update term $-\eta \nabla f({{\mathbf{m}} \vartheta}^{[s]}) + \sqrt{2\eta} {{\mathbf{m}} \xi}^{[s+1]}$ in \eqref{eq: LMC}. As we will see, and as first proposed in \cite{liu2020privacy}, channel noise can be leveraged to contribute to the additive random term ${{\mathbf{m}} \xi}^{[s+1]}$ in the LMC update \eqref{eq: LMC}, as well as a DP mechanism. After $S$ communication rounds, the server obtains a sequence of samples of model parameter vectors $\{{{\mathbf{m}} \vartheta}^{[s]}\}_{s=1}^{S}$. \subsection{Communication Model}\label{sec: comm model} The devices communicate via NOMA on the uplink to the edge server. At any $s$-th communication round, each entry ${\mathrm{g}}_{k,i}^{[s]}$ of the gradient vector ${{\mathbf{g}}}_k^{[s]}=[{\mathrm{g}}_{k,1}^{[s]},\cdots, {\mathrm{g}}_{k,m}^{[s]}]^{\sf T}$ is quantized via one-bit stochastic quantization \cite{jin2020stochastic} \begin{align} \tilde{\mathrm{g}}_{k,i}^{[s]}=\begin{cases} 1& \text{with probability $\Phi(\mathrm{g}_{k,i}^{[s]})$}, \\ -1& \text{with probability $1-\Phi(\mathrm{g}_{k,i}^{[s]})$},\label{eq: quantizer} \end{cases} \end{align} where function $\Phi(\cdot)$ returns a probability that increases with the input argument. An example is given by the sigmoid function $\Phi(x)=\sigma(x)=\big(1+\exp(-ax)\big)^{-1}$ for some fixed parameter $a>0$. Each of the quantized gradient parameters $\tilde{\mathrm{g}}_{k,i}^{[s]}$ is modulated into one BPSK symbol. As a result, a block of $m$ BPSK symbols is produced to communicate the quantized local gradient vector $\tilde{{\mathbf{g}}}_k^{[s]}$ in a communication round. Accordingly, at the $s$-th communication round, the received signal at the server is given by the superposition \begin{align} \label{eq: general received signal} {\mathbf{y}}^{[s]}= \sum_{k=1}^K{\mathbf{H}}_{k}^{[s]}{\bf P}_k^{[s]} \tilde{{\mathbf{g}}}_k^{[s]} +{\mathbf{z}}^{[s]}, \end{align} where ${\mathbf{H}}_k^{[s]}={\operatorname{diag}}[h_{k,1}^{[s]},\cdots, h_{k,m}^{[s]}]$ and ${\bf P}_k^{[s]}={\operatorname{diag}}[P_{k,1}^{[s]},\cdots, P_{k,m}^{[s]}]$ are diagonal matrices collecting respectively the channel gains and power control parameters for $m$ consecutive symbols in a block; while ${\mathbf{z}}^{[s]}$ is the channel noise, which is i.i.d. according to distribution $\mathcal{N}(0,{N_0}{\mathbf{I}})$. We assume perfect channel state information (CSI) at all nodes, so that, as we will see, each device can compensate for the phase and amplitude of its own channel. In the following sections, we will design the power allocation parameters $\{\{P_{k,i}^{[s]}\}_{i=1}^m\}_{k=1}^K$ for each communication round. The transmission of each device is subject to the average per block transmission power constraint: \begin{equation}\label{eq: power constraint} {(\text {Power constraint})} \quad \frac{1}{m}\sum_{i=1}^m \big| P_{k,i}^{[s]} \tilde{\mathrm{g}}_{k,i}^{[s]}\big|^2 \leq P_0, \forall k, s. \end{equation} We define the maximum signal to noise ratio (SNR) as $\mathsf{SNR}_{\sf max}={P_0}/{N_0}$, which is obtained when a device transmits at full power. \subsection{Differential Privacy} We assume an ``honest-but-curious" edge server that may attempt to infer information about local data sets from the received signals ${\mathbf{y}}^{[s]}$. The privacy constraint is described by the standard $(\epsilon,\delta)$-DP constraint, with some $\epsilon>0$ and $\delta\!\in\![0,1)$. DP hinges on the divergence between the two distributions $P({\mathbf{y}}^{[s]} |\mathcal{D}')$ and $P ( {\mathbf{y}}^{[s]} |\mathcal{D}'') $ of the signal received when the data sets $\mathcal{D}'$ and $\mathcal{D}''$ differ a single data point, i.e., $\|\mathcal{D}'-\mathcal{D}'' \|_1=1$. Formally, we have $(\epsilon,\delta)$-DP if the inequality \begin{equation}\label{eq: def dp} \max \limits_{\mathcal{D}',\mathcal{D}'':\|\mathcal{D}'-\mathcal{D}'' \|_1=1}\big\{\Pr(|\mathcal{L}_{\mathcal{D}',\mathcal{D}''}({\mathbf{y}}^{[s]})|\leq \epsilon)\big\}\geq 1-\delta \end{equation} is satisfied, where the DP loss $\mathcal{L}_{\mathcal{D}',\mathcal{D}'' }({\mathbf{y}}^{[s]})$ is \begin{equation}\label{def: privacy loss} \mathcal{L}_{\mathcal{D}',\mathcal{D}''}({\mathbf{y}}^{[s]} )=\ln \frac{P({\mathbf{y}}^{[s]} |\mathcal{D}')}{P ( {\mathbf{y}}^{[s]} |\mathcal{D}'')}. \end{equation} The probability in \eqref{eq: def dp} is taken with respect to the distribution $P({\mathbf{y}}^{[s]} |\mathcal{D}')$. We note that the DP constraint \eqref{eq: def dp} is applied at each communication round, and that the overall privacy guarantees across iterations can be obtained by using standard composition theorems \cite[Sec. 3.5]{dwork2014algorithmic}. To ensure DP requirement as \cite{chen2020understanding,wang2015privacy}, we make the following assumption on the gradients. \begin{assumption}[Bounded Gradients]\label{assumption: BLL}\emph{Each element of the local gradients is bounded by some constant $\ell>0$ as \begin{align}\label{eq: BV} \big| \mathrm{g}_{k,i}^{[s]} \big| \leq \ell ,\quad \text{for all } k, s, i. \end{align} } \end{assumption} In practice, the condition \eqref{eq: BV} can be met by clipping each entry of the gradient as $ \min \{1, {\ell}/{| \mathrm{g}_{k,i}^{[s]} |}\} \mathrm{g}_{k,i}^{[s]}$ before quantization \cite{chen2020understanding}. \section{Power Control for Quantized Federated Langevin Monte Carlo}\label{sec: power control} In this section, we first present the transmitter and receiver designs for the proposed quantized federated Langevin Monte Carlo (FLMC), and then analyze its DP properties. Finally, we address the design of power control parameters in \eqref{eq: general received signal}. \subsection{Signal Design} As described in Sec. \ref{sec: comm model}, each device applies stochastic quantization as in \eqref{eq: quantizer}. Followed by BPSK transmission under the assumption of perfect CSI, we consider channel inversion, whereby the power control matrix in \eqref{eq: general received signal} is selected as ${\mathbf{P}}_k^{[s]}={\mathbf{A}}^{[s]} ({\mathbf{H}}_k^{[s]})^{-1}$. The diagonal matrix ${\mathbf{A}}^{[s]}={\operatorname{diag}}[A_1^{[s]},\cdots, A_m^{[s]}]$ is to be designed with the goal of ensuring that the server can approximate the LMC update \eqref{eq: LMC}, while also guaranteeing the power constraint \eqref{eq: power constraint} and the DP constraint \eqref{eq: def dp}. The server normalizes the received signal as $({\mathbf{A}}^{[s]})^{-1}{\mathbf{y}}^{[s]}$ to obtain an estimate of the global gradient. Accordingly, the server approximates the LMC update \eqref{eq: LMC} as \begin{align} \label{eq: oma update} {{\mathbf{m}} \vartheta}^{[s+1]}= {{\mathbf{m}} \vartheta}^{[s]}- \eta \left[ \sum_{k=1}^K \tilde{{\mathbf{g}}}_k^{[s]}+ \big({\mathbf{A}}^{[s]}\big)^{-1} {\mathbf{z}}^{[s]} \right]. \end{align} \subsection{Privacy Analysis} We now consider the DP constraint \eqref{eq: def dp} for any device $k$. To this end, we fix the quantized gradients $\{\tilde{{\mathbf{g}}}_j\}_{j \neq k}$ of the other devices, and consider neighboring data sets $\mathcal{D}_k'$ and $\mathcal{D}_k''$ for device $k$ that differ only by one sample, i.e., $\|\mathcal{D}_k'-\mathcal{D}_k''\|_1=1$. As the DP constraint \eqref{eq: def dp} is applied to every iteration, we omit the index of the communication round $s$ for ease of notation. Then, the privacy loss \eqref{def: privacy loss} for device $k$ can be written as \begin{align} &\mathcal{L}_{\mathcal{D}',\mathcal{D}''}( {\mathbf{y}} ) = \ln\frac{\prod_{i=1}^m P(A_i \tilde{\mathrm{g}}'_{k,i} +A_i \sum_{q\neq k}\tilde{\mathrm{g}}_{q,i} +z_i \big|\{\tilde{\mathrm{g}}_{q,i} \}_{q\neq k}, \mathcal{D}_k' ) }{\prod_{i=1}^m P(A_i \tilde{\mathrm{g}}''_{k,i} +A_i \sum_{q\neq k}\tilde{\mathrm{g}}_{q,i} +z_i \big|\{\tilde{\mathrm{g}}_{q,i} \}_{q\neq k}, \mathcal{D}_k'') } \nonumber \\ &=\sum_{i=1}^m\ln\frac{\left[ \Phi(\mathrm{g}_{k,i}') \exp\left( \frac{2 (z_i-A_i \sum_{q\neq k } \tilde{\mathrm{g}}_{q,i})}{N_0/A_i}\right)+\left(1-\Phi(\mathrm{g}_{k,i}')\right)\right]}{\left[\Phi(\mathrm{g}_{k,i}'')\exp\left( \frac{2 (z_i-A_i \sum_{q\neq k } \tilde{\mathrm{g}}_{q,i})}{N_0/A_i}\right)+\left(1-\Phi(\mathrm{g}_{k,i}'')\right)\right]},\label{eq: digital privacy format} \end{align} where, with some abuse of notation, $P(X|Y)$ represents the distribution of random variable $X$ evaluated at $X$ when conditioned on the value $Y$ of random variable $Y$; the last step uses the fact that the distributions in \eqref{eq: digital privacy format} are mixture of Gaussians; and we have $z_i\sim\mathcal{N}(0,N_0)$. To attain the maximum DP loss in \eqref{eq: digital privacy format}, we consider the worst-case choice of data sets $\mathcal{D}'$ and $\mathcal{D}''$. To this end, without loss of generality, we set $\Phi(\mathrm{g}_{k,i}')=\Phi(\ell)$ and $\Phi(\mathrm{g}_{k,i}'')=\Phi(-\ell)$ by Assumption~\ref{assumption: BLL}. Furthermore, the value of the sum $\sum_{j\neq k}\tilde{\mathrm{g}}_{q,i}$ is within the range of $[-(K-1),(K-1)]$, and hence have the following inequality \begin{align} &|\mathcal{L}_{\mathcal{D}',\mathcal{D}''}({\mathbf{y}})|\nonumber \\ \leq &\max\Bigg\{ \Bigg|\sum_{i=1}^m\ln\frac{\left[ \Phi(\ell) \exp\left( \frac{2 (z_i+A_i (K-1))}{N_0/A_i}\right)+\left(1-\Phi(\ell)\right)\right]}{\left[\Phi(-\ell)\exp\left( \frac{2 (z_i+A_i (K-1))}{N_0/A_i}\right)+\left(1-\Phi(-\ell)\right)\right]}\Bigg|, \nonumber\\ & \Bigg| \sum_{i=1}^m\ln\frac{\left[ \Phi(\ell) \exp\left( \frac{2 (z_i-A_i (K-1))}{N_0/A_i}\right)+\left(1-\Phi(\ell)\right)\right]}{\left[\Phi(-\ell)\exp\left( \frac{2 (z_i-A_i (K-1))}{N_0/A_i}\right)+\left(1-\Phi(-\ell)\right)\right]} \Bigg| \Bigg\} \nonumber \\ &\triangleq \mathcal{L}^*({\mathbf{z}}), \label{eq: worst case privacy loss} \end{align} where ${\mathbf{z}} \sim \mathcal{N}(0,{\mathbf{I}}_m)$. We can now use \eqref{eq: worst case privacy loss} to evaluate numerically a bound on left-hand side of \eqref{eq: def dp} as $\Pr(|\mathcal{L}^*({\mathbf{z}})|\leq\epsilon)\geq1-\delta$ with ${\mathbf{z}} \sim \mathcal{N}(0,{\mathbf{I}}_m)$. To compare with analog FLMC in \cite{liu2020privacy}, we reproduce the privacy loss in \cite{liu2020privacy} as \begin{align} \mathcal{L}_{\mathcal{D}',\mathcal{D}''}({\mathbf{y}})=\sum_{i=1}^m\frac{2z_iA_i\Delta_{k,i}+(A_i\Delta_{k,i})^2}{2N_0}, \label{eq: analog dp constraint} \end{align} where $z_i \sim\mathcal{N}(0,N_0)$, and $\Delta_{k,i}=|\mathrm{g}'_{k,i}-\mathrm{g}'_{k,i}|$, and we have $\Delta_{k,i}\leq 2\ell$. To gain some insight about the comparison between \eqref{eq: worst case privacy loss} and \eqref{eq: analog dp constraint}, consider the high-SNR regime in which the power of channel noise $N_0$ approaches $0$. In this case, the privacy loss \eqref{eq: analog dp constraint} in the analog scheme goes to infinity, and hence no $(\epsilon,\delta)$-DP level with $\delta<1$ is possible. This is in sharp contrast with the digital scheme, for which the privacy loss \eqref{eq: worst case privacy loss} is upper bounded by $m \ln \Phi(\ell) - m \ln \Phi(-\ell)$. This discussion illustrates the potential advantages of the digital scheme in the presence of privacy constraints in the high-SNR regime. \subsection{Power Control} The design of power control parameters in the power gain matrix ${\mathbf{A}}^{[s]}$ must comply with the power constraints, the LMC noise requirements, and the DP constraints. For the power constraint \eqref{eq: power constraint}, plugging in the choice ${\mathbf{P}}_k^{[s]}={\mathbf{A}}^{[s]} ({\mathbf{H}}_k^{[s]})^{-1}$ yields the inequalities \begin{align} \frac{1}{m}\sum_{i=1}^m \left(\frac{ A_i^{[s]}}{ h_{k,i}^{[s]}} \right)^2 \leq {P_0}, \ \forall k, s.\label{eq: numerical power constraint} \end{align} Furthermore, in order to guarantee that the noise powers $N_0\eta^2 (A_i^{[s]})^{-2}$ in the update \eqref{eq: oma update} are no smaller than the power $2\eta$ required by the LMC update \eqref{eq: LMC} we impose the LMC noise requirement (see also \cite{liu2021wireless}) \begin{align}\label{eq: numerical LMC noise requirement} A_i^{[s]} \leq \sqrt{\frac{\eta N_0}{2}}, \ \forall i, s. \end{align} Finally, to impose the DP constraint, given the desired level of privacy loss $\epsilon$, we numerically estimate the probability $\delta$ in \eqref{eq: def dp} as a function of power gain parameters $A_i^{[s]}$ by drawing samples from the noise ${\mathbf{z}}^{[s]} \sim \mathcal{N} (0, N_0 {\mathbf{I}})$. \section{Numerical Results}\label{sec: experiments} In this section, we evaluate the performance of the proposed quantized FLMC, and compare it with the analog transmission scheme introduced in \cite{liu2021wireless}. Throughout this section, we assume the channel coefficients to be constant within a communication block, and homogeneous across the devices, i.e., $h_{k,i}^{[s]}=h^{[s]}$ for all devices $k=1,\cdots, K$ and all elements $i=1,\cdots, m$. Under this assumption, the power gains for quantized FLMC are obtained via a numerical search to maximize the value of $A_i^{[s]}$ under the three constraints reviewed in the previous sections. In a similar manner, for {\bf analog FLMC}, we have \cite{liu2020privacy} \begin{align} A_i^{[s]} = \min \left\{ \frac{|h^{[s]}|\sqrt{P_0}}{\ell}, \sqrt{\frac{\eta N_0}{2}}, \sqrt{\frac{N_0\mathcal{T}^{-1}(1-\delta)}{2m\ell^2}}\right\}, \ \forall k,\ s, \label{eq: analog constraints} \end{align} where the last term is the inverse function of $\mathcal{T}(x)$ defined by the error function ${\displaystyle \operatorname {erf} (x)={\frac {2}{\sqrt {\pi }}}\int _{0}^{x}e^{-t^{2}}\,dt}$ as \begin{align} \mathcal{T}(x)={\rm erf}\left(\frac{\epsilon-x}{2\sqrt{x}}\right)-{\rm erf}\left(\frac{-\epsilon-x}{2\sqrt{x}}\right), \end{align} which is obtained by plugging \eqref{eq: analog dp constraint} into \eqref{eq: def dp}, and leveraging the tail probability of Gaussian distribution. We also consider benchmark schemes without DP constraint. As for the learning model, as in \cite{liu2021wireless}, we consider a Gaussian linear regression with likelihood \begin{align}\label{eq: gl model} p(v_n|{{\mathbf{m}} \vartheta}, {\mathbf{u}}_n) = \frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2} (v_n-{{\mathbf{m}} \vartheta}^{\sf T}{\mathbf{u}}_n)^2}, \end{align} and the prior $p({{\mathbf{m}} \vartheta})$ is assumed to follow Gaussian distribution $\mathcal{N}(0, {\mathbf{I}}_m)$. Therefore, the posterior $p({{\mathbf{m}} \vartheta}|\mathcal{D})$ is the Gaussian $\mathcal{N}\big(({\mathbf{U}}\bU^{\sf T}+{\mathbf{I}})^{-1}{\mathbf{U}}{\mathbf{v}},({\mathbf{U}}\bU^{\sf T}+{\mathbf{I}})^{-1}\big)$, where ${\mathbf{U}}=[{\mathbf{u}}_1,\cdots,{\mathbf{u}}_N]$ is the data matrix and ${\mathbf{v}}=[v_1, \cdots, v_N]^{\sf T}$ is the label vector. We use synthetic dataset $\{{\mathbf{d}}_n=(\mathbf{u}_n,v_n)\}_{n=1}^{N}$ with $N=1200$ following the learning model in \eqref{eq: gl model}, with input $\mathbf{u}_n$ drawn i.i.d from $\mathcal{N}(0,\mathbf{I}_m)$ where $m=5$. The ground-truth model parameter is ${\mathbf{m}}\vartheta^*=[0.418, -0.289, 0.3982, 0.8231, 0.5251]^{\sf T}$. Unless stated otherwise, the data set is evenly distributed to $K=20$ devices; the constant channel $h^{[s]}$ is set to $0.04$ for all communication rounds; the power of channel noise is set to $N_0=1$; the bound of gradient element is set to $\ell=30$; learning rate is set to $\eta=1.28\times 10^{-4}$ for analog FLMC and $\eta=8.28 \times 10^{-3}$ for digital FLMC, which are tuned by using the smoothness and strongly convexity parameters (see \cite{liu2021wireless}). We consider a sigmoid function for quantization probability in \eqref{eq: quantizer} as $\Phi(x)=[1+\exp(- ax)]^{-1}$, and set $a=0.05$ by default. The total number of communication rounds is chosen as $S=300$, which are comprised of $S_b=200$ samples for the burn-in period, and the following $S_u=S-S_b=100$ samples for evaluation. The quality of the samples is measured by mean squared error (MSE) \begin{align} \text{MSE}=\frac{1}{S_u}\sum_{s=S_b+1}^{S_b+S_u}\|{\mathbf{m}} \vartheta^{[s]}-{\mathbf{m}} \mu\|^2, \label{eq:error} \end{align} where $\boldsymbol{\mu}$ is the mean of the ground-truth posterior distribution. All the results are averaged over 1000 experiments. We first investigate the impact of SNR in Fig. \ref{fig: snr_impact} on the performance of digital and analog FLMC schemes. In this experiment, we set the DP level as $\epsilon=5$ and $\delta=0.01$. Confirming the discussion in the previous section, in the high-SNR regime, digital FLMC is seen to outperform analog FLMC, since the latter one must back off the transmitted power in order to meet the DP constraint. In contrast, SNR lower than $17.5$ dB, analog FLMC is preferable. \begin{figure}[t] \centering \centerline{\includegraphics[scale=0.58]{SNR}} \vspace{-0.2cm} \caption{MSE as a function of SNR ($\epsilon=5, \delta=0.01$).}\label{fig: snr_impact} \end{figure} We now further investigate the impact of the privacy level on the digital and analog FLMC schemes in Fig. \ref{fig: epsilon_impact}. In this experiment, we set $\mathsf{SNR}_{\sf max}=25$ dB. The error of all schemes is seen to decrease by relaxing the DP constraint, until $\epsilon=7.5$ for the digital scheme and $\epsilon=15$ for the analog scheme. Relaxing the DP constraint cannot reduce the error, as the performance becomes limited by the transmitted power constraint or by LMC noise requirement. The digital FLMC scheme outperforms analog FLMC under a stricter DP requirement, i.e., when $\epsilon\leq 7.5$. This provides further validation of the advantage of the digital scheme when the SNR is large enough. \begin{figure}[t] \centering \centerline{\includegraphics[scale=0.58]{epsilon}} \vspace{-0.2cm} \caption{MSE as a function of privacy level $\epsilon$ ($\mathsf{SNR}_{\sf max}=25$ dB, $\delta=0.01$).}\label{fig: epsilon_impact} \vspace{-0.5cm} \end{figure} Finally, in Fig. \ref{fig: bandwidth_impact}, we study the impact of varying the parameter $a$ of the quantization probability function $\Phi(x)=[1+\exp(- ax)]^{-1}$. Note that a small $a$ implies a more noisy quantizer. In this experiment, we also set $\mathsf{SNR}_{\sf max}=25$ dB. Under strict DP requirement $\epsilon<2$, the quantizer with the small value $a=0.01$ outperforms other choices, since the higher level of randomness is applied to meet the DP constraint. Conversely, by relaxing the DP requirement, quantizer with larger value of $a$ become advantageous. \vspace{-0.2cm} \begin{figure}[t] \centering \centerline{\includegraphics[scale=0.58]{bandwidth}} \vspace{-0.2cm} \caption{MSE as a function of privacy level $\epsilon$ for different parameter of the stochastic binary quantization $a$ ($\mathsf{SNR}_{\sf max}=25$ dB, $\delta=0.01$).}\label{fig: bandwidth_impact} \end{figure} \bibliographystyle{ieeetr}
{'timestamp': '2022-03-01T02:55:50', 'yymm': '2202', 'arxiv_id': '2202.13932', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13932'}
arxiv
\section{Introduction} After receiving paper reviews, authors may optionally submit a rebuttal to address the reviewers' comments, which will be limited to a {\bf one page} PDF file. Please follow the steps and style guidelines outlined below for submitting your author response. The author rebuttal is optional and, following similar guidelines to previous CVPR conferences, is meant to provide you with an opportunity to rebut factual errors or to supply additional information requested by the reviewers. It is NOT intended to add new contributions (theorems, algorithms, experiments) that were absent in the original submission and NOT specifically requested by the reviewers. You may optionally add a figure, graph, or proof to your rebuttal to better illustrate your answer to the reviewers' comments. Per a passed 2018 PAMI-TC motion, reviewers should refrain from requesting significant additional experiments for the rebuttal or penalize for lack of additional experiments. Authors should refrain from including new experimental results in the rebuttal, especially when not specifically requested to do so by the reviewers. Authors may include figures with illustrations or comparison tables of results reported in the submission/supplemental material or in other papers. Just like the original submission, the rebuttal must maintain anonymity and cannot include external links that reveal the author identity or circumvent the length restriction. The rebuttal must comply with this template (the use of sections is not required, though it is recommended to structure the rebuttal for ease of reading). \subsection{Response length} Author responses must be no longer than 1 page in length including any references and figures. Overlength responses will simply not be reviewed. This includes responses where the margins and formatting are deemed to have been significantly altered from those laid down by this style guide. Note that this \LaTeX\ guide already sets figure captions and references in a smaller font. \section{Formatting your Response} {\bf Make sure to update the paper title and paper ID in the appropriate place in the tex file.} All text must be in a two-column format. The total allowable size of the text area is $6\frac78$ inches (17.46 cm) wide by $8\frac78$ inches (22.54 cm) high. Columns are to be $3\frac14$ inches (8.25 cm) wide, with a $\frac{5}{16}$ inch (0.8 cm) space between them. The top margin should begin 1 inch (2.54 cm) from the top edge of the page. The bottom margin should be $1\frac{1}{8}$ inches (2.86 cm) from the bottom edge of the page for $8.5 \times 11$-inch paper; for A4 paper, approximately $1\frac{5}{8}$ inches (4.13 cm) from the bottom edge of the page. Please number any displayed equations. It is important for readers to be able to refer to any particular equation. Wherever Times is specified, Times Roman may also be used. Main text should be in 10-point Times, single-spaced. Section headings should be in 10 or 12 point Times. All paragraphs should be indented 1 pica (approx.~$\frac{1}{6}$ inch or 0.422 cm). Figure and table captions should be 9-point Roman type as in \cref{fig:onecol}. List and number all bibliographical references in 9-point Times, single-spaced, at the end of your response. When referenced in the text, enclose the citation number in square brackets, for example~\cite{Alpher05}. Where appropriate, include the name(s) of editors of referenced books. \begin{figure}[t] \centering \fbox{\rule{0pt}{0.5in} \rule{0.9\linewidth}{0pt}} \caption{Example of caption. It is set in Roman so that mathematics (always set in Roman: $B \sin A = A \sin B$) may be included without an ugly clash.} \label{fig:onecol} \end{figure} To avoid ambiguities, it is best if the numbering for equations, figures, tables, and references in the author response does not overlap with that in the main paper (the reviewer may wonder if you talk about \cref{fig:onecol} in the author response or in the paper). See \LaTeX\ template for a workaround. \subsection{Illustrations, graphs, and photographs} All graphics should be centered. Please ensure that any point you wish to make is resolvable in a printed copy of the response. Resize fonts in figures to match the font in the body text, and choose line widths which render effectively in print. Readers (and reviewers), even of an electronic copy, may choose to print your response in order to read it. You cannot insist that they do otherwise, and therefore must not assume that they can zoom in to see tiny details on a graphic. When placing figures in \LaTeX, it is almost always best to use \verb+\includegraphics+, and to specify the figure width as a multiple of the line width as in the example below {\small\begin{verbatim} \usepackage{graphicx} ... \includegraphics[width=0.8\linewidth] {myfile.pdf} \end{verbatim} } {\small \bibliographystyle{ieee_fullname} \section{Method} \label{sec:approach} \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{Figs/bar_trajectory_cropped.pdf} \caption{\textbf{Barbell trajectory.} \textcolor{red}{Red bounding boxes} (bboxes) - barbell object detected; \textcolor{red}{Red dots}: the center of bboxes; \textcolor{Cyan}{Blue} curve: the parabolic trajectory of the barbell traced out.} \label{fig:barbell_trajectory} \end{figure} % In Secs.~\ref{sec:approach_cvcspc}-\ref{sec:approach_pad}, we present our self-supervised approaches. Subsequently, an error detection network is trained to map these self-supervised representations to workout form error probabilities. Note that in the following, we have presented our approaches using BackSquat as an exemplary exercise, but our methods are applicable to other exercises. \noindent\textbf{Preliminary - temporally aligning videos.} Our methods build upon temporally aligned videos. Given a collection of videos of people performing the same exercise, we detect the barbell/weight over time to get a motion trajectory, which when plotted against time traces an approximately parabolic curve as shown in Fig.~\ref{fig:barbell_trajectory}. These trajectories are then amplitude-normalized. We leverage the following property to temporally align the videos: for a given elevation of the object (or equivalently, the amplitude of the trajectory), the people doing the same exercise would be in approximately the same pose. This holds across different subjects, different video instances, and across different views/camera angles. Note that, alternatively, other methods, \eg optical flow, can be used to temporally align videos. \subsection{Self-Supervised Pose Contrastive Learning} \label{sec:approach_cvcspc} \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{Figs/pose_contrastive_framework_2_cropped.pdf} \caption{\textbf{Cross-View Cross-Subject Pose Contrastive learning (CVCSPC)}. \textcolor{red}{Red} lines indicate repulsion, while the \textcolor{ForestGreen}{green} line indicates attraction in the representation space.} \label{fig:approach_pose_contrastive} \end{figure} \noindent\textbf{Objective.} Given the temporally aligned videos of the same exercise action, in this approach, we aim to learn richer human pose information using self-supervised contrastive learning. In contrastive learning, same or similar samples are pulled together, while dissimilar samples are pushed apart \cite{chopra2005_contrastive}. In our case, we hypothesize that we can extend contrastive learning to learn human pose-sensitive representations. Particularly, we propose a self-supervised pretext task, which aims to pull together images (frames of videos) containing humans in similar poses, while pushing apart images with humans in dissimilar poses. Note that, this approach operates on single frame-triplets (not videos or clips) at a time. \noindent\textbf{Constructing triplets for contrastive learning.} Once we have the normalized barbell trajectories, for any given anchor input, $I_{\text{anc}}$, we retrieve the corresponding positive input frames with similar object elevation, $I_{\text{pos}}$, and the negative input frames with a difference in object elevation of more than a threshold value ($\delta$), $I_{\text{neg}}$, from across video instances; and subsequently build triplets of $\{I_{\text{anc}}, I_{\text{pos}}, I_{\text{neg}}\}$. Such triplets provide a cross-view, cross-subject, cross-video-instance self-supervisory signal that has not yet been leveraged by the existing computer vision approaches to learn pose sensitive representations. These triplets also offer strong, in-built data augmentations. We term our approach Cross-View Cross-Subject Pose Contrastive learning (CVCSPC). \noindent\textbf{Contrastive learning.} We use the constructed triplet, $\{I_{\text{anc}}, I_{\text{pos}}, I_{\text{neg}}\}$, to learn good representations through self-supervised contrastive learning. Let $f$ represent a 2D-convolutional neural network (CNN) backbone, which when applied to $I_{\text{anc}}, I_{\text{pos}}, I_{\text{neg}}$, yields $\phi_{\text{anc}}, \phi_{\text{pos}}, \phi_{\text{neg}}$, respectively. In contrastive learning, $\phi_{\text{anc}}$ and $\phi_{\text{pos}}$ are forced to be similar, \ie, $\phi_{\text{anc}} \approx \phi_{\text{pos}}$, while $\phi_{\text{anc}}$ and $\phi_{\text{neg}}$ are forced to be dissimilar, \ie, $\phi_{\text{anc}} \neq \phi_{\text{neg}}$, as illustrated in Fig.~\ref{fig:approach_pose_contrastive}. We optimize the parameters of $f$ during the self-supervised training, by minimizing the distance ratio loss \cite{hoffer2015deep}, \begin{equation} \label{eq:distance_ratio_loss} \mathcal{L} = -\log \frac{\mathrm{e}^{-||\phi_{\text{anc}} - \phi_{\text{pos}}||_{2}}}{\mathrm{e}^{-||\phi_{\text{anc}} - \phi_{\text{pos}}||_{2}} + \mathrm{e}^{-||\phi_{\text{anc}} - \phi_{\text{neg}}||_{2}}}. \end{equation} \subsection{Self-Supervised Motion Disentangling} \label{sec:approach_md} Motion cues can be useful in detecting many workout form errors. Different from our pose-contrastive approach, this approach uses motion information to detect anomalies in workout form. In the following, we first present the preliminary information, before describing our method. \vspace{0.2cm} \noindent\textbf{Preliminaries} \vspace{-0.2cm} \begin{itemize}[noitemsep, leftmargin=*] \item \textbf{Useful property 1: Harmonic motion}. Workout actions have a desirable property of exhibiting harmonic motion. For example, during benchpress (an exercise targeting the chest muscles), the person would be lifting the barbell above their chest and then bringing it down to the starting point; or during squats, the person would be squatting down (first half-cycle in Fig.~\ref{fig:barbell_trajectory}) and then getting up (second half-cycle in Fig.~\ref{fig:barbell_trajectory}). \item \textbf{Useful property 2: Bias in temporal location of form-errors}. People are more likely to make errors (anomalous motions) when lifting up the weights (one half-cycle of the harmonic motion, as in Fig.~\ref{fig:barbell_trajectory}), rather than lowering the weights (another half-cycle of the harmonic motion). \item \textbf{Global motion.} The actual, regular motion of the workout action. For example, in Backsquat, the person squatting down and getting up. \item \textbf{Local motion.} The small-scale, fine-grained, irregular motion of the body parts (ref. Fig.~\ref{fig:approach_md}). For example, in Backsquat, the knees abnormally going inward/outward or forward. So, while the global motion refers to regularities in motion patterns, local motion would cover anomalies in motion patterns. \end{itemize} \noindent\textbf{Objective.} Our goal is to learn self-supervised representations that are sensitive to local (anomalous) motions. The above discussed properties can provide a very useful, freely available signal that has not yet been exploited for this task by the existing computer vision approaches. We design a contrastive learning-based self-supervised approach to disentangle the local motion from the global motion. \begin{figure} \centering \animategraphics[loop,autoplay,poster=1,width=\columnwidth]{3}{Figs/md_ani/fr_}{1}{12} \caption{\textbf{Motion Disentangling (MD) approach.} \textit{Please view in AdobeReader to play the embedded animation for better explanation.} \colorbox{black}{\textcolor{white}{\textbf{Black}}} boxes: global motion (getting up, here); \colorbox{yellow}{\textbf{Yellow}} boxes: local motions (the knees rotating inwards under the influence of heavy training weight); aug: augmentations. Here we have applied very weak augmentation (only color augmentation) for representative purpose\textemdash to better illustrate the concept. However, in practice, we apply much stronger augmentations. \textcolor{red}{Red} lines indicate repulsion, while \textcolor{ForestGreen}{green} indicates attraction in the representation space.} \label{fig:approach_md} \end{figure} \noindent\textbf{Accentuating the local motion.} Temporally reversing any one of the half-cycles would, in general, make both half-cycles identical in terms of the global motion, while they would still differ in terms of the local motion. In other words, contrasting the two half-cycles after temporally reversing any one of them, helps accentuate the anomalous local motion, as shown in Fig.~\ref{fig:approach_md}. \noindent\textbf{Constructing triplets for contrastive learning.} The first half-cycle serves as the anchor; an augmented copy of the anchor serves as the positive input. The second half-cycle serves as the negative input. As discussed previously, we randomly temporally-reverse either the \{anchor, positive\} pair or the \{negative\} input to make the global motion of all three identical. In practice, we randomly and independently applied the following augmentations on the triplets: image horizontal flipping, partial image masking, image translation, image rotation, image blurring, image zooming, color channel swapping, temporal shifting. \noindent\textbf{Contrastive learning.} We use a 3DCNN as the backbone for this model, and Eq.~\ref{eq:distance_ratio_loss} as the loss function for this self-supervision task. Through contrastive learning, the 3DCNN learns to identify the previously discussed local, anomalous motions that are accentuated in our specially created triplets. Anomalous motions maybe harmful or they can be beneficial. For example, knees buckling inwards during squatting is harmful, while knees going outwards is not. Therefore, during the finetuning phase, we aim to calibrate representations learnt using self-supervision to distinguish between harmful irregularities and harmless variations. \subsection{Self-Supervised Pose and Appearance Disentangling} \label{sec:approach_pad} Different from our previous two contrastive learning-based approaches, in this image reconstruction-based approach, we aim to disentangle the pose of the humans doing exercises from their appearance (in computer vision sense). We extend the method proposed by Rhodin \etal \cite{rhodin2018unsupervised}, which disentangles camera view and appearance. We extend their concept to a new setting and propose to disentangle the pose and the appearance, while the camera view remains the same. To accomplish this, we leverage an autoencoder setup. This approach involves using two different frames from an exercise-video instance. The person doing the exercise would be in different poses in both frames. We, then, split the encoder embedding into a pose and an appearance vector; and swap the appearance vectors between the two frames before reconstructing the frames using a decoder. The approach is shown in Fig.~\ref{fig:approach_swapping} and additional details are provided in the Supplementary Material. We hypothesize that the swapping operation disentangles appearance from pose by separating time-varying and time-invariant features. To ensure that appearance feature do not collapse to trivial/null solution, we use appearance vector of much larger size than the pose vector. Pose vector is only 32-dim vector. We then use the pose features for error-detection. \begin{figure} \centering \includegraphics[width=0.9\columnwidth]{Figs/swapping_approach_2_1_cropped.pdf} \caption{\textbf{Pose and Appearance Disentangling (PAD)} via feature partition and swapping. \textit{E} and \textit{D} denote encoder and decoder 2DCNNs; A and P denote appearance and pose feature representations.} \label{fig:approach_swapping} \end{figure} \section{Fitness-AQA Dataset} \label{sec:dataset} Since exercise or workout assessment is an emerging field, there is a shortage of dedicated video datasets. To the best of our knowledge, the Waseda backsquat dataset by Ogata \etal \cite{ogata} is the only publicly available such dataset. However, this dataset has shortcomings such as: it contains samples from a single human subject; the human subject is deliberately faking exercise errors; no kind of exercising weights, such as barbells and dumbbells, are used; the videos do not include realistic occlusions. To that end, we collected the largest exercise assessment dataset from video sharing sites such as Instagram and YouTube. We considered the following three exercises: 1) BackSquat; 2) BarbellRow; and 3) Overhead (shoulder) Press. In addition to the labeled data, we also collected an unlabeled dataset to learn human pose focused representations in self-supervised ways (discussed in Sec.~\ref{sec:approach}). The purpose of the labeled dataset is to finetune our models to do actual error detection and quantify the performance of our models. We have provided statistics and illustrated the full hierarchy of our Fitness-AQA dataset in Fig.~\ref{fig:dataset_fitness-aqa}. Unique properties of our dataset: \begin{itemize}[noitemsep, leftmargin=*] \item \textbf{Real-world videos}. Unlike the existing dataset \cite{ogata}, we collected our dataset from actual real-world videos in actual gyms recorded by the people without any scripts. Due to this, the videos are naturally recorded from a wide range of azimuthal angles, inclination angles, and distances. Our samples were automatically processed to contain a single repetition. \item \textbf{People making errors under the impact of actual weights}. In the existing dataset \cite{ogata}, people are instructed to make deliberate exercise mistakes without being under the influence of actual weights. Our dataset, on the other hand, captures cases where people are naturally making mistakes (without any instructions), under the influence of actually heavy weights. Due to this, we believe that there is no bias towards exaggerated errors, and contains natural, subtler error cases. \item \textbf{Occlusions}. Having captured in actual gyms, human subjects are partially occluded by barbell weights, and/or weight racks or other equipment like benches. \item \textbf{Various types of clothing, background, illumination}. Since we did not hire any specific group of people to collect the dataset, the samples in our dataset are likely to come from numerous unique individuals, which results in a large number of clothing styles, and colors; different gyms (in terms of the room arrangement, and the background); other people in the background; and lighting conditions. \item \textbf{Unusual poses}. Exercise actions result in much more convoluted human body positions than those covered in the existing pose estimation datasets. \item \textbf{Annotated by multiple expert trainers}. Our dataset has been annotated by professional gym trainers. Due to this, even very subtle errors are caught and annotated accordingly. Errors range from very subtle to very severe. \end{itemize} We have provided descriptions of various exercise errors in Table \ref{tab:error_desc} (after the References). \section{Limitations} Our approaches require that the body parts in which the error is to be detected, should be active/moving during the exercise to work well. For example, we do not expect our approach to work well on BarbellRow Lumbar error if trained using our SSL techniques on BarbellRow (lumbar does not move in this exercise). However, a way to overcome this is as we did in Sec.~\ref{exp:cross_exercise_transfer}\textemdash by transferring the model from an exercise where the body part of interest was active (backsquat in our case). \section{Conclusion} In this paper, we addressed the problem of assessing the workout form in real-world gym scenarios, where we showed that pose-features from off-the-shelf pose estimators cannot be reliably used for detecting subtle errors in workout form, as these pose estimators struggle to perform well due to unusual poses, occlusions, illumination, clothing styles. We tackled the problem by replacing these noisy pose features with our more robust image and video representations learnt from unlabeled videos using domain knowledge-informed self-supervised approaches. Using self-supervision helped in avoiding the cost of annotating poses. Mapping of our self-supervised representations to workout form error probabilities was learnt using a much smaller labeled dataset. We also introduced a novel dataset, Fitness-AQA, containing actual, unscripted exercise samples from real-world gyms. Experimentally, we found that while our self-supervised features performed comparably in simpler conditions, they outperformed off-the-shelf pose estimators and various baselines in complex real-world conditions on multiple exercises. \section{Experiments} \label{sec:experiments} To validate our contributions, in our evaluation, we compared our features against various baselines and off-the-shelf pose estimators in simple (Case Study 1) and complex conditions (Case Study 2), showing significant improvements in the latter case. We took a two-step approach towards detecting errors in exercising videos. We first trained our models on the unlabeled datasets, and then used our self-supervisedly learnt models as feature extractors on the supervised datasets. For imbalanced datasets, we used class weights (in cross-entropy loss) inversely proportional to the class size. Note that the labeled dataset contains only the exercise error as ground-truth annotation and no information related to human pose. As such, our models did not use any pose-related ground-truth. For the motion disentangling model, since the temporal model is already baked in it, we simply finetuned the model end-to-end on the labeled dataset for error detection. We used 32 frames for all types of errors. For all 2DCNN-based approaches, we a learnt ResNet1D temporal model \cite{ogata} that aggregates frame-level features for supervised error prediction on our labeled dataset. We used about 200 frames during error detection. Finetuning end-to-end on such a long sequence is not recommended \cite{parmar2017learning, xu2019learning, zeng2020hybrid}. Therefore, in this case, the 2DCNN backbone is not finetuned unless specified otherwise. \paragraph{Implementation details.} We used ResNet-18 \cite{resnet} as the backbone CNN unless specified otherwise. We used custom YOLOv3 \cite{yolov3} to detect barbells/weights; and normalized the amplitudes of the trajectories to -180 to 180 (simply for a resemblance to a full circle). Specifications regarding each approach are as follows: \begin{itemize}[noitemsep, leftmargin=*] \item \textbf{Pose Contrastive Approach (CVCSPC)}. We used a threshold gap of 30 between anchor/positive and negative inputs. We initialized our backbone CNN with ImageNet pretrained weights. We used ADAM optimizer \cite{adam} with an initial learning rate of 1e-4 and optimized for 100 epochs with a batch size of 25. \item \textbf{Motion Disentanglement approach (MD)}. We used R(2+1)D-18 \cite{kensho} as our backbone CNN. We sampled 16 frames from each half-cycle. We randomly applied strong augmentations. We initialized our backbone CNN with Kinetics \cite{kinetics} pretrained weights. We optimized our models using ADAM optimizer with an initial learning rate of 1e-4 for 20 epochs with a batch size of 5. \item \textbf{Pose and Appearance Disentanglement approach (PAD)}. We initialized our backbone CNN, which was based on ResNet-18, with the ImageNet pretrained weights. We used ADAM optimizer with an initial learning rate of 1e-4 and optimized it for 500 epochs with a batch size of 25. \end{itemize} Further details provided in the supplementary material. \subsection{Case Study 1: Simple Conditions} \input{Tables/res_waseda} The Waseda Squat dataset \cite{ogata} provides an excellent labeled dataset for evaluating exercise errors in controlled conditions. The publicly available portion of this dataset contains samples from a single human subject. This dataset was not captured in a gym-like setting, but rather in home, and office-like settings. Each sample contains multiple squat repetitions. Note that the publicly available train/val/test split is different from that used in the original paper. Using this dataset, we experimented detecting the following errors: knees inward error (KIE); convex rounded back (spine) (CVRB); concave rounded back (spine) (CCRB); shallow squat (SS); knees forward error (KFE). To do so, we trained classifiers to distinguish between each of these error classes and good squat class (samples belonging to this class did not contain any errors). In this experiment, we compared features from our CVCSPC method (self-supervisedly trained on our unlabeled BackSquat dataset) against the Temporal Distances Matrices (TDM) derived from HMR pose estimator \cite{hmr}. HMR-TDM features were made available by Ogata \etal \cite{ogata}. During feature extraction, we resized the input images to 320$\times$320 pixels, and considered the center 224$\times$224 pixel crop. We did not consider our MD model because this dataset has multiple repetitions in each sample, and the sequence length is 300 frames, which is about 9 times longer than our MD model sequence length (32 frames). And, consequently, if we temporally downsample the sequence, it would lose a lot of information. The results are summarized in Table \ref{tab:res_waseda}, where we report accuracies. We found that our model outperformed existing methods \cite{ogata} on three types of errors: KIE, CCRB, and KFE; with the performances being notably better on KIE and KFE errors. Even though not consistently across all the errors, our self-supervisedly learnt features outperformed HMR-TDM features on overall average performance. Note that one does not expect the performance gap to be large on this dataset, as in these simpler conditions, pose estimators work quite well. \subsection{Case Study 2: In-The-Wild Conditions} Next, we considered evaluating our approach on more complex datasets. For that, we considered our labeled datasets, which we introduced in Sec. \ref{sec:dataset}, where we also discussed the reasons that make our new in-the-wild dataset more challenging. Unless mentioned otherwise, we divided the datasets into train-, validation-, and test-splits of 70\%, 15\%, and 15\%, respectively. \paragraph{Baselines.} We compared our self-supervised feature extractors with the following models and features: \begin{itemize}[noitemsep, leftmargin=*] \item ImageNet \cite{imagenet} pretrained ResNet-18 \cite{resnet} \item Kinetics \cite{kinetics} pretrained R(2+1)D-18 \cite{kensho} \item Temporal Distance Matrices (TDM) \cite{ogata} constructed from the output of SPIN \cite{spin} (3D joint positions) \item Temporal Distance Matrices \cite{ogata} constructed from the output of OpenPose \cite{openpose} (2D joint positions). Originally, TDM was proposed for 3D joint positions, but we also experiment with constructing from 2D joint positions. \item ImageNet pretrained model adapted to our dataset using a general self-supervised image representation learning approach: SimSiam \cite{simsiam} \end{itemize} \paragraph{Performance metric.} Since this dataset is imbalanced, we report the F1-score, instead of the accuracy. \subsubsection{Dataset: Fitness-AQA BackSquat} \paragraph{Knees Inward and Knees Forward Errors.} First, we evaluated all the approaches on knees inward (KIE) and forward (KFE) errors. The results are summarized in Table \ref{tab:res_ours_squat}. Additionally, here, we also considered a single-view, single-subject version of our cross-view, cross-subject pose-contrastive approach. In this version, anchor, positive, and negative inputs all belonged to the same video instance. We applied strong augmentations (rotation, translation, masking image regions, color channel order changing, zooming, blurring) during training this model. We refer to this approach as Vanilla-PC. \input{Tables/res_ours_squat} We observed the following: 1) Kinetics pretrained 3DCNN baseline outperformed the 2DCNN counterpart; 2) Adaptation using the general SSL methods (SimSiam) improved the performance of regular ImageNet pretrained model; 3) Improvement brought by our PAD model was more than that by general SSL method; 4) Our vanilla pose-contrastive learning improved the performance even more than PAD. However, off-the-shelf pose estimator, OpenPose still worked better than this baseline; 5) By contrast, our full pose-contrastive model, CVCSPC outperformed all the models on KIE; for completeness, we also computed OpenPose baseline with our hyperparameter settings referred to as OpenPose$^*$; 6) Our MD model performed best on KFE; 7) CVCSPC performing better than Vanilla PC also reinforced the importance of considering our cross-view and cross-subject conditions during pose-contrastive learning; 8) Our contrastive learning-based approaches worked better than our reconstruction-based approach; 9) ensemble of our contrastive approaches outperformed all the models. In all the subsequent experiments, we considered only the best performing methods for further evaluation. \paragraph{Attention visualization.} To see where our CVCSPC and MD focused after self-supervised training, we visualized using PCA. We also compared the location of attentions with those before the self-supervised training (refer to Fig. \ref{fig:qual_res_attn_vis}). We found that after self-supervised training, the CNN focused more on the human doing the exercise, around the important body parts, for example, legs in case of squats. \input{Figs/fig_attn_vis} \input{Tables/res_shallow_squat} \paragraph{Shallow Squat.} We further considered evaluating and comparing approaches on another squat error\textemdash shallow squat error. Since shallow depth error is a static type of error, image models (2DCNN-based) are more suitable, where errors are detected in singular images, as opposed to in a stack of video frames. Single image detection also made end-to-end learning more feasible, so we finetuned our models end-to-end. The results are summarized in Table \ref{tab:res_shallow_squat}. We observed that end-to-end finetuning allowed the regular ImageNet pretrained model to outperform OpenPose in complex cases. Our self-supervised learning performed the best, showing how important it is to learn task-specific representations, and that our self-supervised training has utility in end-to-end finetuning scenarios as well. \subsubsection{Dataset: Fitness-AQA OverheadPress} \input{Tables/res_ohp} Further, we evaluated and compared approaches on a different exercise\textemdash OverheadPress. The results are summarized in Table \ref{tab:res_ohp}. We observed that video-based approaches worked better than image-based approaches on this exercise. Both of our proposed approaches outperformed the off-the-shelf pose estimator. \subsection{Cross-Exercise Transfer} \label{exp:cross_exercise_transfer} \input{Tables/res_barbellrow} It is common to not have enough labeled data for each exercise. In such cases, it would be useful if we can transfer models from an exercise with abundant data over to exercises with limited data. So, in this experiment, we transferred our model trained on BackSquat exercise to BarbellRow exercise, where we detected two kinds of errors: Lumbar and TorsoAngle errors. Since these errors are static errors, we considered transferring our CVCSPC model. Note that in this experiment we used only a small amount of training data (details in the Supplementary Material). The results are presented in Table \ref{tab:res_barbellrow}. We observed that models pretrained using our proposed self-supervised approach performed better than baselines even when finetuned to a different exercise action. \section{Introduction} \label{sec:introduction} \input{Figs/fig_concept} Detecting errors in users' gym exercise execution and providing feedback on it is crucial for preventing injuries and maximizing muscle gain. However, feedback from personal trainers is a costly option and hence used only sparingly\textemdash typically only a few days a month, just enough to learn the basic form. We believe that an automated computer vision-based workout form assessment (\eg, in the form of an app) would provide a cheap and viable substitute for personal trainers to continuously monitor users’ workout form when their trainers are not around. Such an option would also be helpful to the socio-economically disadvantaged demographic who cannot afford or have access to personal trainers. \begin{figure*} \centering \includegraphics[width=0.95\textwidth]{Figs/exercise_dataset_hierarchy_3_cropped.pdf} \caption{\textbf{Fitness-AQA dataset hierarchy.} Numbers below the dataset type indicate dataset size; and those under the errors indicate the ratio of non-erroneous:erroneous samples. I, V indicate if the error detection is static image-based or multiframe (video)-based.} \label{fig:dataset_fitness-aqa} \end{figure*} While fitness apps have recently become popular, the existing apps only allow the users to make workout plans\textemdash they do not provide a functionality to assess the workout form of the users. To detect errors in the workout videos, it is important to analyze the posture of the humans. Academic research in workout form assessment so far has been limited to simple, controlled conditions \cite{ogata}, where posture can be reliably estimated using off-the-shelf (OTS) pose estimators \cite{openpose,hmr,spin}. Ours, on the other hand, is the first work to tackle the problem of workout form assessment distinctly in complex, real-world gym scenarios, where, people generally record themselves using ubiquitous cellphone cameras that they place somewhere in the vicinity; which results in large variances in terms of camera angles, alongside clothing styles, lighting, and occlusions due to gym equipment (barbells, dumbbells, racks). These environmental factors combined with the subtle nature of workout errors (refer to Fig.~\ref{fig:ots_fails}) and the convoluted, uncommon poses that people go through while exercising, cause major challenges for OTS pose estimators (refer to Fig.~\ref{fig:ots_fails}), and consequently, workout form errors cannot be reliably detected from pose. To mitigate this in the absence of workout datasets labeled for human body pose, we propose to replace the error-prone pose estimators with our more robust domain knowledge-informed self-supervised representations that are sensitive to pose and motion, learned from unlabeled videos (helps in avoiding annotation efforts). Towards those ends, our contributions are as follows: \begin{enumerate}[noitemsep, leftmargin=*] \item \textbf{Novel self-supervised approaches that leverage domain knowledge}. We initiate the work in the direction of domain knowledge-informed self-supervised representation learning by developing two contrastive learning-based, and one reconstruction-based self-supervised approaches that capitalize on the harmonic motion of workout actions and the large variance in unlabeled gym videos to learn robust fitness domain-specific representations (Sec.~\ref{sec:approach}). Our representations outperform various baselines including 2D- and 3D-pose estimators on the task of workout form assessment on existing and our newly introduced datasets. We believe that, in general, future work on representation learning would benefit from using domain knowledge in designing self-supervised methods, especially when tackling problems involving real-world data. \item \textbf{Workout form assessment dataset}. To facilitate our self-supervised approaches, as well as the subsequent supervised workout form error detection, we collected the largest, first-of-its-kind, in-the-wild, fine-grained fitness assessment dataset, covering three different exercises (Sec.~\ref{sec:dataset}) and enclosing a small labeled subset for evaluation. We show that this in-the-wild dataset provides a significantly more challenging benchmark than the existing one recorded in controlled conditions. \end{enumerate} Note that our objective is not to improve the performance directly on the task of human pose estimation per se, but rather to improve the performance on exercise error detection. \noindent\textbf{Ethics:} We have blurred the faces in our paper. Our dataset is diverse and not limited to any particular demographic. \section{Related Work} In the following, we discuss relevant prior work in the areas of action quality assessment (AQA) and SSL. \paragraph{AQA and Skills Assessment (SA).} Our work can be classified under AQA and SA, which involves the computer vision-based quantification of the quality of movements and actions. Works in AQA and SA have mainly been focused on domains like physiotherapy \cite{tao2016comparative, parmar2016measuring, li2021improving, sardari2020vi, du2021assessing}, Olympic sports \cite{parmar2019action, mtlaqa, xu2019learning, tang2020uncertainty, yu2021group, chen2021sportscap}, various types of skills \cite{doughty2019pros, wang2020towards, liu2021towards, parmar2021piano}. However, workout form assessment, especially, in real-world conditions, has not received much attention. Approaches in AQA can be organized into 1) human pose-features based \cite{pirsiavash, Pan_2019_ICCV}; 2) image and video features-based \cite{parmar2017learning, mtlaqa}. Pose-based approaches use OTS pose estimators to extract 2D or 3D coordinate positions of various human body joints. These approaches have the disadvantage that poor estimation of the pose can adversely affect the final output. This is especially prevalent in non-daily action classes like fitness and sports domains. This can be mitigated, for example, by annotating domain-specific datasets \cite{chen2021sportscap}, but that requires a considerable amount of manual annotation efforts, financial resources, and 3D annotations can only be obtained in controlled conditions. Therefore, we propose to learn domain-specific pose-sensitive representations from unlabeled videos, which can be finetuned using only a small labeled dataset. Closest to ours is the work on backsquat assessment by Ogata \etal \cite{ogata}. However, a) they used OTS pose estimators, whereas we develop self-supervised approaches to learn more powerful representations; b) being dependent on OTS pose estimators, their approach is limited only to simple, controlled environments, whereas our approach is applicable to complex, real-world scenarios (Sec.~\ref{sec:experiments}); and c) their dataset contains only single exercise and was collected in simpler conditions and a single human, whereas our dataset contains three exercises and was collected in real-world gym scenarios and numerous humans (further differences discussed in Sec.~\ref{sec:dataset}). \paragraph{SSL.} Earlier work in this area include those of autoencoders \cite{hinton2006reducing}, which learn low-dimensional representations by reconstructing the input. Le \etal \cite{convisa} propose a way to learn hierarchical representations from unlabeled videos using unsupervised learning, which was also considered as a feature extractor in an earlier AQA work \cite{pirsiavash}, but was found to perform worse than an OTS pose estimator. More recent SSL methods include leveraging properties of video data like: 1) the temporal order \cite{misra2016shuffle, xu2019self}; 2) the objects' upright positions \cite{rotnet}; and 3) motion and appearance statistics \cite{wang2019self}. A few works propose to leverage time-contrast to learn representations using self-supervision \cite{hyvarinen2016unsupervised, tcn, honari2020unsupervised}. However, these temporal models either consider a single-view or a single subject. Our pose contrastive approach, on the other hand, simultaneously exploits cross-view and cross-subject information to learn more meaningful representations. Another work proposes to disentangle pose and appearance from multiple views with a geometry-aware representation \cite{rhodin2018unsupervised}. However, this approach is not tailored for exercise analysis, and requires calibrated multi-view datasets. Inspired by this method, we develop a variant\textemdash our pose and appearance disentangling approach\textemdash applicable to our dataset.
{'timestamp': '2022-03-01T02:59:44', 'yymm': '2202', 'arxiv_id': '2202.14019', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.14019'}
arxiv
\section{Introduction} \label{Intro} Malicious software, a.k.a malware, is defined as a file or program that tries to damage the normal activity of a digital device. Most malware are specifically engineered to the operating system (OS) they target, as OSs tend to vary based on their hardware and functionalities. One of the popular targets of malware is the Android OS. Android application Packages (APKs), the popular executable files of Android OS, can be found in many Android markets around the world (e.g., Google play store~\cite{GooglePlay}). Many malware apps can be found on these markets that target the attention of unsuspecting users to assure downloading of the malicious app. For example, the Etinu malware leverages the fear of the recent COVID-19 in Asia~\cite{covid-report}. This malware stole information from incoming SMS messages, made purchases in the victim's name, and infected more than 700K users. As a safeguard for these users and many more, a vast amount of researchers and cyber experts are looking for a satisfying solution for the correct identification of malware applications~\cite{aafer2013droidapiminer,arp2014drebin,berger2021crystal,cai2018towards,chen2016stormdroid,dini2012madam,huynh2017new,enck2009lightweight,onwuzurike2019mamadroid,shabtai2012andromaly,shabtai2009detection,shabtai2014mobile,sun2016sigpid,talha2015apk,treadwell2009heuristic,venugopal2008efficient,wang2014exploring,wu2012droidmat,xu2013permlyzer}. Several studies were conducted throughout the years to mitigate the threat of Android malware, implementing methods like using heuristics of app structure and signatures~\cite{treadwell2009heuristic,venugopal2008efficient}, permissions' analysis~\cite{enck2009lightweight,wang2014exploring,xu2013permlyzer,talha2015apk,sun2016sigpid}. Hitherto, the most popular approaches to Android malware detection are Machine Learning and Deep Learning~\cite{aafer2013droidapiminer, arp2014drebin, onwuzurike2019mamadroid, shabtai2009detection,berger2021crystal}. A strong ML classifier is based, among others, on the raw data that must represent the domain correctly. Specifically, for different sub-domains of malware detection, there is a different real-world distribution of malicious and benign samples. For example, in the subdomain of URL malware detection, most Internet addresses are considered malicious~\cite{maggi2013two,rahbarinia2017exploring}. In the paper domain, Android malware, most of the apps are considered benign~\cite{G_201_sum,lindorfer2014andradar,pendlebury2018tesseract}. A recent and popular study defined the advisable ratio as 90/10 between benign and malicious Android apps~\cite{pendlebury2018tesseract}. As a result, the challenge for the Android malware classifiers is to analyze the important characteristics of malicious apps, despite the low volume of malicious apps in the dataset. Even an ML classifier trained on the right amount of benign and malicious apps is not 100\% accurate on any input sample. It was proven by Goodfellow et al.~\cite{goodfellow2014explaining} that some ML classifiers are susceptible to manipulations. These manipulations are called~\textit{adversarial examples}. Adversarial examples are created when an attacker manipulates malicious samples so that the sample will be misclassified as benign and vice versa~\cite{grosse2017adversarial,kuppa2019black,yuan2019adversarial}. In turn, \textit{evasion attacks} are intelligent attacks in which the adversary manipulates malicious instances, such that they will be wrongly classified. Evasion attacks that change the physical malicious instance are called problem-based evasion attacks. On the other hand, evasion attacks that manipulate the extracted feature vector of an instance are called feature-based evasion attacks. To address the threats that arise from evasion attacks on APKs, this work follows one of the well-known Android malware detection systems, MaMaDroid~\cite{onwuzurike2019mamadroid}. MaMaDroid is based on Control Flow Graph (CFG)~\cite{10.1145/390013.808479}, where a CFG is a representation of a program using graph notation. This representation depicts all paths that might be traversed through the program while executing it. The contribution of this paper is threefold. First, a full evaluation of the portion of instances on the training set that is benign on the classifier's detection rate is presented. Second, three innovative problem-based evasion attacks against MaMaDroid are introduced. The evasion attacks are thoroughly evaluated based on multiple metrics (e.g., robustness), and a varied set of models. Finally, insights from this analysis motivated the creation of a new version of MaMaDroid, MaMaDroid2.0. The new version incorporates an extended feature set. MaMaDroid2.0 was evaluated against our novel evasion attacks and other known evasion attacks. Compared to the original MamaDroid model ~\cite{onwuzurike2019mamadroid} which results in an evasion robustness of less than 30\%, the new model results in an evasion robustness of more than 90\%. The remainder of this paper is organized as follows. First, related work is presented and discussed in Section~\ref{related}. MaMaDroid, the targeted system, is presented in Section~\ref{machines}, together with the attacker models. In Section~\ref{attacks}, the attacks are presented. Next, in Section~\ref{eval}, metrics and evaluations are discussed. The new version of MaMaDroid, MaMaDroid2.0, is explored in Section~\ref{mama2}. A discussion about the evasion attacks and mitigation techniques can be found in Section~\ref{diss}, along with the conclusion of the paper. Table~\ref{abbrev_table} is an abbreviations table. \section{Related Work} \label{related} In Section~\ref{detection systems label}, four main approaches in the field of Android malware detection systems are described. Additionally, evasion attacks leverage weak spots in ML-based Android malware detection systems. Evasion attacks take two forms: problem-based attacks and feature-based attacks. Problem-based attacks~\cite{alzantot2018generating,apruzzese2018evading,dang2017evading,demontis2017yes,li2018textbugger,rastogi2013droidchameleon,zheng2012adam} include modification of the samples. This is the type of attack implemented in this study. Feature-based attacks~\cite{pkdd2013,carlini2017towards,chen2018droideye,shahpasand2019adversarial,shao2019multi,xu2020towards,zikratov2017formalization} map the sample into a feature vector and modify the values of the features. Feature-based attacks are easier to implement than problem-based attacks. The feature-based attacks can be generated automatically by an ML~\cite{aydogan2015automatic,chen2017adversarial,hu2017generating,ming2015replacement,zhao2019unsupervised}. Still, the correlated code in the sample that needs to be changed according to these attacks may severely damage the functionality of the sample~\cite{chen2018android,pierazzi2020problemspace,salem2018repackman,berger2020evasion}. Therefore, feature-based evasion attacks are less realizable. This study implements problem-based evasion attacks. Therefore, a review of significant works on problem-based evasion attacks on Android malware detection systems is presented in Section ~\ref{evasion-attacks-review}. \subsection{Android Malware Detection Systems} \label{detection systems label} This section surveys well-known Android malware detection systems following four main approaches. The first approach is static analysis, which gathers significant strings from the Smali code files and Manifest file. The second strategy is based on the control flow graph (CFG) of the application, which traces the order of the API calls used in the app. The behavior of the app is inspected in the third approach, which gathers information on the behavior of the Android OS during the run of the app, along with network packets sent and received, etc. The last approach analyses bytecode sequences. Several Hybrid systems are discussed as well. Probably one of the honored Android malware detection systems using static analysis is Drebin~\cite{arp2014drebin}. Drebin gathers 8 types of static features, with a specification of two main components of the APKs. Drebin extracts permissions requests, software/hardware components, and intents from the Manifest file. From the Smali code, it extracts suspicious/restricted API calls, used permissions in the app's run and URL addresses. Sec-SVM~\cite{demontis2017yes} is an improved version of Drebin, using a more evenly weighted learning model. Other versions of Drebin include a Factorization Machine~\cite{li2019android} and a DNN~\cite{AdversarialDeepEnsemble}. The DroidAPIMiner~\cite{aafer2013droidapiminer,droidapiminber_code} is similar to Drebin, in means of static analysis and feature types. The API calls and permissions are the feature set of this detection machine. The authors of this research performed a dataflow analysis for frequently used API values and package names. The static analysis detection systems look for several features from the APK. Enumeration of these features is easy and efficient. However, since most of the static features can be easily understood, they can also be automatically manipulated without many efforts, like in~\cite{demontis2017yes,maiorca2015stealth,meng2016mystique,rastogi2013droidchameleon}. A more robust approach is found in MaMaDroid~\cite{onwuzurike2019mamadroid}, which extracts the Control Flow Graph (CFG) of an application as a base for its feature set. MaMaDroid generates a tree of API calls based on family and package names. Then, the detection system analyzes the API call sequence performed by an app by each mode - family or package, to model its true nature. A similar approach to detect malicious third-party use in apps was used by Backes et al.~\cite{backes2016reliable}. Function and app profiling, such as types and parameters, were used to identify third-party libraries and different versions of the same library. Zhiwu et al.~\cite{xu2018cdgdroid} used CFG along with data flow to characterize Android apps, along with a CNN model to predict the labels of new samples. An extension was suggested in~\cite{zhiwu2019android}, where the same technique was used using n-grams to identify malware families. Monitoring the sequence of functions and API calls inside the app seems like a great idea. Changing the flow of the app is more complicated, since the CFG may be complex and full of details. Furthermore, changing the order of API calls of the app may damage the malicious activity of the app. However, several evasion attacks manipulate the flow of the app and succeed in deceiving this kind of detection system, such as~\cite{chen2018android,ikram2019dadidroid,maiorca2015stealth,piao2016server,sun2014nativeguard}. The third approach tries to map the traces of a malicious app, thus acknowledging the behavior of such apps, using several operating systems and communication features, as was introduced in Andromaly~\cite{shabtai2012andromaly}. A similar approach was taken by Shabtai et al.~\cite{shabtai2014mobile}. These detection systems focused on network usage by measuring the network traffic patterns in a host device running an app. The authors learned the statistics of network packets a user sent and received, the RTT, etc. Another research using a similar strategy is Shabtai et al.~\cite{shabtai2010intrusion}. The authors aggregate data during an app run, including user interactions like clicks and touches and OS behavior such as the CPU and network usage. Saracino et al.~\cite{saracino2016madam} found the correlations between features at four levels: kernel, application, user and package, to identify malicious applications. Wang et al.~\cite{wang2021android} explored the number of pages on virtual machines, the change of states between tasks, etc. Behavioral detection methods are based on the nature of the Android device while running various apps. These behaviors may depend on the app and are therefore hard to generalize. Therefore, they are not a complete solution to malware detection. Bytecode inspection is the last approach to Android malware detection. Dalvik Bytecode Frequency Analysis~\cite{kang2013android} is one example, which looks for popular Dalvik Bytecode instructions of malware apps. Sequences of Dalvik Bytecode instructions were also explored by TinyDroid~\cite{chen2018tinydroid}. The authors of this system gathered families of Bytecode instructions under a single symbol and used n-grams~\cite{damashek1995gauging} to create the feature set. Yang et al.~\cite{yang2015appspear} extracted the bytecode file from the APK and converted the Bytecode to a matrix. This matrix was analyzed by a CNN. Bytecode inspection is a heavy method and ambiguous for the human eye, as it is not a convenient programming language. A hybrid detection system was suggested by Martín et al.~\cite{martin2019android}. This system fused the static and dynamic analysis of Android apps. The authors combined the transitions between execution states (dynamic) and the inspection of API calls (static). A combination of static analysis of permission requests and dynamic testing of their derived API calls was introduced in~\cite{wang2015reevaluating}. MARVIN~\cite{lindorfer2015marvin} inspects the nature of Android apps through static analysis of their design, certificates, etc. In addition, a dynamic analysis of behavioral activity is processed. The combination of static analysis of permissions and intents and dynamic analysis of network traffic was introduced by Ding et al.~\cite{ding2021hybrid}. A hybrid solution seems the best option to identify malicious apps. However, each method that is added as another layer of processing consumes time and resources from the host device. \subsection{Problem-Based Evasion Attacks} \label{evasion-attacks-review} This section targets the problem-based evasion attacks against malware detection systems. Problem-based evasion attacks are categorized into three forms of attacks. The first uses camouflage to conceal incriminating strings and values contained in the app, by encryption and obfuscation. Next, the second incorporates noises to the app; e.g., uncalled functions. At last, the third form tries to alter the behavior of the app. It reviews the flow of the original app and manipulates the code of several function calls. The first course of action in evasion attacks is to conceal specific suspicious components of the app. One well-known example of a concealment effort is with the help of encryption or obfuscation. Demontis et al.~\cite{demontis2017yes} obfuscated suspicious strings, packages, and API calls. Another example of concealment is packing an app inside a fellow app. DaDidroid~\cite{ikram2019dadidroid} explored a similar approach as Demontis et al.~\cite{demontis2017yes} using packing and obfuscation. Reflection allows a program to change its nature at runtime. It is another classic evasion technique. Rastogi et al.~\cite{rastogi2013droidchameleon} presented an attack, which mixes the Demontis et al.~\cite{demontis2017yes} obfuscation method with the addition of the reflection approach. Another form of problem-based evasion attack includes adding noise to the app. These noises mislead the classifier's labeling process. An example of noise addition can be a stub function/code injection. A stub function is a non-operational function, that does not do anything. However, it changes the original flow of an app. An example of a stub function addition is Android HIV~\cite{chen2018android}, where the authors implemented non-invoked suspicious functions against the Drebin classifier and a stub function injection against the MaMaDroid classifier. A recent example of this kind of attack is at~\cite{pierazzi2020problemspace}, where the authors implanted benign snippets of code in malicious apps to evade the Drebin and Sec-SVM~\cite{demontis2017yes} classifiers. Rosenberg et al.~\cite{rosenberg2018generic} generated an evasion attack against Android malware detection systems using API call manipulation. Three methods were used: Addition of non-operational functions to the application, obfuscation of strings, and encoding of short API calls. Cara et al.~\cite{cara2020feasibility} added non-invoked classes to the end of functions to a. The last approach is changing the app flow. One of the ways to implement this approach is by function outlining/inlining. In function outlining, the attacker breaks a function into smaller code snippets. In function inlining, the adversary replaces a function call with the entire function body. This technique was implemented in Droidchameleon~\cite{rastogi2013droidchameleon}, which incorporated function outlining in its evasion attacks. Another option to break the app flow is stub function, as in~\cite{chen2018android,piao2016server,sun2014nativeguard}, resulting in an ML misclassification of a malicious app. \section{MaMaDroid and Attacker Models} \label{machines} In this section, the targeted system MaMaDroid~\cite{onwuzurike2019mamadroid,onwuzurike2019mamadroidold} is presented, followed by the attacker models. \subsection{MaMaDroid} MaMaDroid is an Android malware detection system, introduced in 2017 by Onwuzurike et al.~\cite{onwuzurike2019mamadroid}. This detection system extracts features from the Control Flow Graph (CFG) of an APK sample. It enumerates abstracted API calls to capture the behavioral model of the app. MaMaDroid operates in two modes: family and package mode. For example, the API call \textbf{android.util.Log-$>$d()} is abstracted as \textbf{android.} in the family mode, and \textbf{android.util} in the package mode. Packages or families, which are defined by the app's developer or obfuscated are abstracted as \textit{self-defined} and \textit{obfuscated}, respectively. As the structure of the evasion attack is similar for both modes, and the family mode results in lower processing time and memory, the family mode was chosen for this analysis. The structure of the evasion attack is similar for both modes. MaMadroid creates the features for the learning algorithm in the following manner: First, it extracts the CFG from the app. Then, it gets the sequences of API calls. Next, the APIs are abstracted using one of the modes. At last, it constructs a Markov chain~\cite{brooks2011handbook,geyer1992practical,marjoram2003markov}, with the probabilities of transition between any family/package. These probabilities are used as the features. For example, \textbf{androidTojava} is the feature that resembles the probability of transition between the android family to the java family. For a full description of the MaMaDroid classifier, see~\cite{onwuzurike2019mamadroid} (implementation is available at~\cite{mama_implementation}). \subsection{Attacker Models} \label{model} This section describes two attacker models, which depict the embedded knowledge each attack holds. The first model, named as \textbf{Feature set Access (FA)}, depicts a gray-box attacker that knows the feature set of the targeted system (as the attacker model in~\cite{spooren2019use} and attack scenario F in~\cite{chen2018android}). The second model is the \textbf{Statistics Access (SA)}, which is a white-box attacker, and can access the feature set and the training data (as attack scenario FB in~\cite{chen2018android}). \section{Evasion Attacks}\label{attacks} Based on the attacker models, a set of evasion attacks is engineered that transfers the embedded knowledge of the defense model to a manipulated malicious APK that will be classified as benign. The idea behind these attacks is to break and change the structure of the sample so that the detection system would not recognize the manipulated samples as malicious. The three evasion attacks described in this section are variants of a general attack that will be termed the Structure Break attack. However, before the description of the Structure Break (StB) general algorithm, an explanation of the \textit{mode elements} is provided. These items are vital to each one of the attacks, and specifically engineered for each one of them according to their attacker model. The \textit{mode elements} are discussed in Section~\ref{mode_elem}. Then, the Structure Break (StB) general algorithm is described in Section~\ref{mama_att_algo}. At last, the variants are described in Section~\ref{ev_attacks}. \subsection{Mode Elements} \label{mode_elem} Mode elements are a subset of the feature set of the specific mode MaMaDroid analyzes. For example, for the family mode, android., java. and xml. are a part of the feature set of the family mode and therefore can be picked for the Mode elements of the family mode. In this work, the mode elements are engineered in three ways: \begin{enumerate} \item Randomly - Randomly picking a subset of the feature set. Specifically, several families like android. java. and xml can be picked from the family mode feature set. \item Statistically - Using the statistics of the given data. Given data can be the train and test sets, or just the test set. The given data is analyzed, to produce statistics on the elements. If the training data is given, the elements that will be picked are the ones that hold high values in the benign data, and low values in the malicious data. For example, if the java family's features (javaTojava,javaToandroid,etc.) in the benign data are high values, and also low values in the malicious data, then java will be picked for the mode elements. The idea is to try and mimic the behavior of the benign samples. If only the test data is given, the least popular elements are chosen. The test data includes malicious samples only, as this work analyzed the effect of evasion attacks against the targeted system. For example, if the java family's features (javaTojava,javaToandroid,etc.) in the test data are in low volume, then java will be picked for the mode elements. The idea behind this pick is to try and move the focus of the extracted features to less popular features. These features are supposed to weigh less and therefore be neglected by the targeted system. \end{enumerate} The difference between the methods of picking the mode elements is a result of the specific evasion attacks, which will be discussed in Section~\ref{ev_attacks}. \subsection{Structure Break Algorithm} \label{mama_att_algo} \begin{algorithm}[!] \caption{Structure Break Attack - General Algorithm }\label{alg:structure_break} \begin{algorithmic}[1] \Procedure{Structure Break Attack}{$APK,Mode\_elements,L\_func,P\_func$} \State $Manifest,Smali, Layouts \gets depackage(APK)$ \label{lst:line:dpk} \State $APK\_Tree, Height \gets apk\_structure(Smali)$ \label{lst:line:apk_tree} \State $L \gets L\_func(0,Height)$ \label{lst:line:pick_level} \State $P \gets P\_func(0,1)$ \label{lst:line:pick_precent} \State $f \gets random(Mode\_elements)$ \label{lst:line:get_elem} \State $mkdir(f,APK\_Tree) $ \label{lst:line:cr_elem} \State $Roots \gets get\_roots\_random(APK\_Tree,P,L)$ \label{lst:line:get_roots_ratio} \ForEach {$r \in Roots $}\label{lst:line:roots_loop} \State $r\_new \gets f+r$\label{lst:line:concat} \State $S\_roots \gets get\_Smali\_files(r)$\label{lst:line:root_get_files} \ForEach {$file \in S\_roots $}\label{lst:line:loop_subs} \State $file \gets change\_oc(file,r,r\_new)$\label{lst:line:ch_oc_sroots} \State $ move(r+file,r\_new+file)$ \label{lst:line:move} \EndFor \ForEach {$file \in Manifest,Layouts $} \label{lst:line:man_lay} \State $file \gets change\_oc(file,r,r\_new)$ \label{lst:line:ch_man} \EndFor \EndFor \State $APK \gets Repackage(Manifest,Smali...)$\label{lst:line:repack} \State \textbf{return} $APK$\label{lst:line:end} \EndProcedure \Procedure{change\_oc}{$file,r,r\_new$}{\ForEach {$line \in file $}\label{lst:line:ch_oc1} \State $file[line] \gets file[line].replace(r,r\_new)$\label{lst:line:ch_oc2} \EndFor} \textbf{return} $file$\label{lst:line:oc_end} \EndProcedure \end{algorithmic} \end{algorithm} Given malicious APKs, the attacker manipulates the structure of each APK towards the picked \textit{mode elements}. An algorithm that implements this manipulation is depicted in Algo.~\ref{alg:structure_break}. The inputs for this algorithm include an APK to manipulate, the \textit{mode elements}, and $L\_func$ and $P\_func$. The last two inputs define two functions. $L\_func$ is a function that given the range of 0 to the directories tree's height (of the application), chooses a specific height. $P\_func$ is a function that given a range of change(the default is [0,1]), chooses a ratio of change (for the specific level chosen by $L\_func$). As there are two options for each function depending on the specific attack variant, they are defined as variables. The algorithm implements the following steps: (1) The algorithm’s inputs are an APK file, the \textit{Mode\_elements}, $L\_func$ and $P\_func$; (2) Depackage the APK to the Manifest file, Smali code files, and other subordinate files (line~\ref{lst:line:dpk}); (3) Get the structure of the Smali code files as a tree (\textit{APK\_Tree}), and the tree's height (\textit{Height}) (line~\ref{lst:line:apk_tree}); (4) Run $L\_func$ and store the result it \textit{L} (line~\ref{lst:line:pick_level}); (5) Run $L\_func$ and store the result it \textit{P} (line~\ref{lst:line:pick_precent}); (6) Get a random item from the set of Mode\_elements (line~\ref{lst:line:get_elem}) as $f$; (7) Create a directory whose name is $f$ at the top of \textit{APK\_Tree}, alongside the former root of the tree (line~\ref{lst:line:cr_elem}); (8) According to steps~\ref{lst:line:pick_level}-\ref{lst:line:pick_precent}, get \textit{P} of the directories in level \textit{L} of the \textit{APK\_Tree}. Store them as $Roots$ (line~\ref{lst:line:get_roots_ratio}); (9) For each directory $r$ in the $Roots$ set, run lines~\ref{lst:line:concat}-\ref{lst:line:ch_man} (line~\ref{lst:line:roots_loop}); (10) Concatenate $f$ as a prefix of the former directory name $r$. Call it $r\_new$ (line~\ref{lst:line:concat}); (11) Store all the subdirectories and files of $r$ in \textit{S\_roots} (line~\ref{lst:line:root_get_files}); (12) For each file/directory in $S\_roots$, run lines~\ref{lst:line:ch_oc_sroots}-\ref{lst:line:move} (line~\ref{lst:line:loop_subs}); (13) Run the \textit{change\_oc} on the file/directory, $r$ and $r\_new$ (line~\ref{lst:line:ch_oc_sroots}). The \textit{change\_oc} function (lines~\ref{lst:line:ch_oc1}-\ref{lst:line:ch_oc2}) replaces any occurrence of a line in a file/set of files with a replacement. In this case, it changes the occurrence of $r$ with $r\_new$; (14) Move the file from the previous directory $r$ to the new directory $r\_new$ (line~\ref{lst:line:move}); (15) For each file in the set of Manifest and layout files, run line~\ref{lst:line:ch_man} (line~\ref{lst:line:man_lay}); (16) Run the $change\_oc$ function on the file (line~\ref{lst:line:ch_man}); (17) Repackage the APK (line~\ref{lst:line:repack}), and return it as an output (line~\ref{lst:line:end}). The attacker creates a new full functional APK, as it changes the structure of the Smali code files, the Manifest file, and the layout files (lines~\ref{lst:line:loop_subs}-\ref{lst:line:ch_man}). As all of these files might include some occurrences of the part that changed (in other words, references to files that moved from their original places), these occurrences need to be changed accordingly. A small example of this algorithm is provided for clearance. Let's $APK$ be an APK that includes the following: \begin{enumerate} \item A Manifest file \item 2 Layout Files named $L1$ and $L2$. \item A Smali code directory which has the following structure: \begin{itemize} \item A root directory named $com$. \begin{itemize} \item A subordinate directory with the name $tb$. \begin{itemize} \item A Smali code file named $x1.smali$. \item A Smali code file named $x2.smali$. \end{itemize} \item A subordinate directory with the name $xz$. \end{itemize} \end{itemize} \end{enumerate} Let's $mode\_elements={android,java}$, $L\_func=1$, $P\_func=0.5$. For this example, the chosen part for change is the $tb$ folder. The element $f$ is chosen to be $android$. The structure of the output $APK$ is now: \begin{enumerate} \item A Manifest file \item 2 Layout Files named $L1$ and $L2$. \item A Smali code directory which has the following structure: \begin{itemize} \item A root directory named $com$. \begin{itemize} \item A subordinate directory with the name $xz$. \end{itemize} \item A root directory named $android$. \begin{itemize} \item A subordinate directory with the name $tb$. \begin{itemize} \item A Smali code file named $x1.smali$. \item A Smali code file named $x2.smali$. \end{itemize} \end{itemize} \end{itemize} \end{enumerate} Each occurrence of the changed part (names of $tb$ directory and its subordinate files) is changed in the Manifest files and $L1$ and $L2$. \begin{table} \center \begin{tabular}{|c|c|} \hline Abbreviation & Definition\\ \hline CV & Cross-Validation\\ \hline DT & Decision Tree\\ \hline RF & Random Forest\\ \hline ML & Machine Learning\\ \hline ER & Evasion Robustness\\ \hline DRR & Defense Reciprocal Rate\\ \hline CFG & Control Flow Graph\\ \hline APK & Android PacKage\\ \hline FA & Feature Access\\ \hline SA & Statistics Access\\ \hline StB & Structure Break\\ \hline NN & Nearest Neighbor\\ \hline TPR & True Positive Rate\\ \hline \end{tabular} \caption{Abbreviations table} \label{abbrev_table} \end{table} \subsection{Structure Break Attack Variants} \label{ev_attacks} The previous section~\ref{mama_att_algo} described the general StB algorithm. This section describes the actual evasion attacks, which are variants of the StB general algorithm. Each variant is described by its attacker model, $Mode\_elements$, $L\_func$ and $P\_func$. \begin{enumerate} \item \textbf{Random StB Attack:} This attack variant is based on the FA attacker model, as it uses only the knowledge of the feature set. Therefore, a random set of $mode\_elements$ is taken from the feature set. The $L\_func$ an $P\_func$ are random functions. In other words, these functions randomly pick a level in the range of [0,$Height$], and a ratio of change between 0 to 1, respectively. This variant is called Random StB Attack, as the $Mode\_elements$ are chosen randomly. \item \textbf{Full Statistical StB Attack:} This attack variant is based on the SA attacker model, which incorporates the knowledge of the feature set and the train data. The $Mode\_elements$ are chosen statistically (for more information, see Section~\ref{model}). The attacker chooses the element that has the highest values of transitions between families in the benign apps and low values in the malicious apps. Then, it stores it in the $Mode\_elements$. The $L\_func$ and $P\_func$ are not random functions. They are both set to maximize the effect of the change. In other words, $L\_func$ chooses 0 to include the whole smali directory tree in the change of the app. Also, $P\_func$ is set to 1 to include the maximum amount of files and directories in the manipulation. This attack variant is called Full Statistical StB Attack, as it leverages the full knowledge of statistics of the train data. \item \textbf{Black Hole Statistical StB Attack:} This attack variant is based on the FA attacker model, which uses only the knowledge of the feature set. The set of $Mode\_elements$ is chosen statistically by the test data only. The attacker chooses the element that holds the lowest values of transitions between families in the test data it obtains (as explained in Section~\ref{model}). The picked element is stored in the $Mode\_elements$. The $L\_func$ and $P\_func$ are identical functions to the functions used in the Full Statistical StB Attack, to maximize the effect of the attack. As the idea of this attack variant is to move some of the values to places in the feature vector with no initial positive values (or close to it), which can be referenced as black holes, this variant is called Black hole Statistical StB attack. \end{enumerate} \section{Metrics and Evaluations} \label{eval} A set of experiments was conducted to evaluate the effects of the evasion attacks of Section~\ref{ev_attacks}. First, Section~\ref{mama_exp_settings} describes the design of the experiments. Then, evaluation metrics are reported in Section~\ref{metrics_names}, followed by their evaluation of the evasion attacks. Section~\ref{former_apps_results} describes the evaluation of the Evasion Robustness (ER) metric. Section~\ref{drr_res} presents the results of the Defense Reciprocal Rate (DRR) metric. At last, Section~\ref{mra_res} describes the evaluation of the Model Reliability. \subsection{Experimental Design} \label{mama_exp_settings} The experiments include an analysis of an extended set of models of MaMaDroid~\cite{onwuzurike2019mamadroid}. First, the set of distance-based models of MaMaDroid is used (1-NN and 3-NN) and extended by a 5-NN model. Second, the tree-based models are tackled in a parallel way. RF is the only tree-based model that was originally used. As RF is an ensemble of decision trees (DTs), the basic DT model is included. On the other hand, a boosting model (i.e., AdaBoost), which is a more sophisticated ensemble of DTs, is added. In contrast to the RF, where the final decision is based on the decision of each DT independently, in AdaBoost, each DT is aimed to focus on the wrong classification of the prior ones. In total, six models were explored. For each evasion attack, an experiment was conducted using these six models (1-NN, 3-NN, 5-NN, DT, RF, Adaboost). The experiments were run on an Intel(R) Xeon(R) CPU E5-2683 v4 2.1 GHz with 64 GB RAM with GeForce RTX 2080 TI GPU. The dataset for the experiments consisted of $\sim$73K benign apps from the Google Play Market~\cite{GooglePlay} (obtained from Androzoo~\cite{allix2016androzoo}) and $\sim$6K malicious apps from the Drebin dataset~\cite{ali2016aspectdroid,arp2014drebin,berger2021crystal,frenklach2021android,maiorca2017r,yuan2020byte,zulkifli2018android}. To account for variations in the dataset, a 5-fold CV was used. To test the changes in the detection rate of each of the models, different ratios of benign and malicious apps were used during the experiments. The test data without any manipulations will be termed \textit{clean data}. The post-manipulation test data will be referred to as \textit{manipulated data}. To fully evaluate the evasion attacks, an additional experiment on clean data was used as a baseline. To clarify the effect of the amount of benign data on the decision function of each model is tested, the malicious apps are fixed for each experiment, while the benign ratio changes (10\%,20\%,\ldots,100\%). \subsection{Metrics} \label{metrics_names} \textbf{Evasion Robustness (ER):} To evaluate robustness, the portion of malicious instances which was wrongly classified was computed (similar to the analysis provided in~\cite{tong2017framework}). The TPR of malicious apps was used as this evaluation metric, both for manipulated apps and clean malicious data. \textbf{Defense Reciprocal Rank (DRR):} A new metric to evaluate the strength of an evasion attack was presented in~\cite{brama2022evaluation}. The intuition behind the Defense Reciprocal Rank (\textit{DRR}) is that a correct classification is not the only factor of an evasion attack. The confidence of the classifier matters as well. For example, lower confidence may indicate that the attack, though failed to fully deceive the classifier, gained some effect on the classifier and can be more easily improved into a successful attack. Each of the classes (e.g., benign and malicious) is given a rank, based on popularity among the data, target class, and the other class, or any other way of ranking. $\bar{P_i}$ represents the probability assigned to the true class \textit{i}, and $R_i$ is the rank of that class within the ordered predictions list. For the chosen class by the classifier, the $\bar{P_i}$'s range is between 0-1. For the second-best class, $\bar{P_i}$'s range is between 0-0.5, as if it was more than 0.5, it was the chosen class. The other classes will follow a similar rule. The ranks in the case of a binary classification are 1 and 2, where 1 is the highest rank. The ranks in this paper will be picked as 1 to be the right class of the sample, and 2 for the wrong class. Each rank will have a range. The ranges should not overlap as well, as $\bar{P_i}$ will be mapped to a $R_i$'s range. The range of the first rank is between 0.5-1. The second rank will be between 0.33-0.5, and so on. The DRR is calculated in Eq.~\ref{drr_eq}, for a sample $x$: \begin{equation} \label{drr_eq} DRR(x)=\frac{\bar{P_i}}{R_i+1}+\frac{1}{R_i+1} \end{equation} The first element maps the range of $\bar{P_i}$ to a range in the size of the $R_i$'s range. The second element adds the lower bound of the $R_i$'s range. A sum of both maps $\bar{P_i}$ to the actual range of $R_i$. Therefore, the overall DRR of a classifier $CL$ on a set of samples $X$ is defined in Eq.~\ref{drr_total_eq}: \begin{equation} \label{drr_total_eq} Overall\_DRR(CL,X)=\frac{\Sigma_{x \in X}DRR(x)}{|X|} \end{equation} \textbf{Model Reliability Assessment:} As the process of a binary classification goes, for each test sample, the model outputs a probability of the target class. The second class holds the complement probability. For each test sample, the entropy of the target class and second class is denoted as $s$. In other words, $s=E(P,\overline{P})$, where $E$ symbolizes the entropy function, and $P$,$\overline{P}$ are the probabilities of each class produced by the classifier. To fully evaluate the magnitude of each model, the Shannon Entropy of the probabilities is used, to generate a number that represents the reliability of the model, similarly to the approach suggested in~\cite{nguyen2020ensemble}. The reliability is based on the complement of the average entropy of a test sample. As entropy usually measures uncertainty and disorder, the reliability is calculated as the complement of the average entropy. That way, a higher score is translated as great confidence by the classifier. The reliability is defined with regards to the classifier $CL$, the set of test samples $X$ and the set of entropy $S$ for the test set $X$ using Eq.~\ref{re_eq}: \begin{equation} \label{re_eq} Re(CL,X,S)=1-\frac{S}{|X|} \end{equation} The three metrics create an advanced view of the effects of the evasion attacks. The ER metric depicts the gap in detection rates of malicious samples, between clean and manipulated apps. The DRR metric describes the effect the samples have on the certainty of the prediction function of each detection model. The Model Reliability metric concludes the analysis with the overall reliability of each detection model. As will be exampled in the next section, the following scenario can happen between two models: The first model is more affected by the evasion attacks in means of DRR compared to the second. However, the first model is more reliable in facing evasion attacks. Therefore, the DRR and Model Reliability metrics complete one another by means of a thorough analysis of the effects of the evasion attacks. \subsection{Results - Evasion Robustness } \label{former_apps_results} \begin{figure*}[t!] \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{ER}{er_clean_1nn.tex}{er_clean_3nn.tex}{er_clean_rf.tex}{er_clean_5nn.tex}{er_clean_dt.tex}{er_clean_ada.tex} \subcaption{Clean data} \label{er_clean} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{ER}{er_random_1nn.tex}{er_random_3nn.tex}{er_random_rf.tex}{er_random_5nn.tex}{er_random_dt.tex}{er_random_ada.tex} \subcaption{Manipulated data - Random StB attack} \label{er_random} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{ER}{er_full_1nn.tex}{er_full_3nn.tex}{er_full_rf.tex}{er_full_5nn.tex}{er_full_dt.tex}{er_full_ada.tex} \subcaption{Manipulated data - Full Statistical StB attack} \label{er_full} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{ER}{er_black_1nn.tex}{er_black_3nn.tex}{er_black_rf.tex}{er_black_5nn.tex}{er_black_dt.tex}{er_black_ada.tex} \subcaption{Manipulated data - Black Hole Statistical StB attack} \label{er_black} \end{minipage} \caption{ER results: Distance-based models (1-NN, 3-NN, 5-NN) and Tree-based models (RF, DT, Adaboost). The models were tested with clean data (a), and three types of manipulated data (b-d). The ER represents the detection rate of each model.} \label{er_eval} \end{figure*} \begin{figure*}[t!] \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{DRR}{drr_clean_1nn.tex}{drr_clean_3nn.tex}{drr_clean_rf.tex}{drr_clean_5nn.tex}{drr_clean_dt.tex}{drr_clean_ada.tex} \subcaption{Clean data} \label{drr_clean} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{DRR}{drr_random_1nn.tex}{drr_random_3nn.tex}{drr_random_rf.tex}{drr_random_5nn.tex}{drr_random_dt.tex}{drr_random_ada.tex} \subcaption{Manipulated data - Random StB attack} \label{drr_random} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{DRR}{drr_full_1nn.tex}{drr_full_3nn.tex}{drr_full_rf.tex}{drr_full_5nn.tex}{drr_full_dt.tex}{drr_full_ada.tex} \subcaption{Manipulated data - Full Statistical StB attack} \label{drr_full} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{DRR}{drr_black_1nn.tex}{drr_black_3nn.tex}{drr_black_rf.tex}{drr_black_5nn.tex}{drr_black_dt.tex}{drr_black_ada.tex} \subcaption{Manipulated data - Black Hole Statistical StB attack} \label{drr_black} \end{minipage} \caption{DRR results: Distance-based models (1-NN, 3-NN, 5-NN) and Tree-based models (RF, DT, Adaboost). The models were tested with clean data (a), and three types of manipulated data (b-d). The DRR represents the DRR results of each model.} \label{drr_eval} \end{figure*} \begin{figure*}[t!] \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{Model Reliability}{mr_clean_1nn.tex}{mr_clean_3nn.tex}{mr_clean_rf.tex}{mr_clean_5nn.tex}{mr_clean_dt.tex}{mr_clean_ada.tex} \subcaption{Clean data} \label{mr_clean} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{Model Reliability}{mr_random_1nn.tex}{mr_random_3nn.tex}{mr_random_rf.tex}{mr_random_5nn.tex}{mr_random_dt.tex}{mr_random_ada.tex} \subcaption{Manipulated data - Random StB attack} \label{mr_random} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{Model Reliability}{mr_full_1nn.tex}{mr_full_3nn.tex}{mr_full_rf.tex}{mr_full_5nn.tex}{mr_full_dt.tex}{mr_full_ada.tex} \subcaption{Manipulated data - Full Statistical StB attack} \label{mr_full} \end{minipage} \hspace{15pt} \begin{minipage}[t]{0.2\linewidth} \centering \TPRRes{Model Reliability}{mr_black_1nn.tex}{mr_black_3nn.tex}{mr_black_rf.tex}{mr_black_5nn.tex}{mr_black_dt.tex}{mr_black_ada.tex} \subcaption{Manipulated data - Black Hole Statistical StB attack} \label{mr_black} \end{minipage} \begin{center} \ref{barLagendName} \end{center} \caption{Model Reliability results: Distance-based models (1-NN, 3-NN, 5-NN) and Tree-based models (RF, DT, Adaboost). The models were tested with clean data (a), and three types of manipulated data (b-d). The Model Reliability of each model is presented.} \label{mr_eval} \end{figure*} The first evaluation analyzes the effect of the benign ratio on the ER. The ER metric was computed using the TPR of the malicious apps as the original detection rate was computed. Naturally, as one can expect, as the ratio of benign samples in the train set increases, the classifier will tend to focus on these samples, aiming to minimize the loss function, and the TPR will monotonically decrease. The results of the ER are split into four parts\footnote{extended version of these results and the results of the evasion attacks can be found in Github:https://github.com/harelber/The-Black-Holes-of-Markov-Chains.}, depicted in Fig.~\ref{er_eval}. First, the ER of the clean data is presented as a baseline in Fig.~\ref{er_clean}. Second, the ER of the Random StB attacks is described in Fig.~\ref{er_random}. Then, the ER of the Full Statistical StB attack is presented in Fig.~\ref{er_full}. At last, the ER of the Black Hole Statistical StB attack is depicted in Fig.~\ref{er_black}. \begin{enumerate}[a)] \item\textbf{Clean data:} The results of the ER of the clean data can be seen in Fig.~\ref{er_clean}. It can be seen that the more benign apps used, the fewer malicious apps are detected by each one of the models. The 1-NN and 3-NN models' starting points at 10\% of the benign apps (blue and red lines) are lower than the RF (green line), by $\sim$30\%. Their ending point with 100\% of the benign apps reaches almost 0\%. In other words, the RF's detection rate decreases by $\sim50$\%, and the KNNs by $\sim40$\%. The DT's (black line) starting point at 10\% of the benign apps, is a detection rate of $\sim$90\%. Moreover, this model sustains a stable detection rate. The Adaboost model (red line) shows similar detection rates to the RF, 1-NN and 3-NN, with a slight superiority over the RF model. The 5-NN model (cyan line) is less accurate than all models. It seems that the DT is the best model out of the six. \item \textbf{Random StB attack:} \label{random_stb_results} The results of the ER evaluation of the manipulated data using the Random StB attack are depicted in Fig.~\ref{er_random}. The distance-based models (1-NN, 3-NN, and 5-NN) show an interesting behavior. They have a similar detection rate along the interval of the benign ratio between the clean data and the manipulated data. In other words, the attack did not have a great effect on them. The RF model suffers from a great loss of $\sim$40\% along the interval. In other words, the attack affected the RF model dramatically. This is a change of course, as in the case of the clean data, the RF was more accurate than the 1-NN and 3-NN. The DT and Adaboost models have a similar distribution as with the clean data. However, the starting and ending points of each model in both of them are lower than the correlative points in the clean data's results. The DT model is stable and has the most effective results against the Random StB attack. However, it has an ER of less than 50\% with only 10\% of the benign apps. It falls under 40\% with 100\% of the benign apps. The Adaboost model is now as effective as the 1-NN model. \item \textbf{Full Statistical StB attack:} \label{fs_stb_results} In this case, which is depicted in Fig.~\ref{er_full}, the ER of the manipulated data by the Full Statistical StB attack is presented. The distance-based models stay the same as in previous cases. Their ER is stable, despite their low rates. The RF model continues its decrease in ER, and in this case - to $\sim$0\% on most of the interval. The DT and Adaboost models decrease their ER as well, by 20\%-30\%. \item \textbf{Black Hole Statistical StB attack:} \label{bh_stb_results} The ER results of the manipulated data by the Black Hole Statistical StB attack are depicted in Fig.~\ref{er_black}. In this case, the distance-based models stay the same as before. The ER of the tree-based models (DT, RF, Adaboost) continue their decrease in ER, and in this case - less than 10\% on most of the interval. \end{enumerate} The distance-based models show poor results with the clean data and against the evasion attacks as well. In comparison, the tree-based models show high ER with clean data. Also, the tree-based models were proven to be more susceptible to attacks than the distance-based models. An explanation for these findings is based on the split nodes function of the tree models. The node split function is effective in means of identification of malicious activity, without any manipulation. The more features it processes, the more accurate it becomes. This is true for the DT model, as the amount of benign data did not dramatically affect its detection rate. However, splitting the data between multiple weaker modules, like exampled in the Adaboost and RF models, results in a decrease in the ER. Also, the tree-based models are based on features that are often manipulated by the attack. Therefore, the ER changes according to the attacks. However, as most of the features stay similar to the clean data, the distance-based models show a similar detection rate between the baseline and the evasion attacks. \subsection{Results - Defence Reciprocal Rate} \label{drr_res} The second evaluation is of the DRR. The DRR measures how effective an evasion attack is. A higher DRR means a stronger classifier. In addition to the ER, this metric reflects the gap between the predictions on clean data and the predictions on evasion attacks. The ranks chosen for this experiment were 1 for malicious and 2 for benign, as the test data consisted of only malicious data. Therefore, the rank of 1 depicts the correct label, and a rank of 2 for a mistake. In this section, a review of the results of the models tested on clean data, and the three evasion attacks is presented. The clean data results are depicted in Fig.~\ref{drr_clean}. The DRR of the evasion attacks are presented in Fig.~\ref{drr_random}-\ref{drr_black}. \begin{enumerate} \item\textbf{Clean data: }The results of the DRR evaluation of the clean data are depicted in Fig.~\ref{drr_clean}. As with the case of the ER, the tree-based models overcome the distance-based models, considering data without any evasion attack. Also, the DT model holds the highest DRR, which depicts the most resilient model. Its DRR is more than 90\% along the interval. \item \textbf{Random StB attack:} In Fig.~\ref{drr_random}, the DRR evaluation of the manipulated data using the Random StB attack is depicted. The DRR of the distance-based models stays the same as in the clean data. The RF model's DRR suffers from a decrease of $\sim$20\% in comparison to the clean data. The DT model's DRR decreases by $\sim$30\% in comparison to the clean data. The decrease for the Adaboost model is $\sim$20\% in comparison to the clean data. The DT and Adaboost models show close results along the interval. \item \textbf{Full Statistical StB attack:} In Fig.~\ref{drr_full}, the DRR of the manipulated data by the Full Statistical StB attack is presented. The distance-based models stay with a steady DRR as before. The Adaboost model shows surprising results, similar to the DRR of the Random StB attack. In other words, the attacks had a similar effect on the DRR of the Adaboost model, in contrast to the DT model, which decreased by an additional 10\% in comparison to the Random StB attack. This might raise an alert that the DT model is less reliable than the Adaboost model. However, the next section on the Model Reliability metric will answer this question. The RF model suffers from another DRR decrease, of $\sim$10\% in comparison to the Random StB attack. \item \textbf{Black Hole Statistical StB attack:} The DRR evaluation of the manipulated data by the Black Hole Statistical StB attack is depicted in Fig.~\ref{drr_black}. The distance-based models, the DT and Adaboost models present identical DRR to the Full Statistical StB attack. The starting point of the RF is lower than its correlative starting point in the Full Statistical StB attack. \end{enumerate} The distance-based models showed similar DRRs in each case explored, as in the ER metric. The evasion attacks had a similar effect on the DRR of the Adaboost model, in contrast to the DT model, which decreased by 50\% in the case of the Random StB attack, and an additional 20\% in the Full and Black Hole Statistical attacks. These findings raise the need to investigate if the Adaboost model is more effective than the DT model and if the Adaboost model is more reliable. The next section on the Model Reliability metric will answer these inquiries. \subsection{Results - Model Reliability Assessment} \label{mra_res} The reliability of each model was inspected, to understand the confidence of each model on the predictions. High reliability means that the gap between the two classes is great. A low value means that the classes are close to being indistinguishable. This does not influence the ER, as a classifier with a low detection rate can be "confident" in its predictions. Also, a "lucky" classifier can have a high detection rate, but the probabilities of each class may be close. The assessment was done on four cases - clean data and the manipulated data by the three evasion attacks - to compare the changes the attacks have on the classifiers. The assessment is depicted in Fig.~\ref{mr_eval}. As the reliability assessment results are similar between the four cases - clean data and manipulated data - they will be discussed without specific references to each one of the subfigures. It can be seen that the 1NN model is reliable, as its reliability is 1 on the whole interval, for each one of the cases. The reliability of the DT model is also found to be very high, as its reliability receives the value of 1 along whole the interval for each one of the cases. The reliability of the Adaboost model was found to be a constant value of 0.3 along the interval, for each one of the cases. The Model reliability rates of the other models - 3NN, 5NN, and RF are increasing throughout the interval. The increasing reliability of the 3NN and 5NN models is similar in the four cases. The RF model is found to be more reliable in the cases of evasion attacks than the clean data. In other words, it is more "confident" in its labels of the evasion attacks than the clean data. Both the 1NN and DT models show a constant high value of model reliability, with a value of 1. In contrast, the Adaboost model has a constant value of 0.3. As these phenomena were surprising, a close examination of the probabilities of each class for these models was done. It was found that for the 1NN and DT models, the probabilities are binary for each sample, without any regard to the benign ratio of the apps. For the Adaboost model, both probabilities on each sample were close to 0.5. Therefore, the entropy is high in the results of the Adaboost model, and low in the results of the 1NN and DT models, which outcomes in correlative complement Model Reliability rates. Therefore, it was found that although the Adaboost model had better DRR than the DT model against the evasion attacks, its reliability is far worse. The DT model was found as the most promising model out of the six, based on the combined insights of the ER, DRR, and Model Reliability metrics. Four important insights are derived from the combination of the results of the ER, DRR, and Model Reliability: \begin{enumerate} \item The most promising model tested on the clean data and the evasion attacks is DT. However, this model is susceptible to evasion attacks. \item The distance-based models were not much affected by the evasion attacks. However, their detection rate is low in the baseline and any evasion attack. \item The ER and DRR results proved that the Random StB attack is less effective than the Full Statistical and the Black Hole Statistical attacks. For example, for the DT model, the DRR of the clean data was 80\%-90\%. On the Random StB attack, the DRR was 50\%-60\%. However, the DRR decreased to 40\% and less in the cases of the Statistical StB attack and Black Hole Statistical attack. Also, the ER supports this conclusion. This insight is pretty intuitive as a random attack is not specifically targeting the data the model is built upon. In comparison, the Full Statistical StB attack requires the train data to generate the attack. However, it was important to establish this insight by viewing the results. In addition, the Black Hole Statistical StB attack got similar results to the Full Statistical StB attack but needs less information - only the test data. Therefore, it can be considered the best attack out of the three. \item A lower DRR does not necessarily means a less effective model. As proven, the DT model had a lower DRR in the case of the Full and Black Hole Statistical StB attacks than the Adaboost model, which had a similar DRR for each attack. However, the ER and Model Reliability showed the full picture, in which the Adaboost model is less reliable and robust than the DT model. \end{enumerate} A more robust version of MaMaDroid can be suggested, due to the effect of the ratio of benign apps on the detection of malicious apps and evasion attacks. This version should use the most effective model that was found - DT. However, using the existing DT model is not enough, as it is susceptible to StB attacks. The next section will demonstrate a suitable solution for the holes in the model. \section{MaMaDroid2.0} \label{mama2} As suggested in the previous section, DT was found to be the most effective and reliable model for MaMaDroid. However, the DT model was found to be vulnerable to StB attacks. The distance-based models were found to be robust against the evasion attacks, but their original detection rates were low. A stronger version of MaMaDroid can be suggested due to these findings. As even the strongest model, DT was evaded by the StB attacks, there is still room for improvement. An extension of the feature set might help to mitigate the attacks, thus creating a hybrid approach. One of the influential works on Android malware detection is Drebin~\cite{arp2014drebin}. This work laid the foundations for ML Android malware detection which is based on static analysis. This system is based on eight feature sets. For the extension of MaMadroid, one of the feature sets was picked - the required permissions set. Permissions are a great candidate for a feature set of Android malware detection systems over the years, as a full feature set of a detection machine or a part of it (i.e.~\cite{arora2019permpair,aswini2014droid,ding2021hybrid,enck2009lightweight,li2018significant,pierazzi2020problemspace,sanz2013puma,talha2015apk}). Therefore, the required permissions set was picked to enhance MaMaDroid. It will be termed as \textit{permission set}. An analysis of the permission set of the dataset (the same dataset as Section~\ref{eval}) resulted in several insights. First, using the full permission set from the dataset will increase the size of the feature set. Second, the less frequent permissions will not affect the detection process as their weight will be low. Moreover, an analysis of the rare permissions found that they were custom permissions~\cite{Android_permissions_cust} used on a few apps. Therefore, only the frequently requested permissions in the dataset were included in the permission set, in over 10\% of the data, both benign and malicious\footnote{To assess the applicability of the permission set for other datasets, a subset of 4K malicious apps and 2K benign apps of MaMaDroid1.0 dataset was analyzed as well. The permission set that was extracted had an intersection of more than 87\% with the permission set that was used in this paper. This proved that the permission set, though needs to be updated from time to time, can be useful for the classification of other datasets as well.}. MaMaDroid 2.0, the enhanced version of MaMaDroid, follows the following steps: \begin{enumerate} \item Run MaMaDroid1.0's feature extraction on the app to get MaMaDroid1.0's feature set. \item Extract the permission set from each app by exploring its Manifest file. Filter the less frequently requested permissions. \item Merge the two feature sets. \item Run the model on the merged feature set and get a classification of the app. \end{enumerate} The following sections include the experimental design of MaMaDroid2.0 (Section~\ref{2_set}), and the results (Section~\ref{2_res}) \subsection{Experimental Design} \label{2_set} Several experiments were done to assess the power of MaMaDroid2.0. The dataset for these sets of experiments consisted of the dataset from Section~\ref{eval}, using 100\% of the benign apps. As will be seen in the results, using 100\% of the benign apps does not damage the effectiveness of MaMaDroid2.0, concerning the classification of benign and malicious apps. This set of experiments tested the effectiveness of the new detection machine, both on clean data and manipulated data. It was done to see if the addition of features damaged the correct classification of benign or malicious data. In each experiment, the DT model was tested, which was proven to be the best model in Section~\ref{eval}. Each test case consisted of benign and malicious data, where the malicious data changed according to the specific case. The model was tested in terms of f1-score and recall, to test its correct detection as a whole, and specifically the malicious samples. As most of the test set is benign, it is pretty easy to detect benign apps as benign, using the trivial labeling of the whole test data as benign. Therefore, the recall metric was used, to identify the correct classification of malicious samples. The F1 metric was used to see the effect of the precision and recall together, so as to see the false positives rate on the new machine along with the recall. Furthermore, as MaMaDroid2.0 incorporates the permission set as part of its feature set (as used in Drebin~\cite{arp2014drebin}), attacks against Drebin~\cite{berger2021crystal} were tested as well, to see if the new machine is strong against these attacks as well. Each experiment is described by the test data and feature set, as the train data stays the same. The settings are described in Table~\ref{exp_table}. \begin{table} \begin{tabular}{|c|c|c|c|c|c|} \hline Exp & Clean&Manipulated&StB&MB~\cite{berger2021crystal}&Feature Set\\ \hline 1 & \checkmark&\checkmark&\checkmark&&Base\\ \hline 2 & \checkmark&\checkmark&\checkmark&&Ext\\ \hline 3 & \checkmark&\checkmark&\checkmark&&Perm\\ \hline 4 & \checkmark&\checkmark&&\checkmark&Ext\\ \hline 5 & \checkmark&\checkmark&&\checkmark&Perm\\ \hline \end{tabular} \caption{MaMaDroid2.0 experiments settings. Each experiment is described by the data it incorporates - clean and manipulated data, the evasion attack that created the manipulated data (StB/MB~\cite{berger2021crystal}). Also, the and the feature set that was used is presented - the basic MaMaDroid1.0 feature set (Base), the extended feature set of MaMaDroid2.0 (Ext), and the permission set (Perm).} \label{exp_table} \end{table} The results of these five experiments are presented in Section~\ref{2_res}. \subsection{Results - MaMaDroid2.0} \label{2_res} The results of the first three experiments of MaMaDroid2.0 are presented in Table~\ref{res_mama2_stb}. It can be seen that the recall of the baseline of DT, as was seen in the results of the former experiments (Section~\ref{eval}), is 0.84 using clean data. Additionally, the recall of the StB attacks is lower than 0.3. However, adding the permission set thus using the enhanced feature set, raises the recall of each case to 0.9 or more. The f1-score of each case using this extended feature set is more than 0.96. In comparison, in the baseline, the f1-score is 0.89 with the clean data and less than 0.66 with the manipulated data. Using only the permission set achieves a close recall and f1-score rates to the enhanced feature set of MaMaDroid2.0. \begin{table} \begin{tabular}{|l|c|c|c|c|c|c|c|c|} \hline \multicolumn{1}{|c|}{Cases} & \multicolumn{2}{c|}{Clean} & \multicolumn{2}{c|}{Random} & \multicolumn{2}{c|}{Full} & \multicolumn{2}{c|}{Black}\\ \cline{2-9} \multicolumn{1}{|c|}{FS} & R & F1 & R & F1& R & F1 & R & F1\\ \hline Base & 0.84 &0.89&0.27&0.65&0.07 &0.52&0.05&0.51\\ \hline Ext& 0.96 & 0.97&0.92&0.97 &0.9 &0.96&0.9&0.96 \\ \hline Perm & 0.91&0.95&0.92 &0.95 &0.92&0.95&0.92&0.96\\ \hline \end{tabular} \caption{MaMaDroid 2.0 Recall (R) and F1 metrics for the experiments with the StB attacks. The Feature sets (FS) include the original MaMaDroid features (Base), extended feature set (Ext), and permission set only (Perm). The cases inspected are clean data (Clean), Random StB attack (Random), Full Statistical StB attack (Full), and Black Hole Statistical StB attack (Black).} \label{res_mama2_stb} \end{table} These results may raise the question: What is the importance of the MaMaDroid1.0 feature set if the permission set alone can be used as a standalone to identify evasion attacks? The answer lies in Table~\ref{res_mama2_mb}. The MB attacks show a great impact on a model that is based on the permission set. The highest recall using the permission set only is against MB1, with a value of 0.49. The other MB attacks achieve recall values of 0. In comparison, the enhanced feature set achieves high recall values, at least 0.97, for each case - clean data and manipulated data. This proves that a model that analyzes only the permission set cannot identify evasion attacks that manipulate permissions. In contrast, MaMaDroid2.0 succeeds in this task. In conclusion, it was proven that the enhanced feature set of MaMaDroid2.0 creates a stronger model. This model was proved to identify attacks against both MaMaDroid and Drebin alike. \begin{table} \begin{tabular}{|l|c|c|c|c|c|c|c|c|} \hline \multicolumn{1}{|c|}{Cases} & \multicolumn{2}{c|}{Clean} & \multicolumn{2}{c|}{MB1} & \multicolumn{2}{c|}{MB2} & \multicolumn{2}{c|}{MB3}\\ \cline{2-9} \multicolumn{1}{|c|}{FS} & R & F1 & R & F1& R & F1 & R & F1\\ \hline Ext & 0.97 &0.93&0.98&0.92&0.98 &0.92&0.97&0.91\\ \hline Perm& 0.92 & 0.95&0.49&0.79 &0 &0.47&0&0.46 \\ \hline \end{tabular} \caption{MaMaDroid 2.0 Recall (R) and F1 metrics for the experiments with the MB attacks. The Feature sets (FS) include the extended feature set (Ext) and permission set only (Perm). The cases inspected are clean data (Clean), MB1 attack (MB1), MB2 attack (MB2), and MB3 attack (MB3).} \label{res_mama2_mb} \end{table} \section{Discussion and Conclusion} \label{diss} The original MaMaDroid was based on a specific ratio between benign and malicious applications. The original ratios were between 50\%-50\%, or with a tendency toward the malicious class. As a recent study suggested~\cite{pendlebury2018tesseract}, the realistic ratio in the world between benign and malicious apps is leaning toward the benign class. More specifically, it is 90\%-10\% between benign and malicious apps. As a consequence, the number of benign apps was tested in this research to derive their influence on the ER. As was seen, the ratio did have an impact on each one of the models that were tested. In addition, the StB evasion attacks decreased the tree-based models' ERs. The distance-based models proved to be strong against the attacks, but their detection rates were already low on the clean data (and stayed there on the manipulated data by attacks). The DT model was found to be the best model by means of ER. It was also found to be very reliable, even in the most challenging ratio of more than 90\% of the dataset being benign apps. For all of the above, it was suggested to replace the former models of MaMaDroid with a DT. In addition, the merged feature set upgraded the total effectiveness of the model. Adding the enumeration of permission requests, which are a small amount of data, aids the identification of malicious activities. Other additions to the feature set may help in this task, such as suspicious API calls or intents. These directions are left as future work. Most mitigation techniques to evasion attacks try to find the trail, the attacks leave and identify them. With other attacks, the effect may be eliminated by preprocessing. For example, adding no-operation calls to CFG based detection machines, like in~\cite{chen2018android}. In regards to the StB attacks, the flow of the attack does not add actual code to the app, just a replacement of references to classes names, and moving parts of the application between places. Moreover, in the Full/Black Hole Statistical StB attacks, there is only an addition of a new root directory to the app. A mitigation technique that might succeed in some of the cases is looking for duplication of a name of a directory. For example, if the former root directory of the app is "android" and after the evasion attack now the root directory is also "android", there will be two android directories, one below the other. A quick check for such a case will result in an alert for the StB case. However, not every app's root directory is similar to the new root directory which is picked by the attacker. Therefore, the StB attacks are still a threat to malware detection machines that are based solely on CFG. MaMaDroid is an excellent example of using the CFG to identify behaviors of benign and malicious APKs. In general, a CFG of a software tries to organize the order of commands the software runs. A malware detection machine that is based on a CFG tries to find the differences between the order of commands in malicious and benign apps to address the task of the classification of new samples. As the experiments in this study showed, a shift in the order of commands can cause a miss-classification. For example, the Black Hole StB variant demonstrates the effect of moving some of the commands from the malicious order of commands to an unknown order of commands. In other words, the order turns to chaos. The different variants modify the order of commands in an app, which results in the alteration of its CFG. When the new CFG is inspected by the detection machine, it is puzzled. This course of action can be generalized to other domains as well. Therefore, the CFG-based detection machines are now faced with the following challenge: Are they secure enough against the ominous chaos that will arrive? It seems that an extension of the feature set or a hybrid approach may aid in dealing with this issue. The combination of different features seems a promising step towards more accurate solutions against multiple types of malware that are exploiting different vulnerabilities. \section{Acknowledgment} This work was supported by the Ariel Cyber Innovation Center in conjunction with the Israel National Cyber Directorate of the Prime Minister's Office. The authors will like to thank Dr. Lucky Onwuzurike for his technical aid with MaMaDroid. \bibliographystyle{plain}
{'timestamp': '2022-03-01T02:55:19', 'yymm': '2202', 'arxiv_id': '2202.13922', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13922'}
arxiv
\subsubsection*{References}} \usepackage{mathtools} \usepackage{booktabs} \usepackage{tikz} \usepackage{microtype} \usepackage{graphicx} \usepackage{subfigure} \usepackage{booktabs} \usepackage{url} \usepackage{amsmath,amsfonts,bm} \usepackage{amsthm,amssymb} \usepackage{bbm} \usepackage{diagbox} \usepackage{booktabs} \usepackage{color} \usepackage{xcolor} \definecolor{darkblue}{RGB}{25, 50, 112} \usepackage{float} \usepackage{lipsum} \usepackage{amsmath,amsfonts,amssymb} \usepackage{booktabs} \usepackage{graphicx} \usepackage{hyperref} \usepackage{url} \usepackage{newtxmath} \usepackage{enumitem} \usepackage{multirow} \usepackage{tablefootnote} \usepackage{bbm} \usepackage{wrapfig} \usepackage{nicefrac} \usepackage{chngcntr} \newcommand{\ell}{\ell} \newcommand{\arabic{algorithm}}{\arabic{algorithm}} \usepackage{amsmath} \usepackage{amssymb} \usepackage{mathtools} \usepackage{amsthm} \usepackage[capitalize,noabbrev]{cleveref} \theoremstyle{plain} \newtheorem{theorem}{Theorem}[section] \newtheorem{proposition}[theorem]{Proposition} \newtheorem{lemma}[theorem]{Lemma} \newtheorem{corollary}[theorem]{Corollary} \theoremstyle{definition} \newtheorem{definition}[theorem]{Definition} \newtheorem{assumption}[theorem]{Assumption} \theoremstyle{remark} \newtheorem{remark}[theorem]{Remark} \newcommand{\tocite}[1]{\textcolor{gray}{cite #1}} \DeclareMathOperator{\KL}{KL} \DeclareMathOperator*{\argmax}{arg\ max} \newcommand{\prob}[1]{\mathbb{P}\left(#1 \right)} \newcommand{\probt}[1]{\mathbb{P}_t\left(#1 \right)} \title{Resolving Label Uncertainty with Implicit Posterior Models} \author[1,6]{\href{mailto:<mailto:[email protected]>}{Esther~Rolf}} \author[2,6]{Nikolay~Malkin} \author[3,6]{Alexandros~Graikos} \author[4]{Ana~Jojic} \author[5]{Caleb~Robinson} \author[6]{Nebojsa~Jojic} \affil[1] University of California, Berkeley, CA, USA } \affil[2] Mila and Universit\'e de Montr\'eal, Montr\'eal, QC, Canada } \affil[3]{ Stony Brook University, Stony Brook, NY, USA } \affil[4]{ Paul G. Allen School of Computer Science and Engineering, University of Washington, Seattle, WA, USA } \affil[5]{ Microsoft AI for Good, Redmond, WA, USA } \affil[6]{ Microsoft Research, Redmond, WA, USA } \begin{document} \maketitle \begin{abstract} We propose a method for jointly inferring labels across a collection of data samples, where each sample consists of an observation and a \emph{prior belief} about the label. By implicitly assuming the existence of a generative model for which a differentiable predictor is the posterior, we derive a training objective that allows learning under weak beliefs. This formulation unifies various machine learning settings; the weak beliefs can come in the form of noisy or incomplete labels, likelihoods given by a different prediction mechanism on auxiliary input, or common-sense priors reflecting knowledge about the structure of the problem at hand. We demonstrate the proposed algorithms on diverse problems: classification with negative training examples, learning from rankings, weakly and self-supervised aerial imagery segmentation, co-segmentation of video frames, and coarsely supervised text classification. \end{abstract} \section{Introduction} In prediction problems, coarse and imprecise sources of input can provide rich information about labels. Negative labels (what an instance is \emph{not}), rankings (which of two instances is larger), or coarse labels (aggregated by taxonomy or geography) give clues on what the ground truth label of an instance \emph{might} be, but not what it \emph{is} directly. We consider a collection of data samples, indexed by $i$, consisting of observations (features) $x_i$ and corresponding sample-specific \emph{prior beliefs} about their latent label variables, $p_i(\ell)$. This paper proposes algorithms to \textbf{resolve the uncertainty in these prior beliefs} by jointly inferring an assignment of target labels $\ell_i$ and a model that predicts $\ell_i$ given $x_i$. Partial or aggregate annotations and auxiliary data sources are often more widely available and convenient to collect than ``ground-truth" or high-resolution labels, but they are not readily used by discriminative learners. Supervision from probabilistic targets can result in uncertain predictions (\S\ref{sec:background_and_approach}). Most approaches to resolve these uncertainties involve iterative generation of hard pseudolabels~\citep{zhang2021refining} or loss functions promoting low entropy of predictions~\citep{nguyen2008classification,yu2016maximum,zou2020pseudoseg,yao2020ambiguous}. Typically, these approaches are application-specific \citep{han2014object,zheng2021Weakly,bao2021MRTA,li2021Change}. In many settings, fusing weak input data into a probability distribution over classes is a more natural alternative to transforming the weak input into hard labels~\citep{mac2019presence}. Further connections and comparisons to prior work are made throughout this paper and synthesized in \S\ref{sec:related_work_extras}, \S\ref{sec:implicit_details}. Our key modeling insight (\S\ref{sec:implicit_posterior_model}) is to identify the output distribution of a discriminative model, a feed-forward neural network $q$, with an approximate posterior over latent variables in an \emph{generative} model of features, of which the given prior belief is a part. Bayesian reasoning about the generative model and its posterior makes it possible to learn the inference network \emph{without instantiating the full generative model}, while reaping the benefits of generative modeling: high certainty in the posterior under soft priors and rich opportunities to model structure in the prior beliefs. Prior beliefs about labels can arise from many sources (\S\ref{sec:priors}). We validate the effectiveness of our approach with experiments (\S\ref{sec:experiments}, \S\ref{sec:additional_exp}) on multiple domains and data modalities that highlight: prior beliefs as a natural way to fuse weak inputs, graceful degradation of performance with increasingly noisy or incomplete inputs, and comparison with explicitly generative modeling approaches. \begin{figure*}[t] \centering \hspace{-4mm} \setlength{\fboxrule}{2mm} \definecolor{nicecolor}{rgb}{0.94,0.94,1.0} \definecolor{xi_color1}{rgb}{0,0,0} \definecolor{xi_color2}{rgb}{1,1,1} \fcolorbox{white}{white}{ \hspace{-1em} \scalebox{1.35}{ \includegraphics[width=0.105\textwidth,trim=0 160 0 0,clip]{figures/mnist4.png} \hspace{-16.5mm}\raisebox{15mm}{\textcolor{xi_color2}{$x_i$}\hspace{13mm}} \includegraphics[width=0.125\textwidth,trim=0 0 0 180,clip]{figures/mnist4.png} \includegraphics[width=0.105\textwidth,trim=0 160 0 0,clip]{figures/mnist2.png} \hspace{-16.5mm}\raisebox{15mm}{\textcolor{xi_color2}{$x_i$}\hspace{13mm}} \includegraphics[width=0.125\textwidth,trim=0 0 0 180,clip]{figures/mnist2.png} \includegraphics[width=0.105\textwidth,trim=0 160 0 0,clip]{figures/mnist1.png} \hspace{-16.5mm}\raisebox{15mm}{\textcolor{xi_color2}{$x_i$}\hspace{13mm}} \includegraphics[width=0.125\textwidth,trim=0 0 0 180,clip]{figures/mnist1.png} } \hspace{-1em} } \vspace{-1em} \\ \begin{tabular}{@{}c@{\hspace{8pt}}c@{\hspace{8pt}}c@{}} \hline \vspace{-0.5em}\\ \includegraphics[width=0.31\textwidth]{figures/seducer_v1_img_annotated.pdf} \hspace{-48mm}\raisebox{27mm}{\textcolor{xi_color1}{\huge $x_i$}\hspace{45mm}} & \includegraphics[width=0.31\textwidth]{figures/seducer_v1_prior.png}\hspace{3mm} & \includegraphics[width=0.31\textwidth]{figures/seducer_v1_q.png}\\ (a) $\{x_i\}$: \textit{Le s\'educteur}, Ren\'e Magritte & (b) $p_i(\ell)$: \textit{Boat Prior}, anonymous artist & (c) $q_i(\ell)$: Inferred segmentation \end{tabular} \caption{\textbf{Above:} Inference of latent MNIST digit classes with negative label supervision using a small CNN trained on the \textbf{RQ} criterion (\S\ref{sec:implicit_posterior_model}). \textbf{Below:} (a) Joint inference of latent pixel classes in an image. (b) Prior beliefs $p_i(\ell)$ over three classes -- sky (red), boat (green), water (blue) -- are manually set. (c) A small CNN trained on $(x_i, p_i(\ell))_i$ infers the posterior classes.} \label{fig:examples} \end{figure*} \section{Background and approach} \label{sec:background_and_approach} \paragraph{Two motivating examples.} Two illustrative examples are shown in Fig.~\ref{fig:examples}. In the first example, the $x_i$ are 784-dimensional vectors representing 28$\times$28 MNIST digits. We aim to infer the digit classes $\ell_i \in \{0,1,...,9\}$ for all images in the given collection based on data in which we are given just one \emph{negative} label per sample, i.e., the prior beliefs $p_i(\ell)$ (top row) are uniform over all classes except for one incorrect class. The procedure described in this paper produces inferred distributions over labels (bottom row) that are usually peaky and place the maximum at the correct digit 97\% of the time (see Fig.~\ref{fig:mnist_cifar} and \S\ref{sec:negative_labels}). In the second example, the observations $\{x_i\}_{i \in \textrm{pixels}}$ are image patches centered around each pixel coordinate $i$ in a Surrealist painting, with patch size ($11\times11$) equal to the receptive field of a 5-layer convolutional neural network used in our inference procedure. The prior beliefs $p_i(\ell)$ are distributions over 3 classes (sky, boat, water) depending on the coordinate $i$. The joint inference of all labels in this image yields a feasible segmentation despite the high similarity in colors and textures (see \S\ref{sec:seducer} for more details). These examples illustrate the problem of training on weak beliefs, which is often encountered in some form in machine learning. Weak supervision, semi-supervised learning, domain transfer, and integration of modalities are all settings where coarse, partial, or inexact sources of data can provide rich information about the state of a prediction instance, though not always a ``ground truth'' label for each instance. An inference technique that uses weak beliefs as the sole source of supervision needs to estimate statistical links between observations $x_i$ and corresponding latents $\ell_i$. These links should simultaneously be highly confident (i.e., lead to low entropy in the posterior distributions) and explain the varying prior beliefs, which typically have low confidence (high entropy in the prior distributions). \paragraph{Supervised learning on prior beliefs.} Supervised learning models, including many neural nets, are typically trained to minimize the cross-entropy $-\sum_i\sum_\ell p_i^d(\ell)\log q_i(\ell)$ between a ``hard" distribution over labels with $p_i^d(\ell) \in \{0,1\} $ and the distribution $q_i(\ell)=q(\ell| x_i;\theta)$ output by a predictor $q$ using data features $x_i$. This is equivalent to minimizing the KL divergence $\sum_i \KL(p^d_i \| q_i)$, minimized when the two distributions $p^d_i(\ell)$ and $q_i(\ell)$ are equal. Thus, when $p^d_i(\ell)$ is a ``softer" prior over latent labels, $p_i(\ell)$, the trained model $q$ will reflect this, and also be highly uncertain. Transforming soft labels into hard training targets, (e.g. training on $\mathbbm{1}[\ell=\argmax_\ell p^d_i(\ell)]$ ), can introduce the opposite bias. In these cases, the cost would be minimized by predictions with zero entropy, but learning such a prediction function faces difficulty with overconfident labels which are often wrong, and the possibility that certain labels often receive substantial weight in the prior, but never the maximum. These issues are illustrated in Fig.~\ref{fig:sammamish_loss_comparison}. \paragraph{Generative modeling resolves the prior's uncertainty.} The approach to classification problems through \emph{generative} modeling, instead of targeting the conditional probability of latents given the data features, assumes that there is a forward (generative) distribution $p(x_i|\ell)$ and optimizes the log-likelihood of the observed features, $\sum_i \log(x_i)=\sum_i \log \sum_\ell p(x_i|\ell)p_i(\ell)$, with respect to the parameters of that distribution. The posterior under the model $q(\ell|x_i)\propto p(x_i|\ell)p_i(\ell)$ is then used to infer latent labels for individual data points \citep{seeger}. The generative modeling approach does not suffer from uncertainty in the posterior distribution over latents given the input features, even when the priors $p_i(\ell)$ are soft. (Recall that the posterior distributions in a mixture of high-dimensional Gaussians are often peaky even when the priors are flat.) However, expressive generative models are typically harder and more expensive to train compared to supervised neural networks, as they often require sampling (e.g., sampling of the posterior in variational auto-encoders \cite[VAEs;][]{kingma2014auto} and sampling of the generator in GANs \citep{gan}). Furthermore, the modeling often requires doubling of parameters to express both the forward (generative) model \emph{and} the reverse (posterior) model. And, in case of GANs, the learning algorithms may not even cover all modes in the data, which would prevent joint inference for \emph{all} data points. (See \S\ref{sec:implicit_details} for further discussion. \subsection{\mbox{Optimizing implicit posterior models}} \label{sec:implicit_posterior_model} Suppose that there exists a generative model $p(x|\ell)$ of observed features conditioned on latent labels. Optimization of the log-likelihood of observed features, $\sum_i\log p(x_i)=\sum_i\log(\sum_\ell p(x_i|\ell)p_i(\ell))$, can be achieved by introducing a variational posterior distribution $q(\ell|x_i)$ over the latent variable for each instance $x_i$ and minimizing the free energy (a negated evidence lower bound (ELBO)), defined as \begin{equation} - \sum_i\sum_\ell q(\ell|x_i)\log\frac{p(x_i|\ell)p_i(\ell)}{q(\ell|x_i)} \geq-\sum_i \log p(x_i). \label{eq:free_eng} \end{equation} Minimizing the free energy involves estimating both the forward distributions $p(x_i|\ell)$ and the posteriors $q(\ell|x_i)$. One could parametrize both $p(x|\ell)$ and $q(\ell|x)$ as functions $p(x|\ell,\theta_p)$ and $q(\ell|x,\theta_q)$ using neural networks, as done by VAEs (although VAEs use continuous latent variables $\ell$ and do not involve sample-specific priors). However, in our algorithms, we only parametrize $q(\ell|x; \theta)$ as a neural network taking input $x$ and producing a distribution over $\ell$. The generative conditional $p(x_i|\ell)$ is defined only on data points $x_i$ and is calculated by minimizing \eqref{eq:free_eng} for fixed $q(\ell|x)$, subject to the constraint that $\sum_{i} p(x_i|\ell)=1$ for all $\ell$. The optimum is achieved by: \begin{equation} p(x_i|\ell)=a_{i,\ell}=\frac{q(\ell|x_i)}{\sum_j q(\ell|x_j)}~. \label{eq:aux_p} \end{equation} Here the generative conditional $p(x|\ell)$ is not fully specified for all values $x$. Rather, it is represented as a matrix of numbers $a_{i,\ell}$ describing the conditional probabilities of different values of $x_i$ given different latent labels $\ell$. The probabilities $p(x_i|\ell)$ are greater for the data points $i$ for which $q(\ell|x_i)$ is more certain, relative to how popular assignment to class $\ell$ is across data points (denominator in \eqref{eq:aux_p}). In our formulation, $q$ plays the role of a variational posterior, but \emph{implicitly}, in a generative model consisting of varying instance-specific priors $p_i(\ell)$ and a complex conditional $p(x|\ell)$ that is never fully estimated, but is instead maximized for the data points studied. The full link between $x$ and $\ell$ is left entirely to the neural network $q$ to capture explicitly. In variational methods, the free energy (\ref{eq:free_eng}) is usually rewritten as $\sum_i {\rm KL}(q(\ell|x_i)\|r_i(\ell)))-\log p(x_i)$, where $r$ is the posterior of the forward model, i.e., for the points $i$, $r_i(\ell) \propto p_i(\ell)p(x_i|\ell)$. The minimization of free energy then reduces to minimizing the KL divergence between $r$ and $q$. We define $q_i(\ell)=q(\ell|x_i;\theta)$. After our reduction of $p(x_i|\ell)$ to the auxiliary matrix in \eqref{eq:aux_p}, the posterior $r$ has the form \begin{equation} r_i(\ell) = c_i \cdot p_i(\ell) p(x_i|\ell) = c_i \frac{p_i(\ell)q_i(\ell)}{\sum_j q_j(\ell)}~, \label{eq:true_post} \end{equation} where $c_i$ are scalars making $\sum_\ell r_i(\ell) = 1$. For each instance $i$ we have two outputs: the direct model outputs of the variational posterior $q_i$ and their \emph{implied posterior} $r_i$, which is computed by multiplying the renormalized model outputs with the provided prior at each instance as in \eqref{eq:true_post}. Using these two outputs, we can optimize a single set of model parameters $\theta$ to minimize \eqref{eq:free_eng}: \begin{align} \label{eq:KL_written_out} & \min_\theta \sum_i \text{KL}( q_i \| r_i) = \\[-4em] & \min_\theta \sum_i \text{KL}\bigg( \underbracket{\Big(q(\ell|x_i;\theta)\Big)_\ell }_{ \substack{\text{model output } \\ \text{with input $x_i$}}} \Big\| \Big( c_i \cdot\hspace{-2mm} \overbracket{p_i(\ell) \vphantom{\dfrac{q(|)}{\sum_jq(|)}} }^{ \substack{\text{per-} \\ \text{\phantom{p}instance\phantom{p}} \\ \text{priors}}} \overbracket{\frac{q(\ell | x_i; \theta)}{\sum_j q(\ell | x_j; \theta)}}^{ \substack{ \text{model output} \\ \text{\phantom{p}normalized\phantom{p}} \\ \text{per-class} \\ \text{as in Eq.~\eqref{eq:aux_p}} }} \Big)_\ell \bigg) \nonumber ~. \end{align} While \eqref{eq:KL_written_out} optimizes the free energy \eqref{eq:free_eng} by minimizing $\textrm{KL}(q_i \| r_i)$, minimizing $\textrm{KL}(r_i \| q_i)$ would also find solutions for which the direct model and its implied posterior are close. We propose to optimize either of these two objectives with respect to the model parameters $\theta$ by gradient steps. We iterate over data instances $x_i$ with priors $p_i(\ell)$: \begin{enumerate}[label*=(\arabic*)] \item Calculate the distributions $r_i$ in terms of $q_i$ as in (\ref{eq:true_post}). \item {Update the parameters of $q$ with a gradient step: \\ \mbox{$\bullet$ Option \textbf{QR}: $\theta \leftarrow \theta -\eta \nabla_\theta \sum_i \KL(q_i \| r_i)$.}\\ \mbox{$\bullet$ Option \textbf{RQ}: $\theta \leftarrow \theta -\eta \nabla_\theta \sum_i \KL(r_i \| q_i)$.} } \end{enumerate} Gradients of the objectives are propagated to the expression of $r_i$ through $q_i$ (see (\ref{eq:KL_written_out}) and Fig.~\ref{fig:qr_losses_torch}). Both losses have a stable point when $q_i=r_i$, and \textbf{RQ} reduces to the cross-entropy loss in the case of priors which put all mass on one label (e.g. $p_i(\ell) = \mathbbm{1}[\ell = \ell_i]$). A discussion of the relative benefits and limitations of the \textbf{QR} and \textbf{RQ} losses is given in \S\ref{sec:practical_considerations}, along with practical considerations for implementation. \begin{figure}[t] \centering \includegraphics[width=0.48\textwidth]{figures/qr-losses-torch.png} \caption{Cross-entropy and implicit \textbf{QR} / \textbf{RQ} losses in PyTorch. The normalization in (\ref{eq:aux_p}) is done within batches, rather than across the entire dataset. In practice, this may be sufficient if batches are large and representative of the diversity in the data. Otherwise, the denominator in (\ref{eq:true_post}) may need to be updated in an online fashion.} \label{fig:qr_losses_torch} \end{figure} By defining the conditional model $p(x|\ell)$ as an auxiliary matrix of probabilities $a_{i,\ell}$ that is fit to the reverse model $q$ during learning, we avoid parametrizing both directions of the link $\ell-x$ with highly nonlinear models.\footnote {Note that the use of an auxiliary matrix $a_{i,\ell}$ is also found in expectation-maximization \citep[EM;][]{dempster1977em}, which also minimizes the free energy. However, in EM, it is the variational posterior $q(\ell|x_i)$ which is optimized as a matrix of numbers $a_{i,\ell}$ only on data points, while the \emph{generative} model $p$ is fully parametrized (see Table~\ref{tab:em_vae_comparison}).} We thus manage to keep the problem in the realm of training a single feed-forward network $q$ as a predictor of variables $\ell$, but in a way that treats the instance-specific priors $p_i(\ell)$ as they would be in generative modeling. Next, we discuss the consequences of implicitly modeling the generative model $p$ with an auxiliary distribution. Option \textbf{QR} uses the KL distance in the direction it appears in (\ref{eq:free_eng}) and thus guarantees continual improvements in free energy and convergence to a local minimum (with the exception for the effects of stochasticity in minibatch sampling). Substituting $r_i$ from (\ref{eq:true_post}), the free energy (\ref{eq:free_eng}) becomes: \begin{equation} F=\sum_{i,\ell} q_i(\ell) \log \left(\sum_{j} q_j(\ell)\right) - \sum_{i,\ell} q_i(\ell)\log \left(p_i(\ell) \right) \label{eq:QR} \end{equation} This criterion does not encourage entropy of individual $q_i$ distributions, but of their \emph{average}. The second term alone would be minimized if $q$ could put all the mass on $\argmax_\ell p_i(\ell)$ for each data point, but the first term promotes diversity in assignment of latents (labels) $\ell$ across the entire dataset. Thus a network $q$ can optimize (\ref{eq:QR}) if it makes different confident predictions for different data points. To illustrate this, consider the case when all data points have the \emph{same} prior, $p_i(\ell)=p(\ell)$. Then (\ref{eq:QR}) and the \textbf{RQ} objective are minimized when $\frac{1}{N}\sum_i q_i(\ell) = p(\ell)$. This can be achieved when $q$ learns a constant distribution $q(\ell|x_i; \theta)=p(\ell)$. But both objectives are also minimized if $q$ predicts only a single label for each data point with high certainty, but it varies in predictions so that the counts of label predictions match the prior. As demonstrated in Fig.~\ref{fig:examples} and in our experiments, avoiding degenerate solutions is not hard. We attribute this to two factors. First, the situations of interest typically involve uncertain, but varying priors $p_i(\ell)$ which break symmetries that could lead to predictors ignoring the data features $x_i$. Second, the neural networks used to model $q$, and their training algorithms, come with their own constraints and inductive biases. In fact, as discussed in \S\ref{sec:priors} and \S\ref{sec:aaai_regret}, even unsupervised clustering is possible with suitably chosen priors that break symmetry, allowing this approach to be used for self-supervised training. See also \S\ref{sec:related_work_extras}, \S\ref{sec:implicit_details} for more on relationships with other approaches. \section{Sources of label priors} \label{sec:priors} Having detailed our approach for learning from prior beliefs as weak supervision in \S\ref{sec:background_and_approach}, we now describe a range of machine learning settings where priors $p_i(\ell)$ emerge. These settings are illustrated in experiments in \S\ref{sec:experiments} and \S\ref{sec:additional_exp}. \paragraph{Negative or partial labels (\S\ref{sec:negative_labels}).} When we are given a set of equally possible labels $L_i$ for each point data point $i$, instead of a single label $\ell_i$, then we set the prior $p_i(\ell)=\frac{1}{|L_i|}\mathbbm{1}[\ell \in L_i]$. An extreme example is when one negative label is given and hence can be ``ruled out" (Fig.~\ref{fig:examples}). \paragraph{Joint labels and learning from rankings (\S\ref{sec:ranking}).} Priors may also come in the form of joint distributions over labels of multiple instances. For example, \textit{ranking supervision} -- the knowledge of which example in a pair is greater with respect to an ordering of the labels -- gives prior beliefs about \emph{pairs} of labels. Suppose our data is organized into pairs of images of digits $T_j=\{x_{j,1},x_{j,2}\}$, and for each pair we are told which image represents the digit (0--9) which is greater (or equal). This sets a prior $p(\ell_1,\ell_2)$ over pairs of labels in each pair, represented by either an upper or a lower triangular matrix, depending on which digit in the pair is known to be greater, with all nonzero entries equal to $\nicefrac{1}{55}$. We assume the underlying generative model has the form $p(x_1,x_2|\ell_1,\ell_2)=p(x_1|\ell_1)p(x_2|\ell_2)$. We aim to fit its posterior model $q(\ell|x;\theta)$. For each pair $T_j$, we have two outputs of the predictor network, $q(\ell_1|x_{j,1})$ and $q(\ell_2|x_{j,2})$, for the two images in the pair. The joint posterior under the generative model is \begin{align} r_j(\ell_1,\ell_2) &\propto p(\ell_1,\ell_2)p(x_{j,1}|\ell_1)p(x_{j,2}|\ell_2) \nonumber\\&\propto \frac{ p(\ell_1,\ell_2)q(\ell_1|x_{j,1})q(\ell_2|x_{j,2})}{ \sum_{j} q(\ell_1|x_{j,1}) \sum_{j} q(\ell_2|x_{j,2})}, \label{eq:pair_posterior} \end{align} and we can now use \textbf{QR} or \textbf{RQ} loss to fit $q(\ell_1|x_{j,1})$ to the marginal $r_j(\ell_1)$ and $q(\ell_2|x_{j,2})$ to $ r_{j}(\ell_2)$. \paragraph{Coarse data in weakly supervised segmentation (\S\ref{sec:chesapeake_experiments}, \S\ref{sec:lymphocytes}, \S\ref{sec:seducer}).} We often have side information $z$ associated to each instance $i$ that allows setting the priors $p_i(\ell)=p(\ell|z_i)$ for each point directly by hand. These include situations when we have beliefs about labels for different points, as in the \emph{Seducer} example (Fig.~\ref{fig:examples}). Interesting weak supervision settings also arise in remote sensing (\S\ref{sec:chesapeake_experiments}) and medical pathology (\S\ref{sec:lymphocytes}) applications. For example, in a task of segmenting aerial imagery into land cover classes, we often have coarse labels $c$ associated to large \emph{blocks} of pixels, but not the target labels $\ell$ for individual pixels. If the conditional $p(\ell|c)$ is known, it sets a belief about the high-resolution labels $\ell$ for pixels in a block of class $c$. \paragraph{Fusing models and data sources (\S\ref{sec:enviroatlas_experiments}, S\ref{sec:nlp}).} Auxiliary information $z$ may not always come with a known correspondence $p(\ell|z)$. In the land cover mapping problem, auxiliary information includes different modalities and resolutions (road maps, sparse point labels, etc.). While these sources can be fused into a prior by hand-coded rules, the prior may be more accurately set as the output of a model $p(\ell|z_i)$ \emph{trained} on a separate dataset of points $(\ell_i,z_i)$. This is especially useful when the data $x_i$ (imagery) is informative about the latents $\ell_i$ but is prone to domain shift problems, while the auxiliary data $z_i$ does not suffer from domain shift issues but is not sufficient on its own to predict the labels. In a text classification problem, $z_i$ might be the encoding of text $x_i$ by a pretrained language model, and $p(\ell|z_i)$ a noisy distribution over labels given by their likelihoods under the language model as continuations of a prompt. \paragraph{Priors for self-supervision (\S\ref{sec:aaai_regret}).} In \S\ref{sec:implicit_posterior_model} we discussed the pitfalls of using a constant prior $p_i(\ell)=p(\ell)$ for all data points in training models under the \textbf{QR} loss as a potential method for unsupervised clustering. However, in \S\ref{sec:aaai_regret} we give an example of \emph{joint} learning of the posterior model $q$ and an energy model (Markov random field) on the latent labels $\ell_i$ that expresses local structure of labels in an image. This results in unsupervised clusterings that are useful in downstream segmentation tasks. Such an approach is an example of a benefit of generative modeling -- the possibility of learning of a parametrized distribution over latents -- being inherited by implicit posterior models. \paragraph{Priors with latent structure (\S\ref{sec:tracking}).} Implicit posterior modeling allows building hierarchical latent structure into the prior (another benefit of classical generative models), as we demonstrate in \S\ref{sec:tracking} on a video segmentation task. The prior is an admixture of possible segmentations with a structure similar to \citet{jojic2009stel}, but using a set of mask proposals $p(\ell_i|m)$ from a Mask R-CNN model \citep{he2017maskrcnn}, indexed by a latent $m$. The prior is $p_i(\ell)=\sum_m p(\ell_i|m)p(m)$, where $p(m)$, a probabilistic selection of the masks for the admixture in the given frame, is estimated by minimizing the free energy. \section{Experiments} \label{sec:experiments} \subsection{Partial labels in MNIST and CIFAR-10} \label{sec:negative_labels} \begin{figure}[t!] \centering \includegraphics[width=0.48\textwidth]{figures/negative-mnist.png} \hfill \includegraphics[width=0.48\textwidth]{figures/negative-cifar.png} \\ \caption{Accuracies of MNIST and CIFAR-10 classifiers trained with varying numbers of negative labels per example; the lighter variant of each color and marker shows the peak accuracy over 300 training epochs. (Average of 10 runs with standard error region.)} \label{fig:mnist_cifar} \end{figure} In this experiment, we compare algorithms for learning with partial labels on two 10-class image classification datasets, MNIST and CIFAR-10. To each training example $x_i$, we randomly assign a set $N_i$ of $k$ negative labels, chosen from the 9 labels distinct from the ground truth. The prior $p_i(\ell)$ is set to be uniform over $\ell\notin N_i$ and 0 for $\ell\in N_i$. We vary $k$ from 1 (one negative label per example) to 9 (one-hot prior, full supervision). The data of $k$ negative labels carries $-\log_2(1-k/10)$ bits of label information; if $k=1$, $22\times$ less label information than in the fully supervised setting. For both datasets, the base model $q$ is taken to be a small convolutional network, with four layers of ReLU-activated $3\times3$ convolutions with stride 2 and a linear map to the 10 output logits ($\sim$33k learnable parameters for MNIST, $\sim$34k for CIFAR-10). We experiment with four training losses: \begin{itemize} \item \textbf{CE:} cross-entropy between predictions $q(\ell|x_i;\theta)$ and the prior $p_i(\ell)$. \item \textbf{NLL (union):} negative logarithm of the sum of likelihoods assigned by $q$ to labels in $\ell\notin N_i$, or, equivalently, $\log\sum_\ell p_i(\ell)q(\ell|x_i;\theta)$, as done, e.g., by \citet{jin2002learning,nlnl}. \item The \textbf{QR} and \textbf{RQ} losses defined in \S\ref{sec:implicit_posterior_model}. \end{itemize} The \textbf{CE}, \textbf{NLL (union)}, and \textbf{RQ} loss objectives are equivalent when $k=9$. The \textbf{RQ} and \textbf{NLL (union)} losses are equivalent when $\sum_iq_i(\ell)$ is uniform over $\ell$, which approximately holds after a sufficient number of training epochs. All models are trained for 300 epochs on batches of 256 images with the Adam optimizer \citep{kingma2014adam} and a learning rate of $10^{-4}$. After each epoch, we compute the accuracy of the predictor $q$ on the ground truth labels in the train and test sets. Fig.~\ref{fig:mnist_pairs} shows the final train and test set accuracies, as well as the maximum accuracies achieved at any epoch. Reported results are averaged over 10 choices of partial label sets and random initializations. Models trained on \textbf{RQ} loss perform best, with the greatest benefit over \textbf{CE} seen for very few negative labels. As expected, the performance of \textbf{RQ} and \textbf{NLL (union)} is very similar across $k$. We hypothesize that the small advantage of \textbf{RQ} over \textbf{NLL (union)} loss can be attributed to regularization in early training. Meanwhile, \textbf{QR} performs as well as \textbf{CE} for very uncertain priors at the peak epoch (light curves), but its predictions degenerate -- usually toward uniform predictions -- with longer training. \subsection{Multiple-instance supervision: Learning from ranks} \label{sec:ranking} \begin{figure}[t!] \centering \includegraphics[width=0.8\textwidth]{figures/mnist-rank.png} \caption{ Confusion matrices of MNIST classifiers in the course of training on batches of 128 ranked pairs of digits. The trajectory of convergence to the diagonal shows that uncertainty is first resolved for the digits 0/9, then 1/8, etc.} \label{fig:mnist_pairs} \end{figure} We train a CNN of the same architecture as in \S\ref{sec:negative_labels} on MNIST, but with the only supervision coming in the form of pairs of images in which it is known which image represents the greater digit. The training set of 60k images is divided into pairs that are fixed throughout the training procedure; each digit appears in exactly one pair. We optimize to match the predictor $q$ with the implicit posterior model (\ref{eq:pair_posterior}) using the \textbf{RQ} loss. Fig.~\ref{fig:mnist_pairs} shows the confusion matrices at initial iterations of training. The learned classifier has 97\% accuracy on both training and testing sets, which means that from pairwise comparisons alone, we can group the digit images and place them in order. \subsection{Label super-resolution \label{sec:chesapeake_experiments} We benchmark our method's performance on the Chesapeake Land Cover dataset \footnote{\href{https://lila.science/datasets/chesapeakelandcover}{https://lila.science/datasets/chesapeakelandcover}}, a large 1m-resolution land cover dataset used previously for label super-resolution \citep{robinson2019large,malkin2019label}. It consists of several aligned data layers, including: NAIP (4-channel high-resolution aerial imagery at about 1m/px), NLCD (16-class, 30m-resolution coarse land cover labels), and \text{high-resolution land cover labels (LC)} in four classes. The task is to train high-resolution segmentation models, in the four target classes, using only NLCD labels as supervision. The NLCD layer is at 30$\times$ lower resolution than the imagery and target labels and follows a different class scheme. Cooccurrence statistics of NLCD classes $c$ and LC labels $\ell$ are assumed to be known (Fig.~\ref{fig:cooccurrence_matrices}). To form a prior over land cover classes $\ell$ at each pixel position, we map the NLCD classes to probabilities over the target LC classes using these known cooccurrence counts and apply a spatial blur to reduce low-resolution block artifacts (Fig.~\ref{fig:chesapeake_predictions}, ``Prior"). We then train small convolutional networks (receptive field $11\times11$) to predict high-resolution land cover from input imagery. We evaluate both the \textbf{QR} and \textbf{RQ} variants of our approach on the two states that comprise the ``Chesapeake North" test set: Pennsylvania (PA) and New York (NY), and the two states combined, after picking hyperparameters based on an independent validation set in Delaware (details in \S\ref{app:experiment_details_landcover}). A depiction of the data and prediction results is given in Fig.~\ref{fig:chesapeake_predictions}. \Cref{tab:landcover_results_chesapeake} compares our algorithms against the algorithmic technique with the best published performance on the Chesapake dataset, self-epitomic LSR \citep{malkin2020mining} and the hard na\"ive baseline from \citet{malkin2019label}. Self-epitomic LSR, a generative modeling approach that explicitly produces likelihoods $p(x|\ell)$, analyzes small patches of data by making a large number of comparisons between sampled $7\times7$ image patches and \emph{all other} image patches. It does not produce a trained feedforward inference model, and the inference procedure is at least an order of magnitude slower than evaluation of our convolutional model. The hard na\"ive baseline maps the NLCD classes to LC classes based on a given concurrence matrix, then trains a standard semantic segmentation model on these pseudo-labels. Training on the \textbf{QR} loss outperforms (in once case, matches) performance of self-epitomic LSR (\Cref{tab:landcover_results_chesapeake}), and the generative model for $p(x|c)$ from (\ref{eq:aux_p}) is largely consistent with the epitomic generative model (Fig.~\ref{fig:p_x_given_c_figure}). Moreover, our methods handle \emph{batched input}, where self-epitomic LSR trains on one data tile at a time. Similar per-tile approaches have been shown to degrade in performance and exhaust computation capacity when training on multiple tiles \citep{malkin2020mining}). Optimization under an implied generative model has the computational advantage of scaling naturally to large training data while maintaining the benefits of leading generative modeling approaches. (See also \S\ref{sec:lymphocytes}.) \begin{table}[t!] \centering \caption{Pixel accuracy and class mean intersection over union on the Chesapeake Land Cover dataset. All models use only coarse NLCD labels as supervision. For our proposed methods, we evaluate both the trained predictor ($q_i$) and the posterior under the generative model ($r_i$). The score of the best overall model is \textbf{bolded}. } \input{tables/landcover_results_chesapeake_arxiv} \label{tab:landcover_results_chesapeake} \end{table} \begin{figure*}[t!] \centering \includegraphics[width=\textwidth]{figures/chesapeake_predictions-95compressed.jpg} \caption{Predictions of models trained with \textbf{QR} loss on the NLCD-only prior in the Chesapeake region, shown on regions of 1000$\times$1000 pixels in Pennsylvania and 500$\times$500 pixels in New York.} \label{fig:chesapeake_predictions} \end{figure*} \subsection{Data fusion and learned priors \label{sec:enviroatlas_experiments} In this set of experiments, we augment NLCD with information about the presence of buildings, road networks, and waterbodies/waterways from public sources (see Fig.~\ref{fig:prior_generation_landcover_mapping} and \S\ref{app:landcover_data_sources}). To evaluate the ability of models to generalize to across regions, we use 1m 5-class land cover labels from the geographically diverse EnviroAtlas dataset \citep{pickard2015enviroatlas} in four cities in the US: Pittsburgh, PA, Durham, NC, Austin, TX, and Phoenix, AZ. The NLCD-based prior model from \S\ref{sec:chesapeake_experiments} is augmented with the auxiliary information to obtain a hand-coded prior for each image (see \S\ref{app:forming_priors_landcover}). These types of priors can be made everywhere in the United States, while hard 1m-resolution labels are rarely available. An alternative to performing local inference under such priors is to simply apply supervised models trained on hard labels elsewhere, hoping that the domain shift is tolerable. \Cref{tab:landcover_results_enviroatlas} compares the performance of a model (of the same architecture as in \S\ref{sec:chesapeake_experiments}) trained on Pittsburgh high-resolution data (HR) in each of the three other cities with that of models tuned on the hand-coded prior in each other city. The \textbf{QR} method trained on the local handmade prior outperforms the HR model in each evaluation city. This may be attributed to the extra data in each city given to our method in the form of prior beliefs. To isolate this effect, we also compare to a high-resolution model that consumes the prior belief to \emph{input} data, concatenated with the NAIP imagery (HR + aux). While the HR + aux model does increase performance substantially from the HR model with NAIP imagery alone as input, the \textbf{QR} model remains the highest-fidelity approach in two of the three cities. These results illustrate that information that generalizes across domains may find its best use within a separate model -- to build a prior in our setting -- and then used to supervise local inference. In practice, prior beliefs could be crafted by a domain expert to reflect the uniquities in geographic and structural features for each city. We emulate incorporating such context-specific knowledge by training (on a disjoint set of instances) a neural network that consumes the inputs to the handmade prior function (NLCD and auxiliary map data), and predicts high-resolution labels (Fig.~\ref{fig:prior_generation_landcover_mapping}, ``Learned prior"). Alongside structural interactions between the inputs that generalize across cities (e.g., tree canopy supersedes rivers, roads supersede water), the learned prior captures region-specific knowledge (e.g., buildings in Durham tend to have grass surrounding them and trees farther out, while in Austin, this is reversed, and in Phoenix, riverbeds surrounded by barren land are likely to be dry). Using these tailored prior beliefs during \textbf{QR} training tends to increase scores (Table~\ref{tab:landcover_results_enviroatlas}). The final row in \Cref{tab:landcover_results_enviroatlas} benchmarks the performance of a high-resolution land cover model trained on imagery and labels over the entire contiguous US~\citep{robinson2019large}. This large model takes NAIP, Landsat 8 satellite imagery, and building footprints as inputs. Small, local models with priors created from only weak supervision outperform the US-wide model in all cities. (See \S\ref{app:additional_results} for details.) \begin{figure*}[t!] \centering \includegraphics[width=0.9\textwidth]{figures/learned-prior_all.pdf} \caption{Prior generation for land cover mapping: ``NLCD only prior" (\S\ref{sec:chesapeake_experiments}) and ``$\{$Hand-coded, Learned$\}$ prior" (\S\ref{sec:enviroatlas_experiments}). } \label{fig:prior_generation_landcover_mapping} \end{figure*} \begin{table}[t] \centering \caption{Land cover classification experiments for generalizing across cities. In each column, the score of the best model not depending on auxiliary data as input is \textit{italicized} and the score of the best overall model is \textbf{bolded}. (A larger set of experimental results is given in \Cref{tab:landcover_results_enviroatlas_full}.)} \input{tables/landcover_results_enviroatlas_condensed_arxiv} \label{tab:landcover_results_enviroatlas} \end{table} \subsection{Text classification} \label{sec:nlp} This experiment follows the recent work of \citet{mekala2021coarse} and illustrates the effectiveness of learning on prior beliefs beyond computer vision. We work with a dataset of $\sim$12k New York Times news articles. Each article belongs to one of 20 fine categories (e.g., `energy companies', `tennis',`golf'), which are grouped into 5 coarse categories (e.g., `business', `sports'). The goal is to train text classifiers that predict fine labels, but only the coarse label for each article is available in training. Some external knowledge about the fine categories is necessary to resolve the coarse labels into fine labels. Past work on this problem \citep{meng2018weakly,mekala2020contextualized,meng2020text,wang2021xclass} has trained supervised models on pseudolabels created by mechanisms such as propagation of seed words and querying large pretrained models. On the other hand, \citet{mekala2021coarse} create training data by sampling additional \emph{features} (articles) from a finetuned version of the large generative language model GPT-2 \citep{radford2019language} conditioned on fine categories, then tune a classifier based on the almost equally large model BERT \citep{devlin2019bert} in a supervised manner. We obtain comparable results using an elementary predictor, far less computation, and no finetuning of massive language models (Table~\ref{tab:coarse_text_results}). We form a prior $p_i(\ell)$ on the fine class $\ell$ of each article $x_i$ by querying GPT-2 for the likelihood of each fine category name $\ell$ compatible with the known coarse label following the prompt ``[article text] Topic: '' and normalizing over $\ell$. We then divide $p_i(\ell)$ by the mean likelihood of $\ell$ over all articles $x_i$ and renormalize. We represent each article as a vector of alphabetic trigram counts ($26^3$ features, of which only 8k are ever nonzero) and train a logistic regression with the \textbf{RQ} objective against this `GPT-2 prior'. After ten epochs of training ($\sim$10s on a Tesla K80 GPU), the trained classifier nears or exceeds the performance of models requiring at least $100\times$ longer to train, even excluding the time to generate any pseudo-training data. \begin{table}[t] \centering \caption{F1-scores of various models on the coarsely supervised text classification task. The first five rows are taken from \citet{mekala2021coarse}. The last two rows use the GPT-2 prior defined in \S\ref{sec:nlp} as weak supervision with cross-entropy and \textbf{RQ} loss, respectively (mean of 10 random trials).} \input{tables/coarse_text_results_arxiv} \label{tab:coarse_text_results} \end{table} \section{Discussion and conclusion} In summary, we found that the generative distribution in a free energy criterion can be left implicit to the minimization process in posterior (discriminative) model training. This allowed us to unite the training of neural networks $q(\ell|x_i; \theta)$ for prediction of labels $\ell$ from features $x$ with the modeling of the prior $p_i(\ell)$, possibly with its own latent structure. Implicit modeling of the conditional generative distributions removes the burden of training accurate (and therefore large or deep) generative models, but still allows natural generative approaches to modeling priors. Learning a discriminative network $q$ and its implicit posterior model $r$ via the \textbf{QR} and \textbf{RQ} methods can unify common supervised learning paradigms with realistic label supervision settings, enabling high-fidelity predictions from weak supervision sources carrying far less information. The additional experimental results in \S\ref{sec:additional_exp} detail further results for weakly supervised image segmentation, self-supervised learning, and co-segmentation in video data. Altogether, our results expose promising future work on exploring more creative data sources that can be cast as prior beliefs for downstream training. We expect interesting new modeling paradigms that integrate different modalities and models to arise from our formulation. \paragraph{Code.} This paper is accompanied by a code repository at \href{https://github.com/estherrolf/implicit-posterior}{\tt github.com/estherrolf/implicit-posterior}. The repository contains three directories. Two of them illustrate our algorithms for partial-label learning and weakly supervised segmentation and are sufficient to reproduce predictions resembling those in Fig.~\ref{fig:examples}. The third directory contains code for the land cover mapping experiments (\S\ref{sec:chesapeake_experiments}, \S\ref{sec:enviroatlas_experiments}) and instructions for reproducing the results. \newpage
{'timestamp': '2022-03-01T02:58:54', 'yymm': '2202', 'arxiv_id': '2202.14000', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.14000'}
arxiv
\subsection{Feature set} Based on manual inspection of known examples of malicious packages, we determined eleven features of interest. Nine of them are single-version features that can be extracted from the contents of a single package version, while the other two intrinsically involve two versions of a package. The single-version features are as follows, where we group related features into categories and provide examples of each: \begin{enumerate} \item Access to personally-identifying information (PII): credit-card numbers, passwords, and cookies \item Access to specific system resources \begin{enumerate} \item File-system access: reading and writing files \item Process creation: spawning new processes \item Network access: sending or receiving data \end{enumerate} \item Use of specific APIs \begin{enumerate} \item Cryptographic functionality \item Data encoding using \code{encodeURIComponent} etc. \item Dynamic code generation using \code{eval}, \code{Function}, etc. \end{enumerate} \item Use of package installation scripts \item Presence of minified code (to avoid detection) or binary files (such as binary executables) \end{enumerate} The remaining two features concern two versions of a package, and are the time between publication of the two versions, and the type of update in semantic-versioning terms (major, minor, patch, build, or pre-release). The motivation for considering time between updates is that malicious package versions often exhibit unusual update patterns, such as multiple versions published in very rapid succession (as seen in the \pkgspec{mogodb} example in Section~\ref{sec:background}), or a new version being published after years of inactivity (which might suggest an account takeover). The update type, on the other hand, can determine whether a change in some other feature is suspicious or not, as explained above. These two features, along with the changes in the values of the nine single-valued features between one package version and the previous version, constitute our feature set. In order to accommodate the first version of a package as well, we introduce a pseudo-update type representing first versions, consider their time between updates to be zero, and take the values of the single-version features to be the remaining change features. This enables us to not only detect malicious updates, where a previously benign package becomes malicious, but also packages that were malicious from the start. \subsection{Feature extraction} To compute the first four categories of single-version features, we parse each JavaScript and TypeScript file in the package using Tree-sitter.\footnote{\url{https://tree-sitter.github.io/tree-sitter/}} We then use Tree-sitter AST queries to look for syntactic constructs corresponding to the features, such as string literals containing the keyword \code{password} for PII access; imports of the \code{fs} module for file-system access; and calls to \code{eval} and \code{Function} for dynamic code generation. Similarly, to check for the presence of installation scripts we parse the \filename{package.json} file and look for definitions of \code{preinstall}, \code{install}, and \code{postinstall} properties. Minified or binary files tend to have higher entropy than plain source code, so we compute the Shannon entropy of all files contained in the package and use the average and standard deviation of the entropy across all files as features. To compute change features, we use the publication timestamps provided by the \code{npm view time} command to obtain the time between updates in seconds. We rely on an off-the-shelf semantic-versioning library to determine the update type and, for each given version, determine the previous version in chronological order. Finally, we simply subtract the values of the single-version features across the two consecutive versions. \subsection{Classifier training} Our choice of classifiers is dictated by the corpus of labelled training data we have available. Since malicious packages are taken down by npm immediately upon discovery, most known examples of malicious packages are no longer available for inspection. However, npm kindly agreed to make their archive of 643 malicious package versions detected up to 29 July 2021 available to us for the purposes of this study. Out of these packages, 63 are malicious versions of otherwise non-malicious packages, i.e., compromised packages. We added to the original dataset the 1147 benign versions of the same packages published by the same date, yielding a basic corpus of 1790 labelled samples of malicious and benign package versions. Since the goal of \textsc{Amalfi}\ is to detect malicious packages, the basic corpus oversamples malicious packages, i.e., it contains more malicious packages than we would expect from a similarly-sized random sample of npm packages. This is a common strategy in learning-based approaches~\cite{mohammed2020}. It is worth emphasizing that while compromised packages have a much bigger potential impact on the npm ecosystem, they occur so rarely that there simply is not enough data to make them the sole focus of our study. Anecdotally, however, compromised and malicious packages use similar techniques to carry out attacks, meaning that they share features, which enables \textsc{Amalfi}\ to detect both types of malicious packages. Since the number of malicious samples is smaller compared to the total number of package versions in our dataset and on npm, we had to use learning algorithms that handle imbalanced data well. Further, due to the novelty of the features in our approach, we sought a learning algorithm that allowed us to analyze the importance of the features we selected. In the end, the learning algorithms that satisfied the constraints were decision trees, Naive Bayesian classifiers, and One-class Support Vector Machines (SVMs). We picked the first one due to its ability to explain which features impact the final decision, and the two latter ones because of their versatility when dealing with imbalanced datasets as seen in anomaly detection work. To train the classifiers, we use the \code{sklearn} library for Python. For the decision tree, we use information gain as the split criterion. For the Naive Bayesian classifiers, we use the Bernoulli variant which can only deal with Boolean features, so we omit the discrete features (entropy average and standard deviation as well as update time), and collapse the others to a value of 1 if the feature is present, and 0 otherwise. For the SVM, we choose a linear kernel and train only on benign examples, since the task of this classifier is to detect outlier versions that are noticeably different from the benign ones. We determined the $\nu$ parameter of the SVM, which approximates the number of expected outliers, by conducting a leave-one-out experiment on our basic corpus. The experiment showed that optimal precision and recall are attained for a $\nu$ value of 0.001, meaning that the classifier expects about one in a thousand package versions to be malicious.% \footnote{The source code of our classifier-training scripts and the list of packages in the basic corpus are included in the supplementary materials.} \subsection{Reproducer and clone detector} As explained in Section~\ref{sec:intro}, the reproducer takes a given package version and then attempts to rebuild the package tarball from source. This is a heuristic process that may fail for a variety of reasons: while packages can specify the URL of their source repository in their \filename{package.json} file, this information is optional and many packages do not provide it, or the repository is not publicly accessible. Package versions can also specify the git SHA of the commit they were built from, but again this information is optional. While there are popular conventions for creating branches or tags with names reflecting the package version they correspond to, many packages do not follow these conventions, making it impossible to determine the correct commit. The build commands to run to produce the package from its source are likewise not prescribed. Finally, many packages neglect to specify the precise version of the build tools (such as the TypeScript compiler) they rely on, leading to seemingly random differences between the reproduced package and the original. For all of these reasons, the success rate of the reproducer is low in practice as we shall see, but it still serves a useful purpose as an automated false-positive filter. The third component of \textsc{Amalfi}\ is a simple clone detector that computes an MD5 hash of the contents of a package tarball and compares it to a list of hashes of known malicious packages. When computing the hash, we ignore the package name and version specified in the \filename{package.json} file, since these are always unique and would cause spurious misses. No other attempt at fuzzy matching is made, so only verbatim clones are detected. \subsection{Experiment 1: Classifying newly published packages} This was a large-scale experiment designed to simulate a realistic scenario for automated malware detection in which we applied \textsc{Amalfi}\ to all new public package versions published on the public npm registry over the course of a single, randomly chosen week from 29 July 2021 to 4 August 2021. On the first day, we trained our three classifiers on the basic corpus and then used them to classify the set $N_1$ of all new package versions published that day. Additionally, we ran our clone detector on the same set to find copies of malicious packages in the basic corpus, acting as a fourth classifier. This yielded a set $P_1\subseteq N_1$ of package versions flagged by at least one classifier. We ran the reproducer on this set to automatically weed out some false positives, and manually inspected the rest. The manual inspection was initially conducted by both authors, with each author examining roughly one half of the flagged versions. The package versions that were found to be malicious by one author were afterwards verified by the other author. Finally, we reported the verified malicious packages to the npm security team. All of them were subsequently taken down, meaning that the npm security experts agreed with our assessment. As such, we are confident that our manual labeling of malicious packages is highly accurate. The manual inspection resulted in a partitioning of $P_1$ into two sets $\mathit{TP}_1$ and $\mathit{FP}_1$ of true positives (i.e., genuine malicious packages found by the classifiers) and false positives (i.e., benign packages falsely flagged as malicious). As a last step, we ran the clone detector again to find additional copies of packages in $\mathit{TP}_1$ that were missed by the classifiers, and added them to $\mathit{TP}_1$. On the second day, we retrained the classifiers on the basic corpus as well as the set $N_1$ triaged the previous day, adding $\mathit{TP}_1$ to our set of labelled malicious packages, and everything else (that is, $N_1\setminus \mathit{TP}_1$) to the set of benign packages. In other words, for the purposes of this experiment we assumed that any package \emph{not} flagged by any of the classifiers was benign. This is not true in general, but the enormous number of new package versions published each day made it infeasible to inspect them all, and since we expect the number of malicious packages on any given day to be low it is not an unreasonable approximation to the unknown ground truth. As on the first day, we then applied the classifiers to the set $N_2$ of packages published that day, ran the reproducer on the resulting set $P_2$, manually inspected the rest, and ran the clone detector to mop up anything that was missed, yielding a set $\mathit{TP}_2$ of newly identified malicious packages. On the third day, we retrained the classifiers using the basic corpus as well as both $N_1$ an $N_2$, and so forth for each subsequent day.% \footnote{The list of packages considered in this experiment and the results of the classification are included in the supplementary materials.} The intuition here is that we want to mimic a usage pattern where results from the classifiers are inspected by a human auditor, and the classifiers are then retrained with the additional ground truth obtained in this way. \subsection{Experiment 2: Classifying labelled data} While the first experiment can provide insight into the performance of our approach under real-world conditions and in particular its false-positive rate, it cannot tell us much about false negatives. Hence we ran a second experiment, measuring the precision and recall of \textsc{Amalfi}\ on the basic corpus. Its small size prevented us from separating it in a train-and-test fashion, so instead we performed a 10-fold cross validation experiment, repeatedly training the classifiers on 90\% of the corpus and measuring precision and recall on the remaining 10\%. Given the imbalance in our dataset, we used stratified sampling to maintain the distribution of malicious and benign versions for each fold. Furthermore, we also measured precision and recall on a labelled dataset from recent work by Duan et al. describing their MalOSS system~\cite{duan21}. This dataset had some overlap with our basic corpus which we removed, leaving only the unique data points for this experiment. Also, the dataset initially only contained malicious packages; to balance it, we followed the same strategy as for the basic corpus and added all benign versions of the contained packages. In the end, this yielded a dataset with 372 package versions, out of which 40 were malicious \footnote{Detailed results for this experiment are included in the supplementary materials.} Based on the results from these two experiments, we will now answer the research questions posed above. \subsection{RQ1: Practical performance on newly published packages} The results of the first experiment are presented in Table ~\ref{tab:sliding-window}. The table contains the date for which we collected the package versions (\textbf{Date}) as well as the total number of versions published on that date (\textbf{\# Versions}). Then, for each classifier, the table contains the number of true positives (\textbf{\#TP}) and false positives (\textbf{\#FP}) flagged by the classifier, annotated with the number of additional true positives found by the clone detector ($+n$) and the number of false positives eliminated by the reproducer ($-n$). As explained above, all true positives were confirmed by the npm security team. Thus, for example, the entry $16+2$ in the \textbf{\#TP} column for the decision tree on August 4 means that the classifier flagged 16 true positive among the 17,063 package versions published that day of which the clone detector found two additional copies. The entry $9-1$ in the \textbf{\#FP} column means that among the nine false positives it flagged, one was successfully reproduced and hence eliminated automatically. As explained above, the clone detector is also treated like a fourth classifier. It has no false positives and never misses identical copies, hence this column only contains a single number per day. Note again that in this column we show the number of clones found on that same day, as opposed to the entries after the $+$ sign which depict the number of clones from the previous days. The first takeaway from this table is that the number of new packages published every day is high, but quite variable, with almost four times as many packages being published on July 29 (a Thursday) than on August 1 (a Sunday). Secondly, we can see that all our classifiers are able to correctly classify malicious package versions, with varying degrees of success. The decision tree performs better than the rest, especially in terms of true positives. Removing the overlap between classifiers, we were able to identify 95 previously unknown malicious packages over the course of these seven days, which is a significant number, especially considering that the entire set of malicious packages detected prior to our work only contained 643 samples. Third, we notice that on the first day all three classifiers produce an unmanageable number of results. We therefore had to modify our approach and only examined a subset of all flagged packages in detail, assuming all the rest to be false positives. This means that the false-positive counts for this day are likely to be overstated. However, once this set of packages is added to the training set on the second day, the number of results drops dramatically, and by the end of the week all three classifiers yield a relatively low number of false positives. Fourth, our results show that the reproducer has a low success rate in practice, only being able to reproduce one or two packages on any given day. However, given the overall low number of alerts towards the end of the week this is still a valuable improvement. Similarly, clone detection only contributes a few additional true positives each day (the 17 packages detected on August 4 being an outlier, and mostly overlapping with the results from the decision tree), but it still improves the overall results. Both mechanisms are computationally inexpensive, and thus the help they provide comes at a low cost, making them worth keeping in spite of their limited contributions. Conversely, this shows that our classifiers add value beyond a purely textual scan looking for verbatim copies of known malware. In summary, we can answer RQ1 in the affirmative: \textsc{Amalfi}\ does indeed detect malicious packages in practice. Further, since all the packages found by \textsc{Amalfi}\ and reported to npm had not been identified before, we can confidently claim that our approach complements existing solutions for malicious package detection in npm. \newcommand{\textbf{Prec.}}{\textbf{Prec.}} \newcommand{\textbf{Recall}}{\textbf{Recall}} \begin{table}[th] \begin{tabular}{l||rr|rr|rr} \textbf{Dataset} & \multicolumn{2}{c|}{\textbf{Decision Tree}} & \multicolumn{2}{c|}{\textbf{Naive Bayes}} & \multicolumn{2}{c}{\textbf{SVM}} \\ & \textbf{Prec.} & \textbf{Recall} & \textbf{Prec.} & \textbf{Recall} & \textbf{Prec.} & \textbf{Recall} \\ \hline Basic & 0.98 & 0.43 & 0.90 & 0.19 & (0.98) & (0.27) \\ MalOSS & 0.35 & 0.64 & 0.62 & 0.64 & 0.73 & 0.61 \\ \end{tabular} \caption{Results from Experiment 2} \label{tab:maloss-accuracy} \end{table} \subsection{RQ2: Accuracy} The results from Experiment 2 are presented in Table~\ref{tab:maloss-accuracy}. The first row shows precision and recall measurements from the 10-fold cross-validation experiment on our basic corpus, averaged over all ten runs. The numbers for the SVM classifier have to be interpreted with care, since its $\nu$ parameter was fitted on this very dataset, hence we have put them in brackets. All our models achieve very high precision, but the recall of Naive Bayes and SVM is somewhat poor. This is expected due to the low prior of malicious packages. The second row shows precision and recall from running \textsc{Amalfi}\ on the MalOSS dataset derived from the literature~\cite{duan21} as explained above. We see that the recall is higher than with the previous row, at the expense of precision. These results point to the trade-off between these two metrics, but it is also worth pointing out that the MalOSS dataset contains a number of packages labeled as malicious where npm disagreed with the authors' assessment and did not take them down. A more detailed comparison of \textsc{Amalfi}\ to MalOSS is unfortunately not possible since they do not present statistics on false positives or performance. The heavy-weight nature of their approach and its complicated setup involving a sophisticated pipeline combining static and dynamic components made it infeasible to run on our dataset. Based on these results and the false-positive numbers discussed above, we can give a cautiously positive answer to RQ2: \textsc{Amalfi}\ is reasonably precise and does not produce an overwhelming number of results, making manual triaging of results by a human auditor feasible. The second experiment suggests that there may be a good number of false negatives, but at least the numbers for the decision tree look promising. \subsection{RQ3: Performance} To characterize the performance of our approach, we measured three metrics: (i) the time it takes to train the classifier, (ii) the time it takes to extract features for a package version, and (iii) the time it takes to classify a package version. All three measurements were obtained as a byproduct of Eperiment~1. Figure~\ref{fig:training-time} shows how long it took to train the classifiers for each day of our experiment as a function of the size of the training set. As can be seen, training is quite fast, taking no more than a few seconds despite the steady increase in training data. The SVM-based classifier takes the longest time, though it still seems to scale more or less linearly in the training-set size. The other two classifiers are very quick to train, and it is clear that the training set size could be increased substantially before training time becomes a bottleneck. \begin{figure}[t!] \includegraphics[width=7cm]{figures/classifiers-time.png} \caption{Classifier training time} \Description[Line graphs showing the training time for the three types of classifiers as the size of the training set increases.]{ The training time for all three classifiers is roughly linear in the size of the training set, with the decision tree and the Naive Bayes classifier taking no more than a second to train even on the largest training set with over 90,000 samples. The SVM-based classifier is slower to train, but still finishes in less than five seconds. } \label{fig:training-time} \end{figure} To benchmark feature extraction, we post-processed logs from our run of Experiment~1 to measure the time it takes to extract features for a randomly chosen set of around 500 package versions. By and large, feature extraction takes less than ten seconds, and for over half the packages considered it takes less than one second. However, a single outlier package containing more than 11,000 files takes more than ten minutes to extract, somewhat skewing the distribution for an average extraction time of six seconds. Lastly, we measured the time it took to predict whether a given package was malicious. For all the classifiers, the time for prediction was less than a second. Based on these results, we can give a positive answer to RQ3: \textsc{Amalfi}\ is fast enough for practical use. \subsection{Threats to validity} While the results of our evaluation are overall very promising, there are some threats to the validity of our conclusions. First, while the set of packages we considered in Experiment~1 was taken from the wild, it may have been biased in ways that we did not anticipate, and so our results may not generalize. Also, the basic corpus is to some degree biased in that it contains clusters of similar malware samples resulting from copy-cat campaigns. Second, while we examined all packages flagged by \textsc{Amalfi}\ and reported the true positives to npm, we limited ourselves to at most five minutes' inspection time per package, which prevented detailed investigation of some of the larger ones and may have caused us to miss true positives. Conversely, we may have been mistaken in labelling some packages malicious, leading to missed false positives, but this seems unlikely considering that npm have taken all reported packages down, meaning that they agree with our assessment. Finally, as noted above in our retraining step in Experiment~1 we assumed packages that were not flagged by any classifier to be benign. This is not a sound assumption in general, and might end up increasing the number of false negatives over time. For this reason, and also to escape the slow but inexorable rise in training time suggested by Figure~\ref{fig:training-time}, in practice one would not want to continue retraining in this fashion indefinitely. Table~\ref{tab:sliding-window} suggests diminishing returns from retraining after a few days, but the data is clearly too sparse to draw a definite conclusion. \section{Introduction}\label{sec:intro} \input{intro} \section{Background}\label{sec:background} \input{background} \section{Our Approach}\label{sec:approach} \input{approach} \section{Evaluation}\label{sec:evaluation} \input{evaluation} \section{Discussion}\label{sec:discussion} \input{discussion} \section{Related Work}\label{sec:related} \input{related} \section{Conclusion}\label{sec:conclusion} \input{conclusion} \begin{acks} The authors would like to thank the npm team and the GitHub Trust and Safety team for providing us with access to the corpus of malicious packages, and for facilitating our experiments. We would also like to thank them, as well as our GitHub colleagues Bas Alberts and Henry Mercer, Tom Zimmermann and Patrice Godefroid of Microsoft Research, Laurie Williams, and the entire GitHub Next team for valuable feedback and advice during our work on this paper. Finally, we would like to thank Prof. Nenad Medvidovi\'c for his help and feedback. \end{acks} \bibliographystyle{ACM-Reference-Format} \balance
{'timestamp': '2022-03-01T02:57:11', 'yymm': '2202', 'arxiv_id': '2202.13953', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13953'}
arxiv
\section{Introduction} Hearing assistive devices such as bone-anchored hearing devices and cochlear implants have a limited ability to locate and separate sounds \cite{verschuur2005auditory,denk2019limitations, nelissen2016three}. This is an issue as localization is an important auditory ability for safely moving in space and detecting sounds in environments such as schools, restaurants, busy streets and workplaces. Hearing in noise is facilitated by the localization of sounds in order to turn the head towards the speaker (the source of the sound) and utilize additional speech cues such as lip-reading and facial expressions to extract a message from high background noise. Haptic devices have been shown to significantly improve the localization of sounds \cite{fletcher2020electro}. Studies have also shown that auditory localization can be improved by training \cite{byrne1998optimizing}. People lacking access to visual information are particularly reliant on their auditory localization capacities to move autonomously and safely \cite{guth2010perceiving,lagrow1994orientation, lawson2010improving,kolarik2016auditory}. Robot audition offers interesting solutions to perform sound source localization using microphone arrays in dynamic environments. The existing approaches are well-suited for assisting a human with sound localization tasks as: 1) microphone arrays are available in arbitrary geometries as robots come in many different shapes; and 2) they can run on portable low-cost hardware powered by a battery. There are three main types of sound source localization methods: 1) steered-power beamformers; 2) subspace decomposition methods; 3) machine learning-based approaches. Steered-Response Power with Phase Transform (SRP-PHAT) consists in steering a beamformer in different potential direction of arrivals (DoAs) around the microphone array \cite{dibiase2001robust}. It is also possible to break down the problem for each pair of microphones, using the Generalized Cross-Correlation with Phase Transform (GCC-PHAT) \cite{brandstein1997robust}. The computational load however increases with the number of microphones and the number of potential DoAs \cite{grondin2013manyears}. To reduce the complexity, the search can first be done on a coarse grid, and then finished with a finer grid \cite{grondin2019lightweight}. Another approach is the Singular Value Decomposition with Phase Transform (SVD-PHAT), which relies on Singular Value Decomposition of the SRP-PHAT projection matrix to project the observation on a vector with the principal components \cite{grondin2019svd,grondin2019fast}. A k-d tree is then used to speed up the search for the most likely direction of arrival of sound. These approaches require the \emph{a priori} geometry of the microphone array to be known, which can be an issue if the microphones are installed on a deformable surface. Subspace decomposition consists of methods such as MUltiple SIgnal Classification (MUSIC) \cite{schmidt1986multiple} and Estimation of Signal Parameters via Rotational Invariance Technique (ESPRIT) \cite{roy1989esprit}. While MUSIC was formerly used with narrowband signals, it was adapted for wideband signals such as speech with the Standard Eigenvalue Decomposition MUSIC (SEVD-MUSIC) algorithm \cite{ishi2009evaluation}. SEVD-MUSIC assumes that speech is more powerful than noise for each frequency bin, which is not always the case. The Generalized Eigenvalue Decomposition with MUSIC (GEVD-MUSIC) overcomes this limitation by performing decomposition with respect to the noise spatial correlation matrix \cite{nakamura2009intelligent,nakamura2011intelligent,nakadai2012robot}. GEVD-MUSIC however suffers from the non-orthogonality of the bases spanning the noise subspace, which in turn impacts the accuracy of localization. Generalized Singular Value Decomposition with MUSIC (GSVD-MUSIC) is proposed to enforce bases orthogonality and improve localization accuracy \cite{nakamura2012real}. MUSIC-based methods however rely on eigenvalue or singular value decomposition in real-time, which involves a significant amount of computations, and usually require expensive hardware. Machine learning approaches have recently gained in popularity for a wide range of audio processing tasks, including multi-channel sound source localization. They usually involve training a neural network for a specific microphone array geometry, based on simulated and/or recorded audio data. For instance, it is shown that localization with a uniform linear array can be performed by training a convolutional neural network (CNN) using white noise signals \cite{chakrabarty2017broadband, chakrabarty2019multi}. Convolutive and Recursive Neural Networks (CRNNs) can also be used to estimate DoAs for a specific class of sounds \cite{adavanne2018sound,adavanne2018direction}. Although these deep learning methods show accurate DoA estimation, they have two major drawbacks: 1) they need a significant amount of training data for a specific microphone array geometry, which makes quick calibration difficult; and 2) they require expensive hardware to perform inference as they have numerous weight parameters. In this paper, we propose a new device, called SmartBelt, that can be installed on a user waist. This belt performs sound source localization with multiple microphones using GCC-PHAT with binary time-frequency masks, and provides haptic feedback using motors to inform the user regarding the direction of arrival of sound. There are three main contributions in this paper: 1) we introduce and describe the first belt that performs audio localization and provides haptic feedback; 2) we propose a simple yet effective calibration for the belt to adapt to different waist sizes; and 3) we demonstrate that this belt can estimate DoA accurately and provide useful haptic feedback. This paper is organized as follows. Section \ref{sec:smartbelt} introduces the hardware and the proposed algorithm. Section \ref{sec:experiments} demonstrates how the belt performs in real conditions. Finally, section \ref{sec:conclusion} concludes with final remarks and suggests future work. \section{SmartBelt} \label{sec:smartbelt} The proposed SmartBelt device consists of custom made hardware and uses algorithms based on GCC-PHAT to estimate the DoA of the sound source of interest. \subsection{Hardware} The proposed hardware consists of 8 microphones fixed on the belt perimeter and 15 haptic motors. The haptic motors are fixed to the internal side of the belt, and a microphone is also installed every two motors on the external side of the belt on 3-D printed supports, as shown in Figure \ref{fig:belt}. The geometry of the microphone array is unknown \emph{apriori}, but it is assumed that the motors are spaced evenly on the belt. \begin{figure}[!ht] \centering \includegraphics[width=0.9\linewidth]{images/belt} \caption{SmartBelt Layout} \label{fig:belt} \end{figure} The microphones are plugged in a 8SoundsUSB sound card \cite{abran2014usb}, connected to a Raspberry Pi 4 (RP4) board \cite{mcmanus2021raspberry} via USB. Each haptic motor is connected to a MOSFET module, which is interfaced with a General Purpose Input/Output (GPIO) pin on the RP4. A portable power bank with USB ports powers the RP4 and the MOSFETs. The sound card, MOSFETs, RP4 and power bank are installed in a backpack carried by the user. Cables exit the backpack and connect to the belt from behind. Figure \ref{fig:hardware} shows the hardware for SmartBelt, and Figure \ref{fig:schematic} illustrates the connection schematic. \begin{figure} \centering \includegraphics[width=\linewidth]{images/hardware} \caption{The belt is installed around the user's waist. The microphones are connected to a sound card in the bag, and the haptic motors are driven by mosfet boards also installed in the back pack. Cables leave the bag and run along the belt perimeter to reach each motor and microphone individually.} \label{fig:hardware} \end{figure} \begin{figure} \centering \includegraphics[width=\linewidth]{images/blocks} \caption{Diagram with the connections between the different hardware components of the SmartBelt} \label{fig:schematic} \end{figure} \subsection{Algorithms} \subsubsection{TDoA Estimation} \label{subsubsec:tdoaest} The proposed system captures the audio signals from the microphones and compute a Short-Time Fourier Transform (STFT) for each canal $c \in \mathcal{C} = \{1, 2, \dots, 8\}$ over windows of $N \in \mathbb{N}$ samples for a total of $T \in \mathbb{N}$ frames, denoted as $X_c(t,f) \in \mathbb{C}$, where $t \in \{1, 2, \dots, T\}$ stands for the frame index and $f \in \{0, 1, \dots, N/2\}$ stands for the frequency bin index. The cross-correlation $R(t,f) \in \mathbb{C}$ is computed in the frequency domain for a each pair of microphones $(u,v) \in \mathcal{Q}$ (where $\mathcal{Q}=\{(x,y) \in \mathcal{C}^2: x<y\}$) as follows: \begin{equation} R_{u,v}(t,f) = X_u(t,f)X_v(t,f)^*, \end{equation} where $(\dots)^*$ stands for the complex conjugate. The Time Difference of Arrival (TDoA) estimation for each pair of microphones $(u,v)$ used here relies on the Generalized Cross-Correlation with Phase Transform (GCC-PHAT) approach, which makes use of the inverse Fast Fourier Transform (iFFT) to estimate the correlation in the time domain as follows: \begin{equation} r_{u,v}(t,\tau) = \sum_{f=0}^{N-1}{M(t,f)\frac{R_{u,v}(t,f)}{|R_{u,v}(t,f)|}\exp\left(-j2\pi f\tau/N \right)}, \end{equation} where $\tau \in \mathbb{Z}$ corresponds to the time delay in samples, $j = \sqrt{-1}$ and $|\dots|$ stands for the magnitude of the complex number. A binary time-frequency mask $M(t,f) \in \{0,1\}$ is generated to capture only regions different from background noise (estimated during silence periods), as previously investigated in \cite{grondin2015time,grondin2016noise}. The TDoA $\tau_{u,v}(t)$ at each frame $t$ is then obtained by finding the peak in the correlation signal: \begin{equation} \tau_{u,v}(t) = \argmax_{\tau}{\{r_{u,v}(t,\tau)\}}. \end{equation} All the TDoAs are accumulated in a buffer of $T$ frames, and the final TDoA corresponds to the mode: \begin{equation} \tau_{u,v} = \mathrm{Mod}(\tau_{u,v}(t)). \end{equation} As the exact geometry of the microphone array is unknown, a calibration step is required to map the TDoAs of all pairs of microphones to each potential DoA, and assign a specific DoA for each haptic motor position. \subsubsection{Calibration} Each person has a unique morphology (waist circumference, width, etc.), which can also change over time due to health related issues (e.g. pregnancy, sedentary life style, aging). For this reason, a fast and quick calibration procedure with minimal hardware requirement is desirable. The goal is to associate each haptic motor to a DoA azimuth angle (in degrees). The user first positions himself at an approximate angle, and then a loudspeaker a few meters away plays a white noise signal ant the same height and for 3 seconds. The belt records the audio signals, estimates the TDoA for each pair of microphones, and stores them in memory. The user then orients himself in another direction, and the same procedure is repeated. The eight calibration directions are set to $0^{\circ}$, $45^{\circ}$, $90^{\circ}$, $135^{\circ}$, $180^{\circ}$, $225^{\circ}$, $270^{\circ}$ and $315^{\circ}$. The system then estimates the TDoAs for each of the 360 angles (with a resolution of 1 degree) by performing linear interpolation with the eight calibration directions and associated TDoAs. A lookup table is then generated with each DoA and the corresponding $28$ TDoAs: \begin{equation} \left[ \begin{array}{c} 0 \\ 1 \\ \vdots \\ 359 \\ \end{array} \right] \rightarrow \left[ \begin{array}{ccccc} \tau^0_{1,2} & \tau^0_{1,3} & \tau^0_{1,4} & \dots & \tau^0_{7,8} \\ \tau^1_{1,2} & \tau^1_{1,3} & \tau^1_{1,4} & \dots & \tau^1_{7,8} \\ \vdots \\ \tau^{359}_{1,2} & \tau^{359}_{1,3} & \tau^{359}_{1,4} & \dots & \tau^{359}_{7,8} \\ \end{array} \right]. \end{equation} The haptic motors $\{2$, $4$, $6$, $8$, $10$, $12$, $14\}$ are positioned midway between the pair of microphones $\{(1,2)$, $(2,3)$, $(3,4)$, $(4,5)$, $(5,6)$, $(6,7)$, $(7,8)\}$. This implies that when the sound source faces directly one of these motors, the TDoA estimated at the corresponding pair of microphones corresponds to $0$ (both microphones are equidistant from the motor). Using this property, it is possible to associate a DoA angle (between $0^{\circ}$ and $360^{\circ}$) to each haptic motor with an even index. We denote these angles as $\theta_2$, $\theta_4$, $\theta_6$, $\theta_8$, $\theta_{10}$, $\theta_{12}$ and $\theta_{14}$. Figure \ref{fig:tdoas_haptic} shows how the DoA of the haptic motors can be estimated. It is interesting to note that the calibration angles can be more or less accurate (i.e. they can differ from the exact values of $0^{\circ}$, $45^{\circ}$, $\dots$, $315^{\circ}$). In fact, the interpolated angles can be slightly off and generate a reference scale that is imperfect, but the predicted DoA at test time and the reference haptic motor DoAs are both on this same scale, which compensates for the difference. \begin{figure}[!ht] \centering \includegraphics[width=\linewidth]{images/tdoa} \caption{A sound source generates white noise at eight different angles around the belt ($0^{\circ}$, $45^{\circ}$, $\dots$, $315^{\circ}$). The TDoAs are estimated for each calibration angle, and are connected using linear interpolation. The DoA angles aligned with the haptic motors with even indices correspond to the zero-crossing for pairs of microphones $(1,2)$, $(2,3)$, $(3,4)$, $(4,5)$, $(5,6)$, $(6,7)$ and $(7,8)$. Only the TDoAs that correspond these 8 pairs out of 28 are shown for clarity. In this example, the DoA associated to haptic motor $6$ is $\theta_6 = 170^{\circ}$}. \label{fig:tdoas_haptic} \end{figure} The haptic motors $3$, $5$, $7$, $9$, $11$ and $13$ are equidistant to neighbor motors which DoAs are known. Using linear interpolation, the DoAs can be computed as follows: \begin{equation} \begin{array}{ccc} \displaystyle\theta_3 = \frac{\theta_2 + \theta_4}{2},& \displaystyle\theta_5 = \frac{\theta_4 + \theta_6}{2},& \displaystyle\theta_7 = \frac{\theta_6 + \theta_8}{2},\\ \\ \displaystyle\theta_9 = \frac{\theta_8 + \theta_{10}}{2},& \displaystyle\theta_{11} = \frac{\theta_{10} + \theta_{12}}{2},& \displaystyle\theta_{13} = \frac{\theta_{12} + \theta_{14}}{2}.\\ \end{array} \end{equation} Finally, the DoAs of the two last haptic motors $1$ and $15$ are estimated as follows: \begin{equation} \theta_1 = \frac{3\theta_2 - \theta_3}{2},\ \theta_{15} = \frac{3\theta_{14} - \theta_{13}}{2}.\ \end{equation} \subsubsection{Localization} Once the belt is properly calibrated, it can be used to localize the DoA of a sound stimulus that would normally draw the attention of a person with normal hearing function (e.g. phone ringing, car honking). Once the belt localizes the sound of interest, the haptic motor that matches this direction vibrates to provide feedback to the user. The TDoAs are computed the same way as in Section \ref{subsubsec:tdoaest}. The score between the computed TDoAs ($\hat\tau_{u,v}$) and the TDoAs in the lookup table ($\tau^\phi_{u,v}$) for each potential DoA $\phi$ generated during calibration is obtained using a Squared Exponential Kernel (to make it more robust to potential outliers): \begin{equation} f(\phi) = \sum_{u=1}^{8}\sum_{v=u+1}^{8}\sigma^2 \exp\left(-\frac{( \hat\tau_{u,v}-\tau^\phi_{u,v} )^2}{2l^2}\right). \end{equation} The predicted DoA $\phi^*$ then corresponds to the potential DoA with the highest score: \begin{equation} \phi^* = \argmax_{\phi} \left\{ f(\phi) \right\}, \end{equation} and the belt activates the haptic motor with the closest DoA $\theta_i$ to the predicted DoA $\phi^*$: \begin{equation} \theta_i^* = \argmin_{i} \left\{ |\theta_i - \phi^*| \right\}. \end{equation} \section{Experiments} \label{sec:experiments} The belt is tested in controlled real-life conditions to demonstrate the versatility of the proposed system amongst different users. The frame ($N$) and hop ($\Delta N$) sizes are chosen to ensure a $23$ msec analysis window with an overlap of $50\%$. The Squared Exponential Kernel parameters $l$ and $\sigma$ are chosen empirically to provide good localization accuracy. Table \ref{tab:doa} shows the parameters used for the experiments. \begin{table}[!ht] \renewcommand{\arraystretch}{1.4} \centering \caption{Parameters for DoA estimation} \begin{tabular}{|c|c|} \hline Parameter & Value \\ \hline $N$ & 1024 \\ $\Delta N$ & 512 \\ $l$ & 0.707 \\ $\sigma$ & 1 \\ \hline \end{tabular} \label{tab:doa} \end{table} A bluetooth speaker is used as the sound source, and a general purpose cardboard with 40 azimuth angles ($0^{\circ}$, $9^{\circ}$, $18^{\circ}$, $\dots$, $342^{\circ}$, $351^{\circ}$) serves as a reference for the orientation of the user. The speaker is approximately 2 m from the user and at the same height. For testing, multiple sounds of interests are used: 1) truck horn; 2) car driving by; 3) car horn; 4) car braking; 5) phone ringing; 6) speed car accelerating. Each sound has a duration of approximately 2 seconds. The DoA estimation is performed using the full segment. The belt is worn by two male participants with different waist sizes. Calibration is performed by playing white noise at eight angles ($0^{\circ}$, $45^{\circ}$, $\dots$, $315^{\circ}$). The test sounds are then played at each one of the 40 azimuth angles. Figure \ref{fig:exp_setup} demonstrates the experimental setup used to evaluate the performance of the belt. \begin{figure}[!ht] \centering \includegraphics[width=0.9\linewidth]{images/setup_experiments} \caption{Setup for the experiment with a participant wearing the belt and the loudspeaker playing sounds.} \label{fig:exp_setup} \end{figure} Using the calibration procedure described earlier, the DoAs associated to each haptic motor are obtained and shown in Table \ref{tab:motors}. The results demonstrate that it is possible to easily recover the positions of the haptic motors using the proposed calibration method as they are moved on the belt to accommodate for the different waist sizes. \begin{table}[!ht] \renewcommand{\arraystretch}{1.4} \centering \caption{Corresponding DoA angles for haptic motors} \begin{tabular}{|c|cc|} \hline Motor & Participant A & Participant B \\ \hline 1 & 36$^{\circ}$ & 30$^{\circ}$ \\ 2 & 51$^{\circ}$ & 45$^{\circ}$\\ 3 & 80$^{\circ}$ & 75$^{\circ}$\\ 4 & 109$^{\circ}$ & 105$^{\circ}$\\ 5 & 134$^{\circ}$ & 127$^{\circ}$\\ 6 & 159$^{\circ}$ & 150$^{\circ}$\\ 7 & 169$^{\circ}$ & 168$^{\circ}$\\ 8 & 180$^{\circ}$ & 187$^{\circ}$\\ 9 & 195$^{\circ}$ & 202$^{\circ}$\\ 10 & 210$^{\circ}$ & 218$^{\circ}$\\ 11 & 235$^{\circ}$ & 239$^{\circ}$\\ 12 & 260$^{\circ}$ & 261$^{\circ}$\\ 13 & 282$^{\circ}$ & 279$^{\circ}$\\ 14 & 305$^{\circ}$ & 298$^{\circ}$\\ 15 & 316$^{\circ}$ & 307$^{\circ}$\\ \hline \end{tabular} \label{tab:motors} \end{table} The test sounds are played at each position on the loudspeaker, and the predicted ($\phi$) and reference ($\gamma$) DoAs angles are compared. The Mean Absolute Error (MAE) is then computed for each test sound and participant as follows: \begin{equation} \mathrm{MAE} = \frac{1}{40}\sum_{k=1}^{40}{|\phi_k-\gamma_k|}, \end{equation} where $\phi_k$ and $\gamma_k$ stand for the predicted and baseline angle at position $k$, where $k \in \{1, 2, \dots, 40\}$. Table \ref{tab:mae} shows the MAE for each sound and participant. The results confirm the accuracy of the proposed method to estimate the DoA. On average, both MAEs are similar, with values of $2.69^{\circ}$ and $3.11^{\circ}$ for participants A and B, respectively, and an overall average of $2.90^{\circ}$. This is similar to MAE in humans, estimated in some studies to 3 degrees for wideband sounds coming from a specific direction \cite{blauert1997spatial}. \begin{table}[!ht] \renewcommand{\arraystretch}{1.4} \centering \caption{MAE for each sound and participant} \begin{tabular}{|c|cc|} \hline Sound & Participant A & Participant B \\ \hline Truck horn & 4.55$^{\circ}$ & 3.25$^{\circ}$ \\ Car driving by & 2.45$^{\circ}$ & 2.83$^{\circ}$ \\ Car horn & 2.23$^{\circ}$ & 4.80$^{\circ}$ \\ Car braking & 2.65$^{\circ}$ & 2.25$^{\circ}$ \\ Phone ringing & 2.50$^{\circ}$ & 3.25$^{\circ}$ \\ Speed car accelerating & 1.73$^{\circ}$ & 2.25$^{\circ}$ \\ \textbf{Average} & \textbf{2.69$^{\circ}$} & \textbf{3.11$^{\circ}$} \\ \hline \end{tabular} \label{tab:mae} \end{table} Based on the predicted DoAs, we choose the haptic motor that needs to provide feedback. The chosen motor is compared to the one that should be activated given the theoretical DoA, and a ratio of good match is computed. Table \ref{tab:percentage} shows these results. In general, the belt provides a high fidelity haptic feedback with most sounds, with an average of $92.5\%$ and $92.1\%$ for participants A and B respectively, and an overall average of $92.3\%$. Note that the lowest performances are observed with the truck horn sound, which is expected as for this sound segment, most of the power lies in the low frequencies, and GCC-PHAT performs better with wideband signals. \begin{table}[!ht] \renewcommand{\arraystretch}{1.4} \centering \caption{Proportion of good match between activated haptic motors and haptic motors that should be activated} \begin{tabular}{|c|cc|} \hline Sound & Participant A & Participant B \\ \hline Truck horn & 77.5\% & 82.5\% \\ Car driving by & 100.0\% & 90.0\% \\ Car horn & 95.0\% & 87.5\% \\ Car braking & 92.5\% & 100\% \\ Phone ringing & 95.0\% & 95.0\% \\ Speed car accelerating & 95.0\% & 97.5\% \\ \textbf{Average} & \textbf{92.5\%} & \textbf{92.1\%} \\ \hline \end{tabular} \label{tab:percentage} \end{table} \section{Conclusion} \label{sec:conclusion} This paper presents three contributions: 1) we introduce the first belt that can perform sound source localization at $360^{\circ}$ around a user; 2) we propose a simple calibration procedure to adjust the belt for participants with different waist sizes; and 3) we demonstrate that the belt provides accurate DoA estimation and haptic feedback. So far, a simple time-frequency mask is applied to detect non-stationary sound source and ignore stationary noise. In practice however, it would be important to trigger the haptic feedback only for sounds of interest. To achieve this, joint sound source detection and localization could be applied to each pair of microphones \cite{grondin2019sound}. Moreover, the performance of GCC-PHAT deteriorates with narrower bandwidth sounds, as observed in the experiments with the truck horn sound. It would therefore be useful to combine the inter-level difference between microphones with the delay of propagation information. Moreover, a new prototype could be built with MEMS microphones connected in daisy chain, which would reduce the amount of wiring, reduce the power consumption, and make the device more portable. Given the challenges associated with the use of only amplification to transmit auditory localization information, one potential application of the SmartBelt would be to couple it to a hearing aid device or cochlear implant. In this way, the haptic motors could contribute additional vibrotactile stimulation complementing the auditory information transmitted via the hearing device. Currently there is little information in the literature regarding the benefits of multi-modal stimulation for the improvement of auditory capacities such as localization. Future work could include measuring the functional consequences of vibrotactile stimulation without amplification on a normal-hearing population. Later experiments could be carried out on clinical populations with hearing losses of various degrees coupled to different types of hearing devices. Combining multimodal stimuli has been shown to improve reaction time, perceptual precision and accuracy \cite{burr2009temporal,ernst2004merging,fujisaki2005temporal,camponogara2016hear,mclachlan2021towards} which is particularly important when navigating a physical environment such as a busy street. Future experiments will look at the degree to which threshold auditory localization perception can be improved by combining haptic and auditory stimulation.
{'timestamp': '2022-03-01T02:57:37', 'yymm': '2202', 'arxiv_id': '2202.13974', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13974'}
arxiv
\section{Introduction} Massive data growth in the era of Big Data, has made data mining and data analytics~\cite{chen1996data} some of the fundamental technologies for discovering knowledge and interesting patterns in data~\cite{gan2017data}. In particular, mining \textit{sequence} data has attracted a lot of attention for two main reasons. First, sequential representation for data and events is common for many real-life applications. Second, knowing the useful patterns from sequences can benefit a number of applications, such as web access analysis, event prediction, pattern discovery, time-aware recommendation, DNA sequence detection~\cite{biosensors2002}, and \textit{feature embedding}~\cite{kumar2011pattern}. Feature embedding is a challenging task in sequence mining~\cite{han2001prefixspan,srikant1996mining,GAN2020222}, whose goal is to provide a machine-interpretable representation for the sequence data that may increase performance of learning algorithms. In the specific context of \textit{biological sequences}, the main trend for feature embedding is based on the presumed existence of a conceptual analogy between the languages adopted by humans to communicate and the sophisticated languages used by biological organism to convey information within and between cells. Most of the approaches proposed in literature~\cite{asgari2015continuous,kimothi2016distributed}, indeed, adopt existing methods in Natural Language Processing (NLP) such as \texttt{word2vec}~\cite{mikolov2013efficient} in attempt to gain a deeper understanding of the language of life, with the goal of discovering functions encoded within biological sequences~\cite{yandell2002genomics,searls2002language,motomura2012word,cai2009modeling}. As well as the common techniques in Bioinformatics for analyzing sequences, also such methods involves fixed-length overlapping n-grams~\cite{ganapathiraju2002comparative,srinivasan2013mining,vries2008subfamily}. However, usually n-grams are not used directly in feature extraction, but for training an embedding model adopted for the feature extraction task. In addition to other limitations discussed in Section \ref{sec:related}, we remark that most of the existing methods either limit themselves by extracting only short-term patterns or suffer from a significant increasing computation upon extracting the long-term patterns. \subsection{Contributions of this work} In this article, we focus on a novel approach for the feature embedding of sequencing reads. Unlike the works proposed in the literature which essentially consist of elaborate applications of NLP techniques, in this work we propose a theoretical investigation of combinatorial properties that would guarantee compact embedded representations of the sequences able to preserve similarities. In this section, we provide a discussion about the motivations; then we give an overall description of the proposed method, and finally we explain our main contributions. \paragraph{Motivations.} The main question addressed in this paper is whether there exists a ``similarity signature" that can be: \textit{(i)} easily detected while reading the sequence, and \textit{(ii)} used to define an effective feature embedding method. We answer to this question by exploiting one of the most well-known factorization in combinatorics on words: the \textit{Lyndon factorization}~\cite{10.2307/1970044,lothaire1997combinatorics}. Such a factorization has some main desired properties: \textit{(i)} it is unique for a word, \textit{(ii)} it can be computed in linear time, and more recently it has been proved in~\cite{tcs2020,lata2020} that \textit{(iii)} a read shares a sequence of consecutive common Lyndon factors with the Lyndon factorization of a superstring of the read itself. The notion of Lyndon word is not novel in the field of Bioinformatics, since it was used to locate short motifs~\cite{delgrange2004star} and more recently it was explored in the development of bijective Burrows-Wheeler Transforms~\cite{inplace-bijective-bwt2020}. Surprisingly, in this paper we discover that the length of factors in a Lyndon factorization of a read is enough to define a notion of signature that captures sequence similarity. We have defined such a sequence of lengths as the \textit{fingerprint} of a read. \paragraph{Proposed method.} In this paper we propose a novel sequence feature embedding method which given a sequencing read uses the fingerprint of the read to produce embedded representations. To the best of our knowledge, it represents one of the first attempts to build feature embedded representations based on theoretical combinatorial properties proved to capture sequence similarities and also suitable for machine learning techniques. \paragraph{Our contributions.} The main contributions can be summarized as follows: \begin{enumerate} \item We have implemented the proposed method in the tool \texttt{lyn2vec}, which produces Lyndon-based feature embeddings of sequencing reads. \item Unlike NLP-based embedding methods, \texttt{lyn2vec} does not require any previous training on text corpus, but it is based on combinatorics on words properties to capture sequence similarities. In Section \ref{ssec:theo-investigation} and Section \ref{sec:evaluation}, we investigate properties of the embedded representations w.r.t. some parameters, such as the specific Lyndon factorization variant used to compute the fingerprint and the value of $k$ used to extract the $k$-fingers from the computed fingerprint. \item The computational complexity of \texttt{lyn2vec} is related to the complexity of the algorithms computing the Lyndon factorizations; as described in Section \ref{ssec:theo-investigation}, such algorithms are linear in the length of the sequence, and so the complexity of the \texttt{lyn2vec} is linear in the total length of sequences. \item We introduce the theoretical notion of collision rate to investigate limitations of the use of Lyndon-based representations and we address the problem of how the lexicographic ordering of the alphabet may affect the collision phenomenon. \item As a proof of concept of the possible use of the proposed embedding representations in machine learning tasks, we have evaluated the effectiveness of such representations when used in the context of assigning RNA-Seq reads to the most likely gene from which they originated as fragments of gene transcripts. % In classifying simulated reads belonging to 100 genes, we get high precision and recall and show that our method outperforms other existing embedding methods. \end{enumerate} This paper is organized as follows. In Section~\ref{sec:related} we discuss the main contributions in literature and the differences with our work. In Section~\ref{sec:lynd-representations} we present the properties of various notions of Lyndon-based factorization, including one inspired by the the double-stranded nature of the genomic sequences. In Section~\ref{sec:evaluation}, we propose some experiments to evaluate the effectiveness of the representations produced by \texttt{lyn2vec}. Finally, in Section~\ref{sec:conclusion} we discuss the results and some future work. \section{Related work} \label{sec:related} The past years have seen impressive advances in sequence mining. State-of-the-art sequence mining methods could be categorized as follows: \textit{(i)} sequence alignment~\cite{stoye1997dca,edgar2010search,fu2012cd}, \textit{(ii)} string kernels~\cite{leslie2004mismatch,kuang2005profile,eskin2002mismatch}, \textit{(iii)} time-series classification~\cite{bagnall2015time,hills2014classification,bostrom2017binary,lines2016hive}, and \textit{(iv)} pattern discovery~\cite{comin2012alignment,didier2012variable,zaki2001spade}. In the following we will focus on the feature embedding of \textit{sequencing reads}. Recent results in the NLP~\cite{mikolov2013efficient,mikolov2013distributed} exploited the \textit{word embedding} in the identification of terms with a similar linguistic context. In this approach, known as \texttt{word2vec}, words or phrases are mapped to vectors of real numbers in a low-dimensional space. By training a neural network over a large text corpus, words with similar linguistic context may be mapped close by in the Euclidean space. In~\cite{asgari2015continuous} % the \texttt{word2vec} framework is applied to the feature extraction from biological sequences. The embeddings generated from their algorithm is named \texttt{BioVec} for general biological sequences and \texttt{ProtVec} for the specific case of proteins. Such representations may be utilized for several common bioinformatics tasks, such as protein-space analysis, protein family classification, and disordered proteins visualization and classification. \texttt{seq2vec}~\cite{kimothi2016distributed} extends the idea proposed in~\cite{asgari2015continuous} by modeling a sequence as a sentence in a text corpus and the $k$-mers derived from such a sequence as words in the sentence, which are given as input to the embedding algorithm. In \cite{fastDNA}, authors propose a novel model for fast classification of DNA sequences, named \texttt{fastDNA}, produced by next-generation sequencing methods. It is based on \texttt{FastText} \cite{bojanowski2016enriching}, which is an extension of \texttt{word2vec}, where the main difference is that instead of using individual words to train the Neural Network, words are broken into several n-grams. In \cite{DNABERT}, instead, another well known NLP model, the Bidirectional Encoder Representations from Transformers (BERT), is adapted to model DNA general embeddings. The result is \texttt{DNABERT}, a novel pre-trained bidirectional encoder representations for DNA-language. The main differences between such sequence embedding methods and the one proposed in this paper, is that they essentially consist of elaborate applications of NLP techniques, in which an embedding model is first trained on a large text corpus, and then used to transform biological sequences in numeric vectors to be used by learning algorithms. Therefore, the increasing space and the computational effort required to embed a sequence dataset remain critical issues. Instead, in our approach we change the initial point of view: we investigate combinatorial properties that would guarantee compact embedding representations of the sequences able to preserve similarities. As a result, we define novel embedding representations which can be computed, for each sequence, in linear time respect to the length of the sequence itself, without requiring any previous training. Furthermore, the ability to capture similarities can be controlled by tuning some parameters, such as the specific factorization used. \section{Lyndon-based-factorizations and \texttt{lyn2vec}} \label{sec:lynd-representations} In this section, we first present the notion of fingerprint and {\em Lyndon-based factorization} \cite{10.2307/1970044}, a factorization of a string which is defined starting from the well-known Lyndon factorization denoted by $\ensuremath{\mathsf{CFL}}\xspace$. The acronym $\ensuremath{\mathsf{CFL}}\xspace$ was used for the first time in \cite{duval1983factorizing}, and built using the initial letters of the authors' surname of the \textit{Lyndon factorization} (Chen, Fox, and Lyndon). Then, we provide details of \texttt{lyn2vec}. \subsection{Lyndon-based factorizations and overlapping strings} \label{ssec:theo-investigation} \paragraph{Basics.} Let $\Sigma$ be a finite alphabet and let $s = a_1 \cdots a_n$ be a {\em string} over $\Sigma$, i.e., a sequence of $n$ characters of $\Sigma$; the \emph{length} $n$ will be also denoted by $|s|$. The character of $s$ at position $i$ (that is, $a_i$) is denoted by $s[i]$. The \textit{substring} (or {\em factor}) of $s$ from position $i$ to position $j$ is denoted by $s[i:j]$. When $i=1$ (resp. $j=|s|$) the factor is named \textit{prefix} (resp. \emph{suffix}) of $s$, denoted also by $s[:j]$ (resp. $s[i:]$). In addition, if $j \ne |s|$ (resp. $i \ne 1$), the prefix (resp. suffix) of $s$ is \emph{proper}. In the following, $\Sigma$ is supposed to be totally ordered w.r.t. the lexicographic order, denoted by $<$. We classically extend this notion on $\Sigma^*$, by defining $s \prec v$ (resp. $s \preceq v$) if $s$ is a proper prefix (resp. $s$ is a prefix of $v$) of $v$ or $s = xay$, $v = xbz$, $a < b$. Symmetrically, $v \succ s$ (resp. $v \succeq s$) if $s \prec v$ (resp. $s \preceq v$) \cite{bonizzoni2018inverse}. For two nonempty strings $s,v$, we write $s \ll v$ if $s \prec v$ and $s$ is not a proper prefix of $v$ \cite{Bannai15}. Finally, due to the particular context considered for assessing the proposed embedding representations (Section~\ref{sec:evaluation}), we must introduce the definition of \emph{reverse and complement} of a string $s$ over the DNA alphabet $\{A,C,G,T\}$, which is a typical notion in Bioinformatics originating from the double-stranded nature of the genomic DNA. Precisely, given $s$, then its reverse and complement is the equal length string $\bar{s}$, such that symbol $\bar{s}[i]$ is the complement of symbol $s[|s|-i+1]$, where the \emph{complement} of a symbol is the operation transforming a symbol $A$ into a symbol $T$ (or vice versa) and a symbol $C$ into a symbol $G$ (or vice versa). \paragraph{Definitions.} Now, we recall the notions of a \emph{factorization} and introduce the notion of a \emph{fingerprint}. These are the main ingredients we use to capture the overlap between two reads. A \emph{factorization} of a string $s$ by a given factorization algorithm $F$, is a sequence $\ensuremath{F}(s) = \langle f_1, f_2, \dots, f_n \rangle$ such that $s = f_1 f_2 \ldots f_n$. We define the \emph{fingerprint} of $s$ with respect to $\ensuremath{F}(s)$ as the sequence $\ensuremath{\mathcal{L}}(s)$ of the lengths of the factors in $\ensuremath{F}(s)$, that is, $\ensuremath{\mathcal{L}}(s) = \langle |f_1|, |f_2|, \dots, |f_n| \rangle$. Given a fingerprint $\ensuremath{\mathcal{L}}(s) = \langle l_1, l_2, \ldots, l_n \rangle$ and an integer $k$ ($1 \leq k \leq n$) a \emph{$k$-finger} is any subsequence $\langle l_i, l_{i+1}, \ldots, l_{i+k-1} \rangle$ of $k$ consecutive lengths, that is, a $k$-mer of $\ensuremath{\mathcal{L}}(s)$. We say that $f_i f_{i+1} \cdots f_{i+k-1}$ is the {\em supporting string} of the $k$-finger. Let $S$ and $F$ be a set of strings and a given factorization algorithm. Let $L_S$ be the set of fingerprints obtained by applying $F$ on each sequence $s \in S$. Let $K$ be the set of $k$-fingers extracted from the fingerprints of $L_S$. We denote by $S_k$ the supporting strings of the $k$-fingers in $K$. Clearly, given a $k$-finger in $K$, we may have more than one string in $S_k$ supporting it. This situation will be discussed in the following Section~\ref{ssec:collisions}. \begin{example} Let us consider the factorization $F(s) = \langle GC, \mathit{ATC}, \mathit{ACCTCT}, CT,$ $\mathit{ACAG}, \mathit{TAT}, A \rangle$. Then, the fingerprint is $\mathcal{L}(s) = \langle 2,3,5,2,4,3,1 \rangle$ and $\langle 2,4,3 \rangle$ is a $k$-finger for $k=3$, whose \emph{supporting string} is $\mathit{CTACAGTAT}$, given by the concatenation of the fourth, fifth and sixth factors $CT$, $\mathit{ACAG}$ and $\mathit{TAT}$. \end{example} Fingerprints used for capturing overlaps are based on factorizations into \emph{Lyndon Words}~\cite{lyndon1954burnside, berstel2007origins}. A string $s$ is a \textit{Lyndon word} if and only if it is strictly smaller than any of its proper suffixes. For example, $s=aabbab$ over alphabet $\{a, b\}$, $a<b$, is a Lyndon word, whereas string $s'=abaabb$ is not a Lyndon word, since the suffix $aabb$ is smaller than $s'$. It is well known that any nonempty string $s$ has a unique factorization $\ensuremath{F}(s) = \langle f_1, f_2, \dots, f_n \rangle$ such that $f_1 \succeq f_2 \succeq \dots \succeq f_n$ and each factor $f_i$ is a Lyndon word. Such a factorization is called the \emph{Lyndon factorization} and is usually denoted by $\ensuremath{\mathsf{CFL}}\xspace$ \cite{10.2307/1970044,lothaire1997combinatorics}. Given $s$, the Duval algorithm computes $\ensuremath{\mathsf{CFL}}\xspace(s)$ in linear time and constant space \cite{duval1983factorizing}. \begin{example} \label{esempio_CFL} Let us consider $s=bbababbaa$ and $s'=aaabbbabab$, with $a<b$. Then, $\ensuremath{\mathsf{CFL}}\xspace(s)=\langle b,b,ababb,a,a \rangle$, whereas $\ensuremath{\mathsf{CFL}}\xspace(s')=\langle aaabbbabab \rangle$, since no suffix is greater than $s'$ and the prefix $aaa$ of $s'$ is smaller than each of its suffixes. \end{example} \paragraph{Conservation property.} We now report a crucial property of $\ensuremath{\mathsf{CFL}}\xspace$~\cite{tcs2020}. To this aim, we need to recall the definition of \textit{simple} substring given in~\cite{lata2020}. A substring $x$ occurring in a string $s$ is \textit{simple} with respect to a factorization $\ensuremath{F}(s) = \langle f_1, f_2, \dots, f_n \rangle$ if, for each occurrence of $x$ in $s$, there is an index $j$ ($1 \leq j \leq n$) such that $x$ is a substring of $f_j$. Informally, every occurrence of $x$ needs to be within some factor $f_j$. This definition can be restricted to a \textit{simple} prefix or suffix by requiring that $x$ is substring of $f_1$ or $f_n$. Let $w =xz$ and $w'= zy$ be two substrings of a string $s = xzy$, i.e., $w$ and $w'$ share a common overlap $z$ in $s$ and suppose that $z$ is a non-simple w.r.t. $\ensuremath{F}(s)$. As a consequence of Lemma 13.2 in \cite{tcs2020}, the strings $w,w'$ share common Lyndon substrings between $\ensuremath{\mathsf{CFL}}\xspace(w)$ and $\ensuremath{\mathsf{CFL}}\xspace(w')$ and with $\ensuremath{\mathsf{CFL}}\xspace(s)$. More precisely, assume that $\ensuremath{\mathsf{CFL}}\xspace(w) = \langle h_1, h_2, \dots, h_n \rangle$ and $\ensuremath{\mathsf{CFL}}\xspace(w') = \langle g_1, g_2, \dots, g_m \rangle$. If $z$ is both a non-simple suffix of $F(w)$ and a non-simple prefix of $\ensuremath{F}(w')$, then there will exist two indexes $i,j$, with $1 \leq i < n$, $1 < j \leq m$, such that $z = h''_i h_{i+1} \cdots h_{n} = g_1 \cdots g_{j-1}g'_j$, where $h''_i$ is a suffix of $h_i$ and $g'_j$ is a prefix of $g_j$. Given $\ensuremath{\mathsf{CFL}}\xspace(h''_i) = \langle m_1, \ldots , m_r \rangle$ and $\ensuremath{\mathsf{CFL}}\xspace(g'_j) = \langle v_1, \ldots , v_t \rangle$, then, by the above mentioned result, we have $\ensuremath{\mathsf{CFL}}\xspace(z) = \langle m_1, \ldots , m_r, h_{i+1}, \ldots , h_{n} \rangle = \langle g_1, \ldots ,g_{j-1}, v_1, \ldots , v_t \rangle$. We can reformulate the above result as a \textit{Conservation property} as follows. Let $s$ be a string such that $\ensuremath{\mathsf{CFL}}\xspace(s) = \langle f_1, f_2, \ldots, f_n \rangle$ and let $w, w'$ be substrings of $s$ such that $w=xz$ and $w'=zy$ share a common overlap $z$, where $z=f'_l f_{l+1} \cdots f_{t} f_{t+1}^{'}$ for some indexes $l, t$ with $1 <l,t < n$, and $f_l=f''_lf'_l$, $f_{t+1}=f'_{t+1}f''_{t+1}$. The Conservation property states that $\ensuremath{\mathsf{CFL}}\xspace(w)$ and $\ensuremath{\mathsf{CFL}}\xspace(w')$ share the consecutive factors $f_{l+1}, \ldots, f_{t}$, i.e., $\ensuremath{\mathsf{CFL}}\xspace(w)=\langle \ensuremath{\mathsf{CFL}}\xspace(xf'_l),f_{l+1}, \ldots f_{t}, \ensuremath{\mathsf{CFL}}\xspace(f_{t+1}^{'}) \rangle$ and $\ensuremath{\mathsf{CFL}}\xspace(w')=\langle \ensuremath{\mathsf{CFL}}\xspace(f'_l),f_{l+1}, \ldots f_{t}, \ensuremath{\mathsf{CFL}}\xspace(f'_{t+1}y) \rangle$. Similarly, $\ensuremath{\mathcal{L}}(w)$ and $\ensuremath{\mathcal{L}}(w')$ share the consecutive lengths $|f_{l+1}|, \ldots, |f_{t}|$. It follows that two overlapping strings $w$ and $w'$ share consecutive common Lyndon factors in their Lyndon factorizations. Thus, the fingerprints of $w$ and $w'$ will share consecutive integers. Figure \ref{fig:conservation} illustrates the conservation property. Such an interesting property suggests the possibility of using directly $k$-fingers as features. Indeed, as we will see in Section \ref{sec:evaluation}, to assess such an intuition, we also proposed an approach in which we used $k$-fingers for classifying sequencing reads. \begin{figure}[t!] \includegraphics[width=0.99\linewidth]{conservation.pdf} \caption{An example of Conservation property for the words $s$ such that $\ensuremath{\mathsf{CFL}}\xspace(s) = \langle f_1, f_2, \dots, f_{10} \rangle$ and $z$ where $z=f'_4 f_{5} f_{6} f_{7} f_{8}^{'}$, $f'_4$ and $f_{8}^{'}$ are a suffix and a prefix respectively of $f_4$ and $f_{8}$. Then $\ensuremath{\mathsf{CFL}}\xspace(z) = \langle \ensuremath{\mathsf{CFL}}\xspace(f'_4), f_{5}, f_{6}, f_{7}, \ensuremath{\mathsf{CFL}}\xspace(f_{8}^{'}) \rangle$.} \label{fig:conservation} \end{figure} \paragraph{Lyndon-based factorizations.} To summarize, as a consequence of the above discussion, two main properties can be observed: \textit{(i)} the fingerprint ability of preserving similarities, \textit{(ii)} the possibility of tuning the $k$ value to control the size of the overlapping substrings. The latter property suggests a further investigation on variants of the Lyndon factorization (that we call \textit{Lyndon-based}) which could guarantee similar properties. Specifically, we introduce two types of Lyndon-based factorization: \textit{single-stranded} factorization (for dealing with sequencing reads derived from a unique genome strand) and \textit{double-stranded} factorization (for dealing with sequencing reads derived from both strands of a genome). At this point, we recall the notion of \textit{inverse Lyndon word} given in \cite{bonizzoni2018inverse}: a string $s$ is an Inverse Lyndon word if each proper suffix is strictly smaller than $s$. For instance, $a, b, aaaaa, bbba, baaab, bbaba$ are Inverse Lyndon words over $\{a, b\}$, with $a < b$. A factorization $\ensuremath{F}(s) = \langle f_1, f_2, \dots, f_n \rangle$ of a string $s$ is an \emph{Inverse Lyndon factorization} if $f_j$ is an Inverse Lyndon word for $1 \le j \le n$ and $f_1 \ll f_2 \ll \dots \ll f_n$. Bonizzoni et al.~\cite{bonizzoni2018inverse} proposed a linear time algorithm to produce a special Inverse Lyndon factorization which is unique for the string, called \emph{Canonical Inverse Lyndon factorization} or \textit{Inverse $\ensuremath{\mathsf{CFL}}\xspace$} (referred in the following by $\ensuremath{\mathsf{ICFL}}\xspace$). Also $\ensuremath{\mathsf{ICFL}}\xspace$ (as well as $\ensuremath{\mathsf{CFL}}\xspace$) both guarantees uniqueness and linear time computation. In addition, by definition of $\ensuremath{\mathsf{ICFL}}\xspace$, a factor in $\ensuremath{\mathsf{ICFL}}\xspace$ cannot be a prefix of the next one, thus $\ensuremath{\mathsf{ICFL}}\xspace$ is less prone to split a string in two different factors. Interestingly, as proved in \cite{bonizzoni2018inverse}, $\ensuremath{\mathsf{ICFL}}\xspace$ allows to split any Lyndon word, thus allowing to further factorize long Lyndon factors of Lyndon factorizations (as well as $\ensuremath{\mathsf{CFL}}\xspace$ allows to split any inverse Lyndon word). \begin{example} \label{esempio_ICFL} Let us consider the sequences $s=bbababbaa$ and $s'=aaabbbabab$ used in Example \ref{esempio_CFL}. We have that $\ensuremath{\mathsf{ICFL}}\xspace(s)=\langle s \rangle$, since $s$ is an inverse Lyndon word, and $\ensuremath{\mathsf{ICFL}}\xspace(s')=\langle aaa,bbbabab\rangle$. \end{example} For an extended discussion of the theoretical background of these factorizations, we refer to~\cite{bonizzoni2018inverse} with particular attention to examples 4.7 and 7.2 for a comparison between $\ensuremath{\mathsf{CFL}}\xspace$ and $\ensuremath{\mathsf{ICFL}}\xspace$. We call $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ the factorization obtained by applying first the $\ensuremath{\mathsf{CFL}}\xspace$, and then the $\ensuremath{\mathsf{ICFL}}\xspace$ to factors longer than a given threshold $T$ (a similar definition can be done for $\ensuremath{\mathsf{ICFL\_CFL}}\xspace$, by symmetry). In other words, given $T$ and $\ensuremath{\mathsf{CFL}}\xspace(s) = \langle f_1, f_2, \dots, f_n \rangle$, we obtain $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ by replacing each $f_i$ longer than $T$ with $\ensuremath{\mathsf{ICFL}}\xspace(f_i)$. The $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ has several advantages over $\ensuremath{\mathsf{CFL}}\xspace$ or $\ensuremath{\mathsf{ICFL}}\xspace$. Indeed, the $\ensuremath{\mathsf{ICFL}}\xspace$ factorization, applied on long factors of a $\ensuremath{\mathsf{CFL}}\xspace$ factorization, % enriches the factorization (and the fingerprint) in terms of number of factors. % A similar advantage is provided by $\ensuremath{\mathsf{ICFL\_CFL}}\xspace$ and a discussion is given in paragraph {\em Factor length distribution in Lyndon-based factorizations} below. Examples below show applications of $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ and $\ensuremath{\mathsf{ICFL\_CFL}}\xspace$. \begin{example} \label{esempio_CFL_ICFL} Let $a<b<c<d$ and $s''=dabadabdabdadac$. We have that $\ensuremath{\mathsf{CFL}}\xspace(s'')=\langle d,abadabdabdadac \rangle$ whereas $\ensuremath{\mathsf{ICFL}}\xspace(s'')=\langle daba,dabdab,dadac \rangle$. Now, we can split the second factor of $\ensuremath{\mathsf{CFL}}\xspace(s'')$ by applying $\ensuremath{\mathsf{ICFL}}\xspace$ on this factor, i.e., $\ensuremath{\mathsf{CFL\_ICFL}}\xspace(s'')=\langle d, \langle a,ba,\mathit{dabdab},$ $dadac \rangle \rangle$. \end{example} \begin{example} \label{esempio_ICFL_CFL} Let $a<b<c<d$ and $s''=dabadabdabdadac$. $s'''=adbadbadba$ and $\ensuremath{\mathsf{CFL}}\xspace(s''')=\langle adb,adb,adb,a \rangle$ and $\ensuremath{\mathsf{ICFL}}\xspace(s''')=\langle a, dbadbadbadba \rangle$. Finally, $\ensuremath{\mathsf{ICFL\_CFL}}\xspace(s''')=\langle a, \langle d,b,adb,adb,a \rangle \rangle$. \end{example} So, in Example \ref{esempio_CFL_ICFL}, $\ensuremath{\mathsf{ICFL}}\xspace$ provides better results in terms of factor length distribution, whereas in Example \ref{esempio_ICFL_CFL}, $\ensuremath{\mathsf{CFL}}\xspace$ is better than $\ensuremath{\mathsf{ICFL}}\xspace$. Thus, in general, we cannot say which is the best factorization. However, we can only observe that while the Conservation property holds for $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ (since $\ensuremath{\mathsf{ICFL}}\xspace$ splits again Lyndon factors), it is an open problem to formally prove the property for $\ensuremath{\mathsf{ICFL}}\xspace$, which seems to hold also in this case, as suggested in the experiments. Figure~\ref{fig:read-factorizations} below shows an example of $\ensuremath{\mathsf{CFL}}\xspace$, $\ensuremath{\mathsf{ICFL}}\xspace$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ for two 125-long overlapping reads. \begin{figure}[t!] \includegraphics[width=0.99\linewidth]{read-factorization.pdf} \caption{$\ensuremath{\mathsf{CFL}}\xspace$, $\ensuremath{\mathsf{ICFL}}\xspace$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ for a threshold $T=10$ are depicted for two overlapping 125-long reads $s1$ and $s2$ (the overlap is highlighted in blue) together with their fingerprints. The common factors are underlined. The $\ensuremath{\mathsf{CFL}}\xspace$ produces the $3$-finger $\langle 34,19,16 \rangle$, whereas there are no common factors for $\ensuremath{\mathsf{ICFL}}\xspace$ (observe the long factors at the end of each read). The $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$-10, obtained by applying first $\ensuremath{\mathsf{CFL}}\xspace$ and then $\ensuremath{\mathsf{ICFL}}\xspace$ to factors longer than $10$, yields $17$ consecutive common factors between the reads, and a $17$-finger in the fingerprints.} \label{fig:read-factorizations} \end{figure} \paragraph{Double-stranded factorization.} Due to the double-stranded nature of the genome, we are interested in signatures able to highlight the common regions between two overlapping reads originating from opposite strands. To this aim, given a Lyndon-based factorization $\ensuremath{F}$ (see the previous Section~\ref{ssec:theo-investigation}), we introduce the definition of \emph{double-stranded} factorization algorithm $\ensuremath{F}\ensuremath{^{d}}$ built on the (basic) algorithm $\ensuremath{F}$, having the fundamental property stated by the following Theorem~\ref{prop:comb}. The main idea is the following: given a sequence $s$, we would like a factorization such that the factorization of its reverse and complement $\bar{s}$ is the reverse sequence of its reverse and complement factors. As we will see further in detail, this goal is reached by applying to $s$ and $\bar{s}$ a basic algorithm $F$ and appropriately combining the two obtained fingerprints. \begin{theorem} \label{prop:comb} Given a \emph{double-stranded} factorization $\ensuremath{F}\ensuremath{^{d}}(s) = \langle f_1, f_2, \dots, f_n \rangle$ of a string $s$, then the \emph{double-stranded} factorization of the reverse and complement of $s$ is $\ensuremath{F}\ensuremath{^{d}}(\bar{s}) = \langle \bar{f}_n, \bar{f}_{n-1}, \dots, \bar{f}_1 \rangle$, where $\bar{f}_{i}$ is the reverse and complement of factor $f_i$. \end{theorem} It follows that the fingerprint $\ensuremath{\mathcal{L}}(s)=\langle l_1, l_2, \dots, l_n \rangle$ ($l_i = |f_i|$) is equal to the reverse of the fingerprint $\ensuremath{\mathcal{L}}(\bar{s})=\langle l'_1, l'_2, \dots, l'_n \rangle$ ($l'_i = |\bar{f}_{n-i+1}|$). In particular, given a $k$-finger $\langle l_i, l_{i+1} \cdots, l_{i+k-1} \rangle$ of $\ensuremath{\mathcal{L}}(s)$, we refer to the $k$-finger $\langle l_{n-i+1}, l_{n-i}, \cdots, l_{n-i-k+2} \rangle$ of $\ensuremath{\mathcal{L}}(\bar{s})$ as its \emph{counterpart}, since they are clearly supported by the same string except for a reverse and complement operation. Note that any $k$-finger of $\ensuremath{\mathcal{L}}(s)$ is the reverse of its counterpart on $\ensuremath{\mathcal{L}}(\bar{s})$. For this reason, in order to detect the common regions among a set of reads originating from both strands of the genome, it is necessary to perform the following operation on the $k$-fingers: given a $k$-finger, we need to consider the lexicographically smallest sequence of integers between the $k$-finger and its reverse version, assuming that the $k$-finger is a sequence over the alphabet of the positive integers. For example, the $k$-finger $\langle 4,3,7,8,5 \rangle$ outputs $\langle 4,3,7,8,5 \rangle$ itself, whereas the $k$-finger $\langle 5,10,7,8,5 \rangle$ outputs the reverse $\langle 5,8,7,10,5 \rangle$. In the following we will provide the details about the construction of the double-stranded factorization for a string $s$ (given a basic factorization algorithm $\ensuremath{F}$) and next we will prove Theorem~\ref{prop:comb}. In order to do so, we firstly introduce the notion of \textit{interval-sequence} of a fingerprint $\ensuremath{\mathcal{L}}(s)= \langle l_1, l_2, \dots, l_n \rangle$ as the sequence $\mathcal{I}(s) = \langle i_1, i_2, \dots, i_{n} \rangle$ such that $i_j = l_1 + \cdots + l_j$ (ending position on string $s$ of factor $f_j$). Moreover, given a fingerprint $\ensuremath{\mathcal{L}}(s)$, we call \emph{reversed interval-sequence} $\mathcal{I}^r(s)$ the interval-sequence of the reverse of $\ensuremath{\mathcal{L}}(s)$. For example, given $\ensuremath{\mathcal{L}}(s) = \langle 1, 1, 7, 6 \rangle$, then $\mathcal{I}(s) = \langle 1, 2, 9, 15 \rangle$ is the interval-sequence and $\mathcal{I}^r(s) = \langle 6, 13, 14, 15 \rangle$ is the reversed interval-sequence. Note that more in general the interval-sequence can be defined with respect to any sequence $\langle l_1, l_2, \dots, l_n \rangle$ of positive integers. In the following we say that a strictly increasing sequence $\langle i_1, i_2, \dots, i_{n} \rangle$ of positive integers {\em induces} the sequence $\langle l_1, l_2, \dots l_n \rangle$, where $l_1 = i_1$ and $l_j = i_j - i_{j-1}$ for $1 < j \le n$. In turn, this sequence $\langle l_1, l_2, \dots l_n \rangle$ is the fingerprint that \emph{induces} on $s$ the factorization $\langle s[:i_1], s[i_1:i_2], \dots, s[i_{n-1}:] \rangle$. At this point, given a (basic) factorization algorithm $\ensuremath{F}$, the double-stranded factorization $\ensuremath{F}\ensuremath{^{d}}$ is defined as follows. \begin{definition} Let $\ensuremath{\mathcal{L}}(s)$ and $\ensuremath{\mathcal{L}}(\bar{s})$ be the fingerprints for a string $s$ and its reverse and complement $\bar{s}$ (respectively) obtained by applying $\ensuremath{F}$. Let $\mathcal{I}(s)$ be the interval-sequence of $\ensuremath{\mathcal{L}}(s)$ and let $\mathcal{I}^r(\bar{s})$ be the reversed interval-sequence of $\ensuremath{\mathcal{L}}(\bar{s})$. The \emph{double-stranded} factorization $\ensuremath{F}\ensuremath{^{d}}(s)$ for $s$ is the factorization induced by the fingerprint induced by the increasing sequence obtained by merging $\mathcal{I}(s)$ and $\mathcal{I}^r({\bar{s}})$. \end{definition} \begin{example} \label{ex:fact-comb} Let $s=\mathit{GGATCTCGCAGGCGG}$ be a string and $\bar{s} = \mathit{CCGCCTGCGAGATCC}$ be its reverse and complement. By considering $\ensuremath{\mathsf{CFL}}\xspace$ as basic factorization algorithm, we have $\ensuremath{\mathsf{CFL}}\xspace(s) = \langle G, G, \mathit{ATCTCGC}, \mathit{AGGCGG} \rangle$ and $\ensuremath{\mathsf{CFL}}\xspace(\bar{s}) = \langle \mathit{CCGCCTGCG}, \mathit{AGATCC} \rangle$. The fingerprint and the interval-sequence for $s$ are $\langle 1, 1, 7, 6 \rangle$ and $\langle 1, 2, 9, 15\rangle$ respectively, whereas the fingerprint and the reversed interval-sequence for $\bar{s}$ are $\langle 9, 6 \rangle$ and $\langle 6, 15 \rangle$, respectively. The increasing sequence $\langle 1, 2, 6, 9, 15 \rangle$, obtained by merging $\langle 1, 2, 9, 15\rangle$ and $\langle 9, 6 \rangle$, induces the sequence $\langle 1, 1, 4, 3, 6 \rangle$, which in turn induces the double-stranded factorization $\ensuremath{\mathsf{CFL}}\xspace^d(s) = \langle G, G, \mathit{ATCT}, \mathit{CGC}, \mathit{AGGCGG} \rangle$. The double-stranded fingerprint of $s$ will be $\langle 1, 1, 4, 3, 6 \rangle$. Vice versa, the fingerprint and the interval-sequence for $\bar{s}$ are $\langle 9, 6 \rangle$ and $\langle 9, 15 \rangle$, while the fingerprint and the reversed interval-sequence for $s$ are $\langle 1, 1, 7, 6 \rangle$ and $\langle 6, 13, 14, 15 \rangle$. The increasing sequence $\langle 6, 9, 13, 14, 15 \rangle$, obtained by merging $\langle 9, 15 \rangle$ and $\langle 6, 13, 14, 15 \rangle$, induces on $\bar{s}$ the sequence $\langle 6, 3, 4, 1, 1 \rangle$, which in turn induces on $\bar{s}$ the double-stranded factorization $\ensuremath{\mathsf{CFL}}\xspace^d(\bar{s})$ $=$ $\langle \mathit{CCGCCT}, \mathit{GCG}, \mathit{AGAT}, C, C \rangle$. The double-stranded fingerprint of $\bar{s}$ is $\langle 6, 3, 4, 1, 1 \rangle$. \end{example} The previous example gives an intuition of the proof of Theorem~\ref{prop:comb}. $\ensuremath{\mathsf{CFL}}\xspace^d(s)$ and $\ensuremath{\mathsf{CFL}}\xspace^d(\bar{s})$ have both five factors and the $i$-th factor of $\ensuremath{\mathsf{CFL}}\xspace^d(s)$ is the reverse and complement of the of the $(5-i+1)$-th factor of $\ensuremath{\mathsf{CFL}}\xspace^d(\bar{s})$. For example, the fourth factor $CGC$ of $\ensuremath{\mathsf{CFL}}\xspace^d(s)$ is the reverse and complement of the "symmetrical" second factor $GCG$ of $\ensuremath{\mathsf{CFL}}\xspace^d(\bar{s})$. As a consequence, observe that the fingerprint $\langle 1, 1, 4, 3, 6 \rangle$ of $s$ is the reverse of fingerprint $\langle 6, 3, 4, 1, 1 \rangle$ of $\bar{s}$. The trivial $k$-finger $\langle 1, 4 \rangle$ of $s$ supported by string $GATCT$ has its counterpart in the $k$-finger $\langle 4, 1 \rangle$ of $\bar{s}$ supported by string $AGATC$ and they are manifestly in a reverse and complement relation. In order to prove Theorem~\ref{prop:comb}, we need two technical lemmas. \begin{lemma} \label{prop:rev-comb1} Let $\mathcal{L}_1 = \langle l_1, l_2, \dots, l_n \rangle$ and $\mathcal{L}_2 = \langle l'_1, l'_2, \dots, l'_n \rangle$, be two sequences with the same number $n$ of positive integers. Let $\mathcal{I}_1 = \langle i_1, i_2, \dots, i_n \rangle$ and $\mathcal{I}_2 = \langle i'_1, i_2^{'}, \dots, i_n^{'} \rangle$ be the respective interval-sequences. Then, $\mathcal{L}_1$ is equal to the reverse of $\mathcal{L}_2$ iff $i_j = i'_n - i'_{n-j} \mbox{, for } 1 \le j \le n - 1$. \end{lemma} \begin{proof} The $j$-th element in $\mathcal{L}_1$ is $l_j = i_j - i_{j-1}$, by definition. If $i_j = i'_n - i'_{n-j}$, then $i_{j-1} = i'_n - i'_{n-j+1}$. Therefore, $$l_j = i_j - i_{j-1} = i'_n - i'_{n-j} - i'_n + i'_{n-j+1} = i'_{n-j+1} - i'_{n-j}$$ which is, by definition, the $(n - j + 1)$-th element of $\mathcal{L}_2$. \end{proof} We denote by $\mathcal{L}_1 \oplus \mathcal{L}_2$ the sequence {\em induced} by the increasing sequence obtained by merging the interval-sequences of $\mathcal{L}_1$ and $\mathcal{L}_2$. It is not difficult to use Lemma~\ref{prop:rev-comb1} and prove that such \emph{induced} sequence is equal to the reverse of the sequence induced by merging the interval-sequences of the reverse of $\mathcal{L}_1$ and $\mathcal{L}_2$. Then, denoting by $\mathcal{L}_1^r$ and $\mathcal{L}_2^r$ the reverse of the sequences, the following Lemma can be stated. \begin{lemma} \label{prop:rev-comb2} Given two sequences $\mathcal{L}_1$ and $\mathcal{L}_2$ with the same number $n$ of elements, then $\mathcal{L}_1 \oplus \mathcal{L}_2$ is equal to the reverse of $\mathcal{L}_1^r \oplus \mathcal{L}_2^r$. \end{lemma} \noindent Now, Theorem \ref{prop:comb} can be proved as a consequence of Lemmas~\ref{prop:rev-comb1} and \ref{prop:rev-comb2}. By definition, the double-stranded factorization $\ensuremath{F}\ensuremath{^{d}}(s)$ is \emph{induced} by the fingerprint $\ensuremath{\mathcal{L}}(s) \oplus \ensuremath{\mathcal{L}}(\bar{s})^r$ where $\ensuremath{\mathcal{L}}(s)$ and $\ensuremath{\mathcal{L}}(\bar{s})$ are the fingerprints of $s$ and its reverse and complement $\bar{s}$ (respectively) obtained by applying algorithm $\ensuremath{F}$. Similarly, $\ensuremath{\mathcal{L}}(\bar{s}) \oplus \ensuremath{\mathcal{L}}(s)^r$ is the fingerprint inducing $\ensuremath{F}\ensuremath{^{d}}(\bar{s})$. By Lemma~\ref{prop:rev-comb2}, we have that $\ensuremath{\mathcal{L}}(s) \oplus \ensuremath{\mathcal{L}}(\bar{s})^r$ (fingerprint of $s$) is equal to the reverse of $\ensuremath{\mathcal{L}}(s)^r \oplus (\ensuremath{\mathcal{L}}(\bar{s})^r)^r$. Since $(\ensuremath{\mathcal{L}}(\bar{s})^r)^r$ is $\ensuremath{\mathcal{L}}(\bar{s})$, then $\ensuremath{\mathcal{L}}(s) \oplus \ensuremath{\mathcal{L}}(\bar{s})^r$ is the reverse of $\ensuremath{\mathcal{L}}(s)^r \oplus \ensuremath{\mathcal{L}}(\bar{s})$ (fingerprint of $\bar{s}$) and Theorem~\ref{prop:comb} is proved. \paragraph{Computational complexity of Lyndon-based factorization algorithms.} The computational complexity of the algorithms to compute the Lyndon-based factorizations plays a crucial role in the realization of \texttt{lyn2vec}. As explained above, $\ensuremath{\mathsf{CFL}}\xspace$ and $\ensuremath{\mathsf{ICFL}}\xspace$ can be computed in linear time and constant space. Let us consider $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ for simplicity (the algorithm for $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ will be pretty similar). Then We are able to compute them in linear time. The idea is to use a main process for computing the $\ensuremath{\mathsf{CFL}}\xspace$ factorization of the input read, and, as the $\ensuremath{\mathsf{CFL}}\xspace$ factors are computed, a new (parallel) process applies $\ensuremath{\mathsf{ICFL}}\xspace$ on each of them. In conclusion, the factorization can be computed in linear time. \paragraph{Factor length distribution in Lyndon-based factorizations and conservation property.} The conservation property allows to capture the similarity between two strings. However, in the degenerate case of factorizations consisting of singleton factors, the conservation property does not apply. Moreover, the property has been proved for $\ensuremath{\mathsf{CFL}}\xspace$ and its extension to $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ is a trivial consequence of the fact that we factorize the long $\ensuremath{\mathsf{CFL}}\xspace$ factors obtained in the common substrings of two strings. We currently do not have a proof that the conservation property holds for $\ensuremath{\mathsf{ICFL}}\xspace$, but the high accuracy of experimental results suggest the validity of this conjecture. Undoubtedly, the number of factors in a factorization affects the possibility of detecting common regions of two substrings: the higher the number of factors is, the more likely the detection of the common regions will be. An experimental analysis has been performed to investigate the distribution of the number of factors for the Lyndon-based factorizations computed on a simulated error-free dataset. The dataset was simulated by using \texttt{dwgsim}~\cite{homerdwgsim} and includes 21 million 150-long reads extracted from the region \texttt{960,000}-\texttt{80,960,000} of the human Chromosome 1, for a total of 80 million bases. \begin{figure}[t!] \centerline{\includegraphics[width=.99\textwidth]{number-of-factors.png}} \caption{Distribution of the number of factors. The factorization algorithms are listed in the legend by decreasing peak.} \label{fig:number-of-factors} \end{figure} Figure~\ref{fig:number-of-factors} shows, for each factorization algorithm, the distribution of the number of factors per read. Note that $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ produces about twice as much factors than any other factorization, whereas $\ensuremath{\mathsf{CFL}}\xspace$, $\ensuremath{\mathsf{ICFL}}\xspace$, and $\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$ produce a small number of factors with a low variance in the distribution. In general it is worth observing that the question on how many factors are present in a Lyndon factorization has been recently faced in~\cite{stacs2021}. \subsection{Uniqueness of the fingerprint and k-fingers: the collision phenomenon} \label{ssec:collisions} The properties discussed above play an important role in \texttt{lyn2vec}'s effectiveness, since they allow us to state that our representation method can capture higher orders of similarities without significant increase in the computation. In this section, we face the following problem: given a sequence, the corresponding representation produced by its fingerprint or by its k-fingers is \textit{unique}? As we will see, such a property is closely related to the \textit{collision phenomenon}. \paragraph{Collision definition.} We recall that one of our main aim is to use $k$-fingers for capturing the similarity of two sequences. As already said, we must pay attention to the fact that distinct strings may have have common $k$-fingers as shown in the example below. \begin{example} Let us consider $x = CCGGTT$ and $y = AACCGG$. Then $\ensuremath{\mathsf{ICFL}}\xspace(x) = \langle CC,GG,TT \rangle$ and $\ensuremath{\mathsf{ICFL}}\xspace(y) = \langle AA,CC,GG \rangle$. Thus, $\ensuremath{\mathcal{L}}(x)=\langle 2,2,2 \rangle$ and $\ensuremath{\mathcal{L}}(y)=\langle 2,2,2 \rangle$. Now, if we set $k = 3$, we obviously have that $\langle 2,2,2 \rangle$ is a $k$-finger which is supported by $x$ and by $y$. \end{example} The example above describes the collision phenomenon when we use Lyndon-based factorizations. We can define the $k$-finger collision in our context as follows. \begin{definition} [$k$-finger collision] \label{def:collision} Let $x,y \in \Sigma^*$ be two strings and let $\ensuremath{F}$ be a Lyndon-based factorization. Let $\ensuremath{\mathcal{L}}(x)$ and $\ensuremath{\mathcal{L}}(y)$ be the fingerprints for $x$ and $y$ with respect to $F$, respectively. Let $\mathcal{K}_x$ be a $k$-finger of $\ensuremath{\mathcal{L}}(x)$ and $\mathcal{K}_y$ be a $k$-finger of $\ensuremath{\mathcal{L}}(y)$. Let $s_{\mathcal{K}_x}$ and $s_{\mathcal{K}_y}$ be two factors of $x$ and $y$ supporting $\mathcal{K}_x$ and $\mathcal{K}_y$, respectively. If $\mathcal{K}_x = \mathcal{K}_y$ and $s_{\mathcal{K}_x} \neq s_{\mathcal{K}_y}$, then we say that there exists a \emph{collision} between $s_{\mathcal{K}_x}$ e $s_{\mathcal{K}_y}$ (w.r.t. the same $k$-finger $\mathcal{K}_x$). \end{definition} Let $w$ be a sequence of length $s$ and let $\Sigma_s$ be the alphabet of the lengths of a fingerprint of $w$. Clearly, a $k$-finger of $w$ is a $k$-mer over the alphabet $\Sigma_s$. The collision phenomenon can be studied by exploiting results already obtained in literature in the case of $k$-mers \cite{mhap,mash}. Observe that, the length of the fingerprints can vary for each read considered, and so, to extend those results to our case we will indicate with $s$ the \textit{mean length} of a generic set of reads considered. \paragraph{Collision measure.} Given a dataset $S$ of sequences, a Lyndon-based factorization, and a value for $k$, the next question is: ``How can we measure the collisions?''. A naive counting method could be the following: for each $k$-finger $\mathcal{K}_x$, consider all the sequences in $S_{\mathcal{K}_x}$ that support $\mathcal{K}_x$, and define $count(s_{\mathcal{K}_x})$ the number of occurrences of the string $s_{\mathcal{K}_x} \in S_{\mathcal{K}_x}$ as supporting sequence of $\mathcal{K}_x$. We denote all the different pairs of such supporting strings by $c_{\mathcal{K}_x} = \prod_{s_{\mathcal{K}_x} \in S_{\mathcal{K}_x}} count(s_{\mathcal{K}_x})$. Loosely speaking, $c_{\mathcal{K}_x}$ represents the effective number of possible collisions with respect to $\mathcal{K}_x$. Finally, let $\cal K$ be the set of different $k$-fingers generated, the total number of collisions which can occur is $\sum_{\mathcal{K}_x \in {\cal K}} c_{\mathcal{K}_x}$. The reference to $\mathcal{K}_x$ is dropped if it is clear from the context. \begin{example} Let $\alpha=\langle 2,2,2 \rangle$ be a $k$-finger. Let $s_1=AACCGG$, $s_2=AACCTT$ and $s_3=CCGGTT$ be the different corresponding sequences in $S$ with $count(s_1) = 3$, $count(s_2) = 4$ and $count(s_3) = 5$. Then the number of collisions with respect to the $k$-finger $\mathcal{K}_x$ is $c_{\mathcal{K}_x} = count(s_1) \times count(s_2) \times count(s_3)$ $=$ $3 \times 4 \times 5$ $=$ $60$. \end{example} When used on large datasets, such a method presents several obvious disadvantages. First, the numbers generated can be huge and the time required to calculate them can be too much expensive. Second, such calculated numbers do not give any statistical information which can then be used for comparisons. Thus, we need of a novel metric to measure the phenomenon defined above. Here we propose a novel metric, named \textit{collision rate}. \begin{definition}[\textit{Collision rate}] Let $S$ be a set of sequences, $\ensuremath{F}$ be a factorization, $L_S$ be the set of fingerprints obtained by applying $\ensuremath{F}$ on each string in $S$. Let $K$ be the set of distinct $k$-fingers extracted from $L_S$, and $S_K$ be the set of distinct sequences supporting the $k$-fingers in $K$. Then, the collision rate is $c_r$ $=$ $\frac{|S_K|}{|K|}$. \end{definition} \begin{example} Let $K=\{\langle 2,2,2 \rangle\}$ be the set of distinct $k$-fingers extracted, and let $S_K = \{AACCGG, AACCTT, CCGGTT\}$ be the set of distinct subsequences corresponding to $k$-fingers in $K$. Then, the collision rate is $c_r = \frac{|S_K|}{|K|} = \frac{3}{1} = 3$. \end{example} ``What does this metric express?''. Intuitively, the collision rate represents the average number of distinct sequences corresponding to the same $k$-finger. Let us observe, that such a metric is obviously related to the collision phenomenon. In fact, in the best case $|K| = |S_K|$ and so $c_r = 1$, i.e., for each $k$-finger there exists a single corresponding sequence, thus no collision can occur. As the size of $S_K$ increases, then also the number of possible sequences corresponding to each $k$-finger increases and therefore the probability of collision also increases. In the next paragraph, we prove some theoretical properties regarding the causes of the collisions. Then, we investigate if the order of the characters in the alphabet may intervene in this problem. It is worth of note that in general, the questions of finding an optimal alphabet ordering for Lyndon factorization (i.e., such that number of Lyndon factors is at most, or at least, $n$, for a given number $n$) is hard (\cite{stacs2021}). \paragraph{Collision-free perspectives: the superfingerprint.} For a string $s$, $alph(s)$ denotes the set of symbols in $s$. In the following we denote by $\Sigma = \{a_1, \ldots, a_n\}$ a finite alphabet and $(a_1, \ldots, a_n)$ the totally ordered alphabet $(\Sigma, <)$, where $ < $ is defined by $a_i < a_{i+1}$ for $i = 1, \ldots, n-1$. In other words, $ < $ is such that $(a_1, \ldots, a_n)$ is a sorted list in increasing order. In what follows, $\Pi_{\Sigma}$ stands for the set of all totally ordered alphabets defined by the possible orderings of the symbols in $\Sigma$. For each $p \in \Pi_{\Sigma}$, we write $<_p$ to denote the lexicographic order induced by $p$. Moreover, if $L \in \{\ensuremath{\mathsf{CFL}}\xspace, \ensuremath{\mathsf{ICFL}}\xspace \}$, then $L_p$ will be referred to $<_p$. When $p=(A,C,G,T)$, we denote by $\bar{p}=(T,G,C,A)$ the inverse ordering of $p$. \begin{example} Let $\Sigma = \{A,C,G,T\}$, $x = CAG$ and $y = ACG$. Let $p, p' \in \Pi_{\Sigma}$, where $p = (A,C,G,T)$, $p' = (C,A,G,T)$. We have $y <_p x$ and $x <_{p'} y$. \end{example} \begin{example} Let $\Sigma = \{A,C,G,T\}$ and $x = CAACAC$. Let $p, p' \in \Pi_{\Sigma}$, where $p = (A,C,G,T)$, $p' = (C,A,G,T)$. Then $\ensuremath{\mathsf{ICFL}}\xspace_{p}(x) = \langle CAA,CAC \rangle$, while $\ensuremath{\mathsf{ICFL}}\xspace_{p'}(x) = \langle C,AACAC \rangle$. \end{example} The position of even a few symbols in the order of the used alphabet may have a significant impact on the Lyndon-based factorizations. Under some conditions, even just by changing the relative position of two symbols, some words that were Lyndon words before the change may no longer be (see Proposition \ref{P1}), thus leading to a change in the whole factorization. % The following proposition shows that given two words having distinct alphabet, then they have distinct Lyndon-based factorizations under permutations of the alphabet. \begin{proposition} \label{P1} Let $\Sigma$ be a finite alphabet. Let $x,y \in \Sigma^*$ be such that $alph(x) \not = alph(y)$ and $|x| = |y| > 1$. For any $p \in \Pi_{\Sigma}$ there exists $p' \in \Pi_{\Sigma}$ such that only one of the orderings of $alph(x)$ and of $alph(y)$ is changed in $p'$. Moreover, if $x$ and $y$ are both Lyndon (resp. inverse Lyndon) words with respect to $ <_p$, then only one of $x$ and $y$ is a Lyndon (resp. inverse Lyndon) word with respect to $ <_{p'}$. \end{proposition} \begin{proof}% Let $x,y \in \Sigma^*$ be such that $alph(x) \not = alph(y)$ and $|x| = |y| > 1$. Set $$x = a_1 \cdots a_n, \quad y = a'_1 \cdots a'_n$$ Since $alph(x) \not = alph(y)$, one of the following two cases can occur (the other cases are symmetric) \begin{itemize} \item[(1)] $a'_1 \not \in alph(x)$. \item[(2)] There exists $i$, $1 < i \leq n$, such that $a'_i \not \in alph(x)$. \end{itemize} Assume that case (1) holds. For any $p \in \Pi_{\Sigma}$, let $p' \in \Pi_{\Sigma}$ be such that $a < a'_1$, for any $a \in \Sigma \setminus \{a'_1 \}$, whereas the order on the other symbols remains unchanged. In particular, the ordering of $alph(x)$ is not changed in $p'$. Assume that $x$ and $y$ are both Lyndon words with respect to $ <_p$. Since $y$ is a Lyndon word and $|y| > 1$, there exists $a'_j \in alph(y)$ with $a'_j \not = a'_1$. Thus $y = a'_1 \cdots a'_n >_{p'} a'_j \cdots a'_n$ and $y$ is not a Lyndon word with respect to $ <_{p'}$. On the contrary, since the ordering of $alph(x)$ is not changed in $p'$, $x$ is still a Lyndon word with respect to $ <_{p'}$. Assume that case (2) holds. For any $p \in \Pi_{\Sigma}$, let $p' \in \Pi_{\Sigma}$ be such that $a'_i < a$, for any $a \in \Sigma \setminus \{a'_i \}$, whereas the order on the other symbols remains unchanged. In particular, the ordering of $alph(x)$ is not changed in $p'$. Assume that $x$ and $y$ are both Lyndon words with respect to $ <_p$. Thus $y = a'_1 \cdots a'_n >_{p'} a'_i \cdots a'_n$ and $y$ is not a Lyndon word with respect to $ <_{p'}$. On the contrary, the ordering of $alph(x)$ is not changed in $p'$, hence $x$ is still a Lyndon word with respect to $ <_{p'}$. \end{proof} \begin{example} Let $\Sigma = \{A,C,G,T\}$. The words $x = ACG$ and $y = ACT$ are both Lyndon words with respect to $p = (A,C,G,T)$. Let $p' = (T,A,C,G)$ as in the proof of Proposition \ref{P1}. We see that the ordering of $alph(x)$ is not changed in $p'$, hence $x$ is still a Lyndon word with respect to $ <_{p'}$. On the contrary, $y$ is not a Lyndon word with respect to $ <_{p'}$ because $y \succ T$. \end{example} The properties described above show that the choice of a specific ordering of the initial alphabet can have a significant impact on the collision phenomenon. However, the problem of understanding which particular order minimizes this phenomenon remains open, and as explained in Section \ref{sec:conclusion}, future investigations will be devoted to it. However, in this work we have carried out experiments by combining the regular ordering with the inverse ordering to verify the impact it could have the combined use of different orderings. As we will see in Section \ref{sec:evaluation}, results suggest that, from a practical point of view, the addition within the representation of a sequence of information coming from the application of the factorization with respect to the inverse alphabet, reduces the probability of collisions. Thus, we extend the notion of fingerprint by defining the superfingerprint, which concatenates the fingerprint of the sequence with respect to the lexicographic ordering $(A,C,G,T)$, and the fingerprint of the sequence with respect to the inverse ordering $(T,G,C,A)$. \begin{definition}[Superfingerprint] \label{def:superfingerprint} Let $\Sigma=\{A,C,G,T\}$ be an alphabet and $p=(A,C,G,T)$. Let $x$ be a sequence on $\Sigma$ and $F$ be a Lyndon-based factorization. Then, the superfingerprint of $x$ is $\langle \ensuremath{\mathcal{L}}_{p}(x)$, $\$$, $\ensuremath{\mathcal{L}}_{\bar{p}}(x) \rangle$, where $\ensuremath{\mathcal{L}}_{p}(x)$ is the fingerprint of $F(x)$ obtained by considering the ordering $p$ when applying $F$, $\ensuremath{\mathcal{L}}_{\bar{p}}(x)$ is the fingerprint obtained by considering the ordering $\bar{p}$ when applying $F$ and the symbol $\$$ is not in $\Sigma$. \end{definition} \subsection{\texttt{lyn2vec}: a tool for Lyndon-based sequence embedding} \label{ssec:lyn2vectool} We have implemented \texttt{lyn2vec}, a novel tool for providing sequencing read embeddings based on \textit{Lyndon-based factorizations}. \texttt{lyn2vec} takes as input a file in \texttt{FASTA} or \texttt{FASTQ} format and, for each input read $s$, executes a Lyndon-based factorization algorithm (specified as input) for computing a numerical vector that can be used as a representation of $s$. Specifically, \texttt{lyn2vec} produces the following representations for $s$: \begin{itemize} \item the fingerprint of $s$ \item the sequence of the $k$-fingers extracted from the fingerprint of $s$ (for a fixed value of $k$ specified as input parameter) \item the sequence of the $k$-fingers extracted from the superfingerprint (see Definition~\ref{def:superfingerprint}) of $s$, discarding the $k$-fingers containing the symbol \$ \end{itemize} As an example, let us consider $s=\mathit{GCATCACCGCTCTACAG}$. By using the factorization algorithm $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ with $T = 30$ and $k=3$, the factorization and the fingerprint of $s$ will be $\ensuremath{\mathsf{CFL\_ICFL}}\xspace(s) = \langle G, C, \mathit{ATC}, \mathit{ACCGCTCT}, \mathit{ACAG} \rangle$ and $\mathcal{L}(s) = \langle 1,1,3,8,4 \rangle$, respectively. Observe that $\ensuremath{\mathsf{CFL\_ICFL}}\xspace'(s) = \langle G, \mathit{CA}, \mathit{TCACCGC}, \mathit{TCTACAG} \rangle$ is the factorization of $s$ w.r.t. the inverse alphabet $\overline{\Sigma} = \langle T,G,C,A \rangle$ and the superfingerprint of $s$ will be given by concatenating the fingerprint $\mathcal{L}(s) = \langle 1,1,3,8,4 \rangle$ with the fingerprint $\langle 1,2,7,7 \rangle$ obtained from $\ensuremath{\mathsf{CFL\_ICFL}}\xspace'(s)$ and interposing a symbol \$. In other words, the superfingerprint of $s$ is $\mathcal{S}(s) = \langle 1,1,3,8,4,\$,1,2,7,7 \rangle$. By assuming $k=3$, \texttt{lyn2vec} will output one of the following three representations for such sequence: \begin{itemize} \item the \textit{fingerprint} $\mathcal{L}(s) = \langle 1,1,3,8,4 \rangle$ from $\ensuremath{\mathsf{CFL\_ICFL}}\xspace(s)$ \item the sequence $\langle\langle 1,1,3 \rangle, \langle1,3,8 \rangle, \langle3,8,4 \rangle\rangle$ of the \textit{$k$-fingers} extracted from $\mathcal{L}(s)$ \item the sequence $\langle \langle1,1,3 \rangle$, $\langle1,3,8\rangle, \langle3,8,4\rangle, \langle1,2,7\rangle, \langle2,7,7\rangle \rangle$ of the \textit{$k$-fingers} extracted from $\mathcal{S}(s)$ \end{itemize} \texttt{lyn2vec} is written in Python by using the library \textit{Scikit-learn}\footnote{\url{https://scikit-learn.org/stable/}}. The source code and all the files used and produced during the evaluation study are available online\footnote{\url{https://github.com/rzaccagnino/lyn2vec}}. \section{Experiments} \label{sec:evaluation} In this section, we provide details of the experiments carried out to assess the effectiveness of \texttt{lyn2vec}, i.e., its capability to provide suitable numerical representations for biological sequences that can be effectively learned by for machine learning models. To this aim, as a preliminary study we have selected a typical classification problem in Bioinformatics, referred as \textit{read-gene classification} problem. We can state the problem as follows: given a sample of RNA-Seq reads, assign each read to a putative origin gene. Indeed, a RNA-Seq read is a transcript fragment obtained by Next-Generation Sequencing. From a computational point of view, a read is a sequence over the alphabet $\{A,C,G,T\}$ and is a substring of a transcript (messenger RNA, mRNA). A gene is a genomic \emph{locus} (a piece of the genomic DNA of an organism) espressing transcripts. Hence, the origin gene of a RNA-Seq read is the gene expressing the transcript which the read has been sequenced from. The goal of our experiments is to test the capability (in a machine learning context) of the embedding representations produced by \texttt{lyn2vec} to highlight common regions between reads and gene transcripts in order to assign each read to an origin gene. Precisely, the idea is to train a machine learning model to learn the mapping between the read representations and the transcripts (and ultimately to the genes) and use such trained model in order to perform such mapping to be used for classifying the reads. We remark that the application of Lyndon-based features for the specific case of RNA-Seq data is a proof of concept of the possible use of the proposed representations in dealing with the comparison of sequenced reads w.r.t. others embeddings proposed in literature. The motivation for assigning RNA-Seq data to an origin gene derives by the fact that we want to evaluate the quality of the embeddings in representing nucleotide sequences even in situation where typically the quantification of reads per transcript could make the task difficult for machine learning based representations. We assume the reader is familiar with the basic notions of machine learning. However, for further details we refer to~\cite{tan2016introduction}. \paragraph{Tasks.} We remark that, as described in Section \ref{ssec:lyn2vectool}, \texttt{lyn2vec} is able to provide three types of representation for a read. As a consequence, we have faced the read-gene classification problem in three different ways, that is, considering each time one of the three representations provided by \texttt{lyn2vec}. To this, we have organized our experiments into three groups (we call \emph{tasks}), each one assessing one of the read representations produced by \texttt{lyn2vec}, and corresponding to a specific question: \begin{itemize} \item[\textbf{T1.}] \textit{``How effective is the fingerprint produced by \textup{\texttt{lyn2vec}} as read representation in the read-gene classification problem?''} \item[\textbf{T2.}] \textit{``How effective is the sequence of $k$-fingers extracted from the fingerprint produced by \textup{\texttt{lyn2vec}} as read representation in the read-gene classification problem?''} \item[\textbf{T3.}] \textit{``How effective is the sequence of $k$-fingers extracted from the superfingerprint produced by \textup{\texttt{lyn2vec}} as read representation in the read-gene classification problem?''} \end{itemize} As we will see, the use of a specific representation in each task will affect the way in which the read-gene classification problem will be solved. Regarding T1, each machine learning model will directly use the fingerprints of the reads as \textit{feature vectors} (each fingerprint will correspond to one feature vector) on which to be trained. We remark that, in a classification problem, the feature vector represents the list of features of an object considered important for training a model to classify the object itself. Regarding T2 (resp. T3), we will solve the read-gene classification problem in two steps: \textit{(i)} first, each machine learning model will be trained to assign each $k$-finger extracted from the fingerprint (resp. superfingerprint) of a read to a gene (each $k$-finger will correspond to one feature vector), and \textit{(ii)} then, we will define a special classifier (see Section \ref{ssec:EQ2-task}) which, given the sequence of $k$-fingers extracted from the fingerprint (resp. superfingerprint) of a read, will use the result of the classification of these $k$-fingers for assigning the read to a gene. As it will be seen further, the fingerprint representation can work very well in case of error-free data, while the performance degrade in presence of sequencing errors. In response, the $k$-finger-based representation (extracted from the fingerprints) is shown to be more robust to the presence of such errors. Finally, we have empirically proved the usage of the $k$-finger-based representation (extracted from the superfingerprints) enable to reduce the collision phenomenon and to improve performances (see Section \ref{ssec:EQ3-task}; we remark that the problem of the choice of best order of the alphabet on a theoretical point of view remains currently open). \paragraph{Data setting.} \label{datasets} We have used the annotation of the human $6040$ genes of chromosomes $1$, $17$ and $21$ (\texttt{havana} and \texttt{ensembl\_havana}) and randomly selected $100$ genes out of them in order to obtain a small set of genes for assessing the effectiveness of our embedding representation. For each one of those genes gene we have considered all their transcripts, for a total of $17,314$ sequences ($4$ transcripts per gene on average). Then, from each transcript we have extracted all the $100$-mers, thus obtaining a total of $797,407$ $100$-long substrings used as input error-free \emph{reads} to be used for our experiments. A \emph{read} clearly belongs to one of the considered $100$ classes (one class for each gene). \paragraph{Basic methodology.} We have performed the following steps: \begin{enumerate} \item \textit{Feature Extraction.} This step produces the datasets of feature vectors (samples) to train the machine learning models in our experiments (a dataset is related to an experiment). More in detail, a total of $10$ factorization algorithms have been considered: the four algorithms $\ensuremath{\mathsf{CFL}}\xspace$, $\ensuremath{\mathsf{ICFL}}\xspace$, $\ensuremath{\mathsf{CFL}}\xspace\ensuremath{^{d}}$ and $\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$ plus the two algorithms $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ applied for the three values $\{10, 20, 30\}$ of the parameter $T$. For each algorithm we have computed (by using \texttt{lyn2vec}) the fingerprint and superfingerprint of each input read, thus obtaining $10$ datasets of fingerprints (\textit{i.e.},\xspace the $10$ experiments of task T1 where the feature vectors are fingerprints) and $10$ datasets of superfingerprints (\textit{i.e.},\xspace used for the experiments of task T3 where the feature vectors are the $k$-fingers extracted from the superfingerprints). Then, from each one of the $10$ fingerprint (resp. superfingerprint) datasets we have extracted the \emph{$k$-fingers} for $k$ from $3$ to $8$ (six values), thus obtaining a total of $60$ datasets of $k$-fingers, \textit{i.e.},\xspace the $60$ experiments of task T2 (resp. task T3) where the feature vectors are $k$-fingers. We point out that the considered feature vectors are clearly composed of a variable number of elements (integers); consequently, since the length of the feature vectors in a given dataset must be constant, each feature vector must be padded with trailing values equal to $-1$ in order to reach the maximum length inside the dataset itself. This observation is also valid for $k$-fingers even though they have constant length by definition. Indeed, a read fingerprint might be shorter than $k$ and such fingerprint is padded in order to extract one only $k$-finger. \item \textit{Dataset Labeling.} Each feature vector (fingerprint, $k$-finger from fingerprint or superfingerprint), in each one of the datasets obtained in the previous step, has been labeled in order to link it to its origin class (that is, to its origin gene). \item \textit{Learning.} We have considered the following machine learning models: \textit{Random Forest} (\texttt{RF}), \textit{Logistic Regression} (\texttt{LR}), and \textit{Multinomial Naive Bayes} (\texttt{MNB}). Each model has been trained on each one of the labeled datasets previously constructed. First, we have normalized the data by using the \textit{MinMaxScaler} technique. The normalization is used to set the values of the features in a fixed range (usually $[0,1]$), usually providing better results with respect to the case in which features have values in different ranges. Then, the dataset has been split into a \textit{Training Set} (80\% of the samples), and a \textit{Testing Set} (20\% of the samples) using \textit{Stratification}\footnote{The stratification has been performed by using the method \texttt{train\_test\_split} of \textit{Scikit-learn} Python library. }, which guarantees that in both sets all the considered $100$ classes (genes) are represented maintaining the same proportions of the dataset. We remark that both stratification and normalization are two well-known techniques in machine learning. Then, to validate the classifiers and obtain the best hyper-parameters for each of them, we have performed a 5-fold cross-validation by using the \textit{GridSearchCV} method. \item \textit{Evaluation.} The goal of this step is assess the \textit{generalization} capability of the trained models, i.e., the capability to reach high performance on unseen samples. To this aim, the trained models have been applied for classifying the elements of the \textit{Testing Set} using the best parameters found in the previous step. \item \textit{Testing on simulated RNA-Seq reads.} The goal of the Testing step described above was to assess the generalization capability of the chosen machine learning models on the Testing set ($20\%$ of the samples). In this step, instead, the goal is to use best trained model obtained previously for classifying a set of reads originating from the $100$ gene of the data setting. To this aim, we have produced a set of $285,628$ RNA-Seq reads simulated from the panel of $100$ genes by means of Flux Simulator~\cite{fluxsimulator}. More in detail, $10$ million $100$-long reads were simulated with Flux Simulator for different expression levels from the $17,314$ transcripts of the human genes of chromosomes $1$, $17$, and $21$. The reads were simulated with default parameters, the default Illumina error model and disabling the generation of Poly-A tails. Then, only the $285,628$ reads related to our panel of $100$ genes were retained and used in this step. The origin gene (class) of each read is clearly known. We point out that the set of obtained reads is unbalanced. Indeed, $142,266$ reads were simulated from gene \texttt{ENSG00000132517} (the most expressed in the dataset), whereas only $2$ reads were simulated from gene \texttt{ENSG00000116205} (the least expressed in the dataset). Observe that, since fingerprints represent entire reads, then the class of a read is trivially the class of its fingerprint. On the other hand, when a read is represented by the set of its $k$-fingers, then its class must be inferred from the classes of its $k$-fingers. In Section~\ref{ssec:EQ2-task} a rule-based classifier to this aim is presented. \end{enumerate} \paragraph{Performance scores.} Due to the multi-class nature of the considered problem, we will report the performance of the chosen machine learning models obtained both in \emph{Evaluation} and in \emph{Testing on simulated RNA-Seq reads} steps (described above) experiments not only in terms of \emph{accuracy}, but also of \emph{precision}, \emph{recall} and \emph{F-score}. Such metrics are originally defined for binary classification problems, where only two classes are taken into account, the positive one and the negative one, and they are given by, respectively, $\frac{TP+TN}{TP+TN+FP+FN}$, $\frac{TP}{TP+FP}$,$\frac{TP}{TP+FN}$ and $2 \cdot \frac{\mathit{precision} \cdot \mathit{recall}}{precision + recall}$. In particular, accuracy measures the correct portion of correctly predicted samples, the precision indicates how many instances classified in a class actually belongs to such a class, and the recall gives the amount of samples of a given class which are correctly assigned to that class. Finally, the F-score is the harmonic mean between precision and recall, so that it can be used as a useful summary metric. In the case of multi-class classification problems, the global performance of a classifier can be obtained by first averaging the metrics calculated for each single class, and then considering the arithmetic or weighted mean. In this work, due to the unbalanced datasets obtained during the experiments, we will use the averaged values of these metrics weighted for the number of actual samples belonging to each class. We remark that, in order to evaluate the generalization capability of the trained machine learning models, we will report the results obtained, in terms of such metrics, on the sets used for the testing (both for the Evaluation and Testing on simulated RNA-Seq reads steps). The following three sections give the performance scores obtained during our experiments (each section groups together the experiments of a specific task). The last section presents the results of a study carried out in order to analyze the behavior of the classification errors obtained during the experiment providing the best results. \subsection{Effectiveness of the fingerprint representation (task T1)} \label{ssec:EQ1-task} We recall that the feature vector used in task T1 is the fingerprint and an experiment has been performed on each one of the $10$ fingerprint datasets obtained in the \emph{Feature Extraction} step, for a total of $10$ experiments. As a result we have observed that the \texttt{RF} model always outperforms the other models and we only report its results on the testing set (see Table~\ref{tab:EQ1-classification}). As the table shows, the \texttt{RF} model trained with the fingerprints obtained with $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ outperforms the \texttt{RF} model trained with the other factorization algorithms. In particular, the best results (highlighted in bold) have been obtained by using $\texttt{T} = 20$. Furthermore, for $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ the performance does not vary significantly with the parameter \texttt{T}. This may be due to the fact that the longest factors to break are the same, and they are most probably longer than 30 bases. % \begin{table} \centering \caption{Performance of the \texttt{RF} model in task T1.} \label{tab:EQ1-classification} \begin{tabular}{ccllll} \toprule \multicolumn{2}{l}{\textbf{Factorization}} & \textbf{Accuracy} & \textbf{Precision} & \textbf{Recall} & \textbf{F-score} \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{$\ensuremath{\mathsf{CFL}}\xspace$}} & 0.43 & 0.45 & 0.43 & 0.43 \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{$\ensuremath{\mathsf{ICFL}}\xspace$}} & 0.40 & 0.45 & 0.40 & 0.41 \\ \midrule \multirow{3}{*}{$\ensuremath{\mathsf{CFL\_ICFL}}\xspace$} & \multirow{1}{*}{\texttt{T=10}} & 0.90 & 0.90 & 0.90 & 0.90 \\ & \multirow{1}{*}{\texttt{T=20}} & 0.90 & 0.90 & 0.90 & 0.90 \\ & \multirow{1}{*}{\texttt{T=30}} & 0.89 & 0.89 & 0.89 & 0.88 \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{$\ensuremath{\mathsf{CFL}}\xspace\ensuremath{^{d}}$}} & 0.72 & 0.72 & 0.72 & 0.72 \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{$\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$}} & 0.85 & 0.85 & 0.85 & 0.85 \\ \midrule \multirow{3}{*}{$\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$} & \multirow{1}{*}{\texttt{T=10}} & 0.92 & 0.93 & 0.92 & 0.93 \\ & \multirow{1}{*}{\texttt{T=20}} & \textbf{0.93} & \textbf{0.94} & \textbf{0.93} & \textbf{0.94} \\ & \multirow{1}{*}{\texttt{T=30}} & 0.92 & 0.93 & 0.92 & 0.92 \\ \bottomrule \end{tabular} \end{table} To assess the effectiveness of \texttt{lyn2vec} we compared its results with those obtained by using other embedding techniques, in particular \texttt{BioVec, fastDNA} and \texttt{DNABERT}. In particular, we have performed a further experiment on the same data set obtained with $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$, $T=20$. Afterwards, we performed once again the classification task by feeding the new embedded features to the RF model which was the one providing the best results the exepriments. As it is shown further in Table \ref{tab:comparison}, the results obtained with the other representations were systematically lower than then those obtained using \texttt{lyn2vec}. \begin{table} \caption{Performance of the \texttt{RF} model with the embeddings by \texttt{BioVec}, \texttt{fastDNA} and \texttt{DNABERT}. The first row (labeled by \texttt{lyn2vec} is a copy of the performance scores reported in Table~\ref{tab:EQ1-classification} for $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ and $\texttt{T}= 20$ (task T1).} \label{tab:comparison} \centering \begin{tabular}{ccllll} \toprule \multicolumn{2}{l}{\textbf{Factorization}} & \textbf{Accuracy} & \textbf{Precision} & \textbf{Recall} & \textbf{F-score} \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{\texttt{lyn2vec}}} & 0.93 & 0.94 & 0.93 & 0.94 \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{\texttt{BioVec}}} & 0.83 & 0.85 & 0.83 & 0.83 \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{\texttt{fastDNA}}} & 0.67 & 0.65 & 0.67 & 0.67 \\ \midrule \multicolumn{2}{l}{\multirow{1}{*}{\texttt{DNABERT}}} & 0.37 & 0.36 & 0.35 & 0.36 \\ \bottomrule \end{tabular} \end{table} Results obtained by our approach on this task are shown to be the highest, with accuracy of 0.93, precision of 0.94 and a recall of 0.93, outperforming the ones obtained by using the other proposed tools. Also, the dataset produced by applying \texttt{lyn2vec} is way smaller than the one produced by other representation, due to the fixed size of the embedding vectors they produce. Finally, we have carried out the \emph{Testing on simulated RNA-Seq reads} step by using the \texttt{RF} model trained with the fingerprints from $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ and $T=20$. We have obtained a precision of $0.85$, a recall of $0.42$, and a F-score of $0.55$. Such results are related to the presence of sequencing errors in the simulated RNA-Seq reads datasets, since we remind that changes in the sequences lead to corrupted fingerprints, which differ from those used during the training of the classifier. \subsection{Effectiveness of the $k$-finger-based representation (task T2)} \label{ssec:EQ2-task} We recall that the feature vector used in task T2 is the $k$-finger and an experiment has been performed on each one of the $60$ datasets obtained in the \emph{Feature Extraction} step, by considering values of $k$ from $3$ to $8$. From a technical point of view, the $k$-mers extracted from the fingerprints computed by \texttt{lyn2vec}, \textit{i.e.},\xspace, the $k$-fingers, can be used as feature vectors. Our goal is assessing the effectiveness of the $k$-fingers as feature vectors in the read-gene classification to improve performance in presence of sequencing errors. As for task T1, the \texttt{RF} model outperforms the other models. Figure~\ref{fig:EQ2-fscore} provides an overall insight: experiments conducted with $k=3,4,5$ show that $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ always results in lower accuracy compared to other factorization algorithms. The same reflects into the F-score plot. We only report the results of the \texttt{RF} model on the testing set in Tables~\ref{tab:EQ2-classification1} and~\ref{tab:EQ2-classification2}. We observed that in most cases the performance scores increase with the increase of $k$, so we only report the values $\{3,6,8\}$. The best result (highlighted in bold in the tables) has been obtained by using $k = 8$, $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$ with $\texttt{T} = 20$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ with $\texttt{T} = 30$. \begin{table} \caption{Performance of the \texttt{RF} model in classifying the $k$-fingers (task T2) by using $\ensuremath{\mathsf{CFL}}\xspace$, $\ensuremath{\mathsf{ICFL}}\xspace$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace$.} \label{tab:EQ2-classification1} \centering \begin{tabular}{cccllll} \toprule \multicolumn{2}{l}{\textbf{Factorization}} & \textbf{k value} & \textbf{Accuracy} & \textbf{Precision} & \textbf{Recall} & \textbf{F-score} \\ \midrule \multicolumn{2}{l}{\multirow{3}{*}{$\ensuremath{\mathsf{CFL}}\xspace$}} & 3 & 0.53 & 0.61 & 0.43 & 0.49 \\ \multicolumn{2}{l}{} & 6 & 0.73 & 0.75 & 0.66 & 0.69 \\ \multicolumn{2}{l}{} & 8 & 0.79 & 0.81 & 0.78 & 0.80 \\ \midrule \multicolumn{2}{l}{\multirow{3}{*}{$\ensuremath{\mathsf{ICFL}}\xspace$}} & 3 & 0.57 & 0.60 & 0.46 & 0.51 \\ \multicolumn{2}{l}{} & 6 & 0.71 & 0.77 & 0.47 & 0.53 \\ \multicolumn{2}{l}{} & 8 & 0.81 & 0.80 & 0.42 & 0.48 \\ \midrule \multirow{9}{*}{$\ensuremath{\mathsf{CFL\_ICFL}}\xspace$} & \multirow{3}{*}{\texttt{T=10}} & 3 & 0.47 & 0.58 & 0.31 & 0.37 \\ & & 6 & 0.91 & 0.91 & 0.87 & 0.89 \\ & & 8 & 0.93 & 0.94 & 0.93 & 0.93 \\ \cmidrule{2-7} & \multirow{3}{*}{\texttt{T=20}} & 3 & 0.50 & 0.57 & 0.36 & 0.42 \\ & & 6 & 0.92 & 0.92 & 0.89 & 0.90 \\ & & \textbf{8} & \textbf{0.95} & \textbf{0.95} & \textbf{0.93} & \textbf{0.94} \\ \cmidrule{2-7} & \multirow{3}{*}{\texttt{T=30}} & 3 & 0.55 & 0.62 & 0.41 & 0.47 \\ & & 6 & 0.91 & 0.92 & 0.88 & 0.90 \\ & & 8 & 0.92 & 0.93 & 0.91 & 0.92 \\ \bottomrule \end{tabular} \end{table} \begin{table} \caption{Performance of the \texttt{RF} model in classifying the $k$-fingers (task T2) by using $\ensuremath{\mathsf{CFL}}\xspace\ensuremath{^{d}}$, $\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$ and $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$.} \label{tab:EQ2-classification2} \centering \begin{tabular}{cccllll} \toprule \multicolumn{2}{l}{\textbf{Factorization}} & \textbf{k value} & \textbf{Accuracy} & \textbf{Precision} & \textbf{Recall} & \textbf{F-score} \\ \midrule \multicolumn{2}{l}{\multirow{3}{*}{$\ensuremath{\mathsf{CFL}}\xspace\ensuremath{^{d}}$}} & 3 & 0.56 & 0.63 & 0.45 & 0.51 \\ \multicolumn{2}{l}{} & 6 & 0.90 & 0.91 & 0.86 & 0.89 \\ \multicolumn{2}{l}{} & 8 & 0.90 & 0.93 & 0.86 & 0.89 \\ \midrule \multicolumn{2}{l}{\multirow{3}{*}{$\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$}} & 3 & 0.65 & 0.68 & 0.57 & 0.61 \\ \multicolumn{2}{l}{} & 6 & 0.92 & 0.92 & 0.87 & 0.90 \\ \multicolumn{2}{l}{} & 8 & 0.87 & 0.91 & 0.78 & 0.84 \\ \midrule \multirow{9}{*}{$\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$} & \multirow{3}{*}{\texttt{T=10}} & 3 & 0.38 & 0.55 & 0.21 & 0.25 \\ & & 6 & 0.89 & 0.89 & 0.86 & 0.87 \\ & & 8 & 0.93 & 0.93 & 0.92 & 0.93 \\ \cmidrule{2-7} & \multirow{3}{*}{\texttt{T=20}} & 3 & 0.40 & 0.55 & 0.23 & 0.25 \\ & & 6 & 0.91 & 0.91 & 0.88 & 0.89 \\ & & 8 & 0.94 & 0.94 & 0.92 & 0.93 \\ \cmidrule{2-7} & \multirow{3}{*}{\texttt{T=30}} & 3 & 0.42 & 0.51 & 0.24 & 0.28 \\ & & 6 & 0.91 & 0.91 & 0.88 & 0.89 \\ & & 8 & \textbf{0.94} & \textbf{0.94} & \textbf{0.93} & \textbf{0.94} \\ \bottomrule \end{tabular} \end{table} \begin{figure}[h!t] \centering \includegraphics[width=\linewidth]{fscore_d.png} \caption{F-score of the \texttt{RF} model and $k$ from $3$ to $8$ (task T2).} \label{fig:EQ2-fscore} \end{figure} At this point, before giving the results of the \emph{Testing on simulated RNA-Seq reads} step, we need to describe the \textit{rule-based classifier} used for inferring the class of a read from the classes of its $k$-fingers. During some preliminary tests we have defined many \textit{criteria} to deduce the classification of a read using the results of the classification of its $k$-fingers. By empirical observations two possible criteria for our problem have been selected: \begin{itemize} \item \textit{Majority.} Given a read, then a gene $G$ reaches the majority for that read, if at least half of its $k$-fingers are assigned to $G$; therefore the read is assigned to $G$. \item \textit{Threshold.} Given a read, for each of its $k$-finger the \textit{classification margin} is computed, and the read is assigned to the gene for which the highest value of this margin is achieved. The \textit{classification margin} is obtained by subtracting the lowest probability whereby a $k$-finger was correctly classified during the training step to the probability by which it was currently classified. \end{itemize} We remark that in our experiments we have tested such two criteria both individually and combined in different orders. Best results were obtained when they are combined by applying \emph{Majority} first and \emph{Threshold} where the first criterion can not be reached. In this step, we have used the \texttt{RF} model trained with the $k$-fingers produced by $\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$ and $k = 5$, which achieves the best scores in the read classification (recall that the \texttt{RF} model with $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$, $\texttt{T} = 30$ and $k = 8$ has achieved the best scores in the $k$-finger classification as described before during Training). Such a phenomenon can be explained by reminding that $(i)$ errors in sequencing can modify the resulting fingerprint, making more difficult for the classifier to recognize it, and $(ii)$ the rule-based classifier relies on the classifications of the $k$-fingers in order to classify an entire fingerprint (corresponding to a read). By using a lower value of $k$, a higher number of $k$-fingers can be extracted by a single fingerprint. In this way, it is more likely that a higher number of $k$-fingers will be correctly classified, since the eventual error should affect a lower number of $k$-fingers. % We obtained a precision of $0.91$, a recall of $0.77$, and a F-score of $0.82$, instead of precision of $0.85$, a recall of $0.42$, and a F-score of $0.55$ obtained in task T1, by directly using the entire fingerprint as feature vector. Such a huge different in the performance can be explaining again by the fact that, in presence of errors, $k$-fingers are able to extract the parts of the fingerprint which are not corrupted, while in the case of the direct classification of the fingerprint, the classifier must infer the read class relying only on a (probably) single corrupted feature vector.% \subsection{Superfingerprints to overcome the impact of $k$-finger collisions on the read classification (task T3)} \label{ssec:EQ3-task} In this task, we have repeated the experiments carried out in task T2, using the $k$-fingers extracted from the superfingerprints (see Definition~\ref{def:superfingerprint}) instead of those obtained from the fingerprint representations. A total of $60$ datasets of $k$-fingers extracted from superfingerprints were obtained, one for each $k$ (from $3$ to $8$) and for each one of the $10$ factorization algorithms. The results of this task have achieved a significant improvement over T2, both in \emph{Evaluation} and \emph{Testing on simulated RNA-Seq reads}. Specifically, in \emph{Evaluation}, for the (best performing) \texttt{RF} model trained with $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$, $\texttt{T} = 30$ and $k = 8$, we have reached $0.97$ as accuracy, $0.96$ as precision, $0.95$ as recall and $0.95$ as F-score against the accuracy 0.94, precision 0.93, recall 0.94 and f-score 0.94 obtained in the same step in task T2 for the same factorization. Finally, in \emph{Testing on simulated RNA-Seq reads} we have obtained 0.95 as precision, 0.83 as recall and 0.88 as F-score with $\ensuremath{\mathsf{ICFL}}\xspace\ensuremath{^{d}}$ and $k = 5$, against 0.91, 0.77 and 0.82 obtained in T2 in the same step and, also in this case, for the same factorization. In our opinion, the increase of the classification scores with respect to task T2 can be explained by the fact that the rule-based classification (for inferring the class of a read from the class of its $k$-fingers) is somehow more robust and less affected by collisions, since the collision rate may even not decrease. We remark that superfingerprints are proposed as a possible solution to reduce the impact of collisions (see Section~\ref{ssec:collisions}) on the classification results and, consequently, to improve the classification performance. This can be explained noticing that, even though other collisions could occur also in the case of the $k$-fingers extracted from the fingerprint built on the inverse alphabet, concatenating the two fingerprints reduce the overall probability of collision, since the probability that both fingerprints are affected by the collision phenomenon is lower than the probability of collision of the two fingerprints taken singularly. In terms of how the rule-based classifier works, this means that, even if the absolute number of $k$-fingers being collisions may increase, their incidence on the total number of $k$-fingers obtained will be lower, leading to a higher number of correct classifications. Still, the theoretical demonstration of the superfingeprint capacity to reduce the collisions remains open, so task T3 has been carried out as a first attempt to empirically asses its effectiveness. \subsection{Error analysis} We have carried out a preliminary analysis to investigate the errors due to the use of $k$-fingers in classifying reads; indeed, $k$-fingers are the most suitable to this aim, since we wanted to investigate how effectively they are able to highlight common regions in different reads. We have considered the results obtained in task T2 (with the \texttt{RF} model) during the \emph{Training} step on the six datasets of $k$-fingers produced with the $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ factorization, $T=30$ and $k$ from $3$ to $8$ (see Section~\ref{ssec:EQ2-task}). Recall that the best results (in the training step of task T2) were obtained for $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$, $T=30$ and $k=8$. Each one of the six datasets (training set plus testing set, in order to consider also the errors produced by the model in the training set) has been given as input to the rule-based classifier (see Section~\ref{ssec:EQ2-task}) in order to infer the classification of the reads of the data setting (for each $k$ from $3$ to $8$). A misclassification occurs when a read is assigned to the wrong class (gene) and can be related to one of the following three facts: \textit{(i)} the read shares substrings with transcripts coming from the wrong gene, \textit{(ii)} some $k$-fingers of the read collide (see Section~\ref{ssec:collisions}) with $k$-fingers of reads coming from the wrong gene and \textit{(iii)} some $k$-fingers of the read are close (in terms of integers) to $k$-fingers of the wrong gene and therefore the trained model makes a wrong assignment of the read $k$-fingers. For example $k_1 = \langle 2,5, 8,7,20 \rangle$ and $k_2 = \langle 2,5,7,7, 19 \rangle$. We have decided to perform the analysis on the error-free reads of the data setting (instead of the reads used in the Testing on simulated RNA-Seq reads step) in order to discard the noise due to sequencing errors. For each one of the obtained (six) datasets of classified reads, we have carried out the following analysis. Given the set $D$ of the $100$ genes of our data setting, we have considered all the elements $(G_T, G_A)$ of the cartesian product $D^2$, such that $G_T \ne G_A$ (a total of $9900$ elements). $G_T$ will be referred as \emph{target gene}, while $G_A$ as \emph{assignment gene}. For each pair $(G_T, G_A)$ we have computed the number of reads originated from $G_T$ but assigned to $G_A$, referred in the following as \emph{misclassification number}. Overall, for each value of $k$ we have observed a large number of pairs with a misclassification number below $30$ (on average, 9832). The most interesting results were obtained for $k = 5$ and $k=8$. \paragraph{k=8} We have detected a total of $229$ pairs having a misclassification number over $30$ and involving $34$ distinct genes. The number of exchanges ranged from 0 to 113. % On average, we have found that $36$ distinct $k$-fingers per pair were misclassified due to reason \textit{(iii)} related to numerically close $k$-fingers. Still, the fact that only $229$ pairs out of the $9900$ considered are misclassified more than $30$ times is surprising. Such a few number of misclassified pairs and the high performance scores (see the results reported for $\ensuremath{\mathsf{CFL\_ICFL}}\xspace\ensuremath{^{d}}$ with \texttt{T=30} in Table \ref{tab:EQ2-classification2}) suggest that the \texttt{lyn2vec} provides effective representations of a string. \paragraph{k=5} In this case we have detected only $29$ pairs having a misclassification number over $30$; they involve $27$ distinct genes. The number of exchanges ranged from 0 to 158. On average, the number of (distinct) misclassified $k$-fingers per pair is $20$. In general, about the $65$\% of the misclassified $k$-fingers are shared between the two genes, of which, only the $15$\% actually correspond to common substrings whereas the other ones were misclassifed due to reason \textit{(ii)}. Not surprisingly, these results suggest that for higher values of $k$, the collision rate is lower. This analysis highlights how different values of the parameter $k$ lead to different behavior of the $k$-fingers and, consequently, to different results. $k=8$ seems to be the best choice in terms of results in the current machine learning task, achieving 0.94 and 0.93 of precision and recall on the $k$-finger representation. Limitations of the choice of higher $k$ are related to the fact that the method can misclassify similar $k$-fingers. Clearly, the length of the reads could be also another parameter to take into account to allow higher values of $k$. Those results suggest that different parameters and models applied in combination with the \texttt{lyn2vec} representation could lead to different uses whose investigation can be carried out in future works. \subsection{Discussion and perspectives} \label{ssec:discussion} The results obtained in this section, allow us to confirm that the \texttt{lyn2vec} method is effective in providing representations of sequencing reads useful in machine learning problems. The representation based on the basic notion of fingerprint (see Section \ref{ssec:EQ1-task}) already provided results (precision 0.94 and recall 0.93) overcoming the results obtained using other well-known representation methods, i.e., \texttt{BioVec}, \texttt{fastDNA} and \texttt{DNABERT} . % Later, in Section \ref{ssec:EQ2-task}, we further assessed our method by applying it on RNA-Seq reads simulated with Flux Simulator with different gene-expression levels and errors, showing that using a hybrid approach in which $k$-fingers were used in combination with a rule-based classifier, significantly increases performance, by reaching high precision 0.91 and recall 0.77, despite of a precision of 0.85 and a recall of 0.42 reached by directly classifying the whole fingerprints of such data. Finally, in Section \ref{ssec:EQ3-task} the problem of collisions was addressed in a positive way using the notion of superfingerprint as a \texttt{lyn2vec} representation. Results obtained outperforms that obtained in T1 and T2 tasks, by reaching precision 0.95 and recall 0.83. \section{Conclusion} \label{sec:conclusion} In this paper we propose \texttt{lyn2vec}, a novel feature embedding method using the notion of fingerprint to represent sequencing reads. Differently from NLP-based feature embedding, our method relays on theoretical investigation of combinatorial properties which guarantee to capture similarities among sequences. In particular, the computation complexity of \texttt{lyn2vec} is linear in the number of sequences represented, no training of embedding model is necessary and the size of the built datasets is certainly smaller with respect those obtained with NLP-based sequence embedding methods. Since the main goal of the present work is the investigation of the potentiality of \texttt{lyn2vec} as an embedding method in a machine learning approach, to evaluate its effectiveness, we have decided to use the read representations provided for assigning RNA-Seq data with respect to the origin gene. The choice of this framework is due to the fact that it is an ideal context to compare the effectiveness of the notions of fingerprint, $k$-finger and finally superfingerprint to capture subsequence similarities. We have also run an experimental analysis to investigate the error due to misclassification of the reads. The carried out study has pointed out that \texttt{lyn2vec} performance can be greatly improved by $k$-fingers with higher $k$ thus leading to possible uses for long reads instead of short reads. Long read sequencing technologies are becoming more relevant in various applications in bioinformatics~\cite{Logsdon2020}. While this work is mainly a proof of concept that \texttt{lyn2vec} is effective to represent sequencing reads; future investigations will be needed to understand the use of the proposed representations in developing practical applications on real data. Furthermore, it could be of interest to evaluate the effectiveness of \texttt{lyn2vec} in other types of machine learning contexts such as clustering and structure prediction, or other problems such as pattern discovering. \paragraph{Funding.} This project has received funding from the European Union's Horizon 2020 research and innovation programme under the Marie Skłodowska-Curie grant agreement number [872539].
{'timestamp': '2022-03-01T02:52:23', 'yymm': '2202', 'arxiv_id': '2202.13884', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13884'}
arxiv
\section{Conclusion} \label{sec:conclusion} In this paper, we proposed a novel viewport-adaptive motion estimation technique for fisheye images that leads to considerable gains over the projection-based approach and outperforms traditional motion compensation by almost 3 dB in terms of PSNR on fisheye images. We have shown that our method leads to considerable gains even on sequences where the prior projection-based approach failed. Hence, significant gains for other algorithms based on motion compensation can be expected. An investigation of the applicability to video coding suggests that major improvements in rate-distortion performance are highly likely. As a next step, we will therefore integrate our method into the VVC Test Model (VTM) \cite{Chen2020}, which will require additional research to adapt other dependent algorithms in the coding pipeline to the presented viewport-adaptive approach. \section{Simulations and Experiments} \label{sec:experiments} We investigate the performance of the proposed viewport-adaptive motion estimation technique by applying it to the task of motion compensation, which forms the baseline for many image and video processing tasks. In the following, three methods for block-based motion estimation and compensation employing a translatory motion model are tested. The traditional motion compensation method employing a translatory motion model is thereby called Translatory Motion Compensation (TMC) \cite{ShanZhu2000}, the projection-based approach is called Projection-based Translatory Motion Compen-\mbox{sation (PTMC) \cite{Eichenseer2019}}, and the novel viewport-adaptive approach is called Viewport-Adaptive Projection-based Translatory Motion Compensation (VA-PTMC). All experiments are performed using the eight sequences \textit{HallwayA}, \textit{HallwayB}, \textit{HallwayD}, \textit{PillarsC}, \textit{PoolA}, \textit{PoolB}, \textit{PoolNightA} and \textit{Street} from the fisheye dataset \cite{Eichenseer2016}. The sequences of size 1088$\times$1088 pixels have been rendered using an equisolid fisheye lens with a bitdepth of 8 bits per channel and exhibit different global camera motion types such as translation, zoom and pan. For each sequence, 100 frame pairs consisting of a reference frame and the subsequent current frame are processed. The motion compensation is performed on the luminance channel with the Peak Signal to Noise Ratio (PSNR) and the Structural Similarity Index Measure (SSIM) \cite{Wang2004} as estimates for the achieved motion compensation quality. Both measurements are calculated on the actual pixel data only while the irrelevant area around the circular fisheye images is ignored. A block matching search range of 96 pixels to all sides of the current block is selected for all algorithms. As the optimal brute-force full search strategy is rarely used in actual motion estimation systems due to its immense computational complexity, we employ the diamond search strategy \cite{ShanZhu2000}. This provides faster, more practical results and a better estimate of the resulting gains in quality for real applications. The sum of squared differences (SSD) is used as an error metric during the motion estimation procedure, and the motion vector candidates are limited to integer accuracy in the perspective domain. Different square blocksizes $B \times B$ with $B \in \{8, 16, 32, 64, 128\}$ are tested. For PTMC and VA-PTMC, the reference frame is interpolated to 1/8th pixel accuracy using cubic convolution interpolation \cite{Keys1981} and the motion compensated fisheye coordinates are quantized accordingly. \begin{table}[t] \footnotesize \centering \caption{Average PSNR results in dB of the motion compensated frames for the different sequences employing a blocksize of $B = 16$. The second column specifies the indices of the employed reference frames. The PSNR gain with respect to TMC is given in brackets.}\vspace{2pt} \label{tab:psnr_results_sequences} \begin{tabular}{lr|rrr} \toprule Sequence & Frames & TMC & PTMC & VA-PTMC \\ \midrule \textit{HallwayA} & 331--430 & 28.10 & 26.05 (--2.06) & \textbf{28.71 (+0.61)} \\ \textit{HallwayB} & 1--100 & 31.12 & 29.68 (--1.45) & \textbf{33.21 (+2.09)} \\ \textit{HallwayD} & 1--100 & 32.70 & 36.95 (+4.25) & \textbf{38.57 (+5.87)} \\ \textit{PillarsC} & 101--200 & 36.78 & 37.43 (+0.65) & \textbf{38.52 (+1.74)} \\ \textit{PoolA} & 101--200 & 36.09 & 37.40 (+1.31) & \textbf{39.42 (+3.33)} \\ \textit{PoolB} & 301--400 & 36.22 & 38.20 (+1.98) & \textbf{41.17 (+4.95)} \\ \textit{PoolNightA} & 1--100 & 33.48 & 34.73 (+1.25) & \textbf{36.20 (+2.72)} \\ \textit{Street} & 401--500 & 23.13 & 22.65 (--0.47) & \textbf{24.01 (+0.88)} \\ \midrule Average & & 32.20 & 32.88 (+0.68) & \textbf{34.98 (+2.78)} \\ \bottomrule \end{tabular} \end{table} Table \ref{tab:psnr_results_sequences} shows the achieved PSNR results for an exemplary blocksize of $B = 16$. It is clearly visible that the proposed VA-PTMC significantly outperforms TMC and PTMC. In the sequences \textit{HallwayA} and \textit{HallwayB}, that also exhibit non-translational motion, PTMC has difficulties and performs even worse than conventional TMC. VA-PTMC, on the other hand, provides considerable gains in quality for sequences exhibiting non-translational motion, as well. Furthermore, in sequence \textit{Street} large parts of the motion happen below the camera, i.e.\ on the bottom motion plane. The implicit front/back viewport of PTMC can not model the motion on that plane and hence leads to slightly worse results than TMC whereas VA-PTMC leads to a gain of +0.88 dB for the selected blocksize. \begin{table}[t] \footnotesize \centering \caption{Average PSNR results in dB for different blocksizes $B$. The PSNR gain with respect to TMC is given in brackets.}\vspace{2pt} \label{tab:psnr_results_mean} \begin{tabular}{l|rrr} \toprule Blocksize $B$ & TMC & PTMC & VA-PTMC \\ \midrule 8 & 32.78 & 33.07 (+0.29) & \textbf{35.42 (+2.64)} \\ 16 & 32.20 & 32.88 (+0.68) & \textbf{34.98 (+2.78)} \\ 32 & 31.78 & 32.51 (+0.73) & \textbf{34.69 (+2.91)} \\ 64 & 31.26 & 31.88 (+0.62) & \textbf{34.49 (+3.23)} \\ 128 & 30.28 & 30.91 (+0.63) & \textbf{33.68 (+3.40)} \\ \midrule Average & 31.66 & 32.25 (+0.59) & \textbf{34.65 (+2.99)} \\ \bottomrule \end{tabular} \end{table} Table \ref{tab:psnr_results_mean} shows the PSNR results for different blocksizes averaged over all sequences, i.e.\ averaged over 800 motion compensated frames. Clearly, the large gains of VA-PTMC with respect to TMC and PTMC are not limited to the investigated blocksize $B=16$ but are obtained for all blocksizes. While the overall motion compensation quality decreases for increasing blocksizes $B$, the gain of VA-PTMC with respect to TMC increases. Overall, VA-PTMC leads to average gains of +2.99 dB on the investigated fisheye sequences. For comparison, the average SSIM values amount to 0.8863 for TMC, 0.8924 (+0.0061) for PTMC, and 0.9227 (+0.0364) for VA-PTMC. With these significant improvements in terms of motion compensation quality, it can be expected that VA-PTMC leads to considerable improvements in algorithms that build on motion compensation, such as video coding, framerate up-conversion, or resolution enhancement. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{images/decision-maps.jpg} \caption{Viewport decision maps overlaid on motion compensated frames of sequences \textit{Street} (top) and \textit{HallwayD} (bottom) for blocksizes 128, 64, and 32 (from left to right). The viewports are color coded as front/back (red), bottom/top (blue), left/right (green).} \label{image:decision-maps} \end{figure} Fig. \ref{image:decision-maps} shows the color coded viewport decisions overlaid on the motion compensated frames for the sequences \textit{Street} and \textit{HallwayD} for the blocksizes $B = 128$, $B = 64$ and $B = 32$. It is visible that the proposed VA-PTMC reliably selects the bottom/top viewport for structured ground areas in the images, especially for larger blocksizes. For smaller blocksizes, noise-like patterns emerge in some image areas, where viewports that do not match the expected motion plane supplied the minimum SSD. This can be partly attributed to the suboptimal diamond search strategy. It has shown that in some cases, unexpected viewport decisions might be beneficial in order to implicitly access pixels at subpixel precision. Depending on the application scenario, this behavior might be desired. In other cases, a possible method to prevent these situations could be a voting system that takes different viewport decisions within a suitable neighborhood into account and then selects the most frequent viewport for the current block. \begin{figure}[t] \setlength\figurewidth{\columnwidth} \setlength\figureheight{.62\columnwidth} \centering {\footnotesize\input{tikz/rate_distortion}} \caption{Motion compensation PSNR over average side-information in bit per pixel. For TMC and PTMC, the side information consists of the motion vectors only, while for VA-PTMC the viewport decision is included additionally.} \label{fig:rate_distortion} \end{figure} Fig. \ref{fig:rate_distortion} shows the average compressed side information per pixel in relation to the average PSNR of the motion compensated images for different blocksizes $B$. Thereby, the side information is compressed using the bzip2 algorithm \cite{Seward2019}. For TMC and PTMC, the side information consists of the 8 bit signed integer motion vectors only, while for VA-PTMC the 2 bit viewport decision is included additionally. The more accurate fisheye motion model provides slighlty better results than TMC at comparable rates. VA-PTMC, however, shows significantly improved results and spans roughly the same range as TMC and PTMC in terms of side information rate. Especially noteworthy is that neither PTMC nor TMC can match the high quality of VA-PTMC for $B=128$ with any of the tested blocksizes. This strongly suggests that the additional bits pay off and notable improvements in rate-distortion performance can be expected if the proposed viewport-adaptive approach is to be integrated into an actual video codec. \section{Introduction} \label{sec:introduction} In recent years, fisheye lenses \cite{Miyamoto1964} have found their way into many modern imaging products and are not only used for industrial applications like autonomous driving \cite{Cui2019} and video surveillance \cite{Findeisen2013}, but are also increasingly being built into consumer devices like action cameras and smartphones. The popularity of fisheye lenses stems from their large fields of view (FOV) of up to 180° and more, which enables them to capture exceptionally large regions of their surroundings. Estimating the motion between two frames of an image sequence is a crucial part of many image and video signal processing tasks like video coding \cite{Sullivan2012}, \cite{Bross2020}, framerate up-conversion \cite{Byung-TaeChoi2000}, or resolution enhancement \cite{SungCheolPark2003}. Commonly, block matching \cite{ShanZhu2000} incorporating a translational motion model is used, where a block in the current frame is matched to a block in a reference frame by shifting it according to different motion vector candidates and selecting the best match. The motion between two frames can then be compensated by copying the motion compensated blocks from the reference frame to the the corresponding blocks in a compensated frame. Unlike traditional perspective lenses, fisheye lenses do not follow the pinhole model. They follow projection functions \cite{Miyamoto1964}, \cite{Kannala2006} that heavily bend the incident light rays towards the image sensor to realize their large FOVs. The hereby introduced strong radial distortions in the image impair the performance of block-based motion compensation techniques. There have been different approaches to improve fisheye motion compensation. Jin et al. \cite{Jin2015} proposed a pixel-wise warping of the motion vector according to an equidistant fisheye projection. Ahmmed et al. \cite{Ahmmed2016} inserted an additional reference frame generated using an elastic motion model into the motion compensation procedure. Eichenseer et al. \cite{Eichenseer2019} introduced a state-of-the-art projection-based approach where the block matching procedure is conducted in the perspective domain. \begin{figure}[t] \begin{minipage}[b]{0.3\columnwidth} \centering \centerline{\includegraphics[width=\linewidth]{images/fisheye-original}} \centerline{a) Fisheye image.}\medskip \end{minipage} \hfill \begin{minipage}[b]{0.6\columnwidth} \centering \centerline{\includegraphics[width=\linewidth]{images/viewport-flower}} \centerline{b) Perspective viewports.}\medskip \end{minipage} \caption{a) The original fisheye image \cite{Eichenseer2016} and b) the top, left, front, right and bottom perspective viewports.} \label{image:viewport-introduction} \end{figure} Although the latter projection-based approach takes the fisheye projection into account during motion compensation, it does not cover for the large incident angles of up to 90° and more, where different motion planes need to be considered. Thereby, a motion plane describes a plane in 3D space on which the motion is performed according to a translational model. Implicitly, the traditional approach as well as the projection-based approach take only the forward oriented motion plane into account, i.e.\ the motion plane parallel to the sensor plane. While this is sufficient for perspective lenses, the large FOV of fisheye lenses requires different motion planes to be considered. Similar to 360° images, fisheye images can be mapped to a sphere in 3D space. Hence, generating different viewports into fisheye images is possible as shown in Fig. \ref{image:viewport-introduction}b) where the top, left, front, right and bottom viewports into the original fisheye image in Fig. \ref{image:viewport-introduction}a) are visualized. In the novel viewport-adaptive approach, we exploit this possiblity of projecting the fisheye coordinates to different perspective viewports in order to realize differently oriented motion planes in 3D space. The remainder of this paper is organized as follows: Section \ref{sec:ptmc} briefly summarizes the projection-based approach from \cite{Eichenseer2019}. Section \ref{sec:mv-ptmc} explains the novel viewport-adaptive approach in detail and introduces an improved virtual image plane compensation. Section \ref{sec:experiments} evaluates the performance of the new approach on the task of motion compensation and gives an estimate of the expected rate-distortion performance in video coding compared to traditional block matching. Finally, Section \ref{sec:conclusion} concludes this paper. \section{Viewport-Adaptive Motion Compensation} \label{sec:mv-ptmc} \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{images/block-diagram} \caption{Block diagram of the described viewport-adaptive motion compensation technique for one image block $\boldsymbol{B}_\text{cur}$ (red box), viewport candidate and motion vector candidate. Dashed lines convey pixel coordinates only.} \label{image:block-diagram} \end{figure} We propose an extension of the projection-based approach \cite{Eichenseer2019} that projects the coordinates into different viewports in the perspective domain in order to realize differently oriented motion planes in 3D space. In this context, a viewport describes the orientation of a virtual perspective camera in 3D space. We allow the motion estimation procedure to choose between the front/back, the bottom/top, and the left/right viewport. We'll explain why it is possible to perform the calculations for opposite viewport pairs simultaneously, at the end of this section. Fig. \ref{image:block-diagram} describes the general procedure of the viewport-adaptive motion compensation technique for one motion vector and viewport candidate. In a first step, the pixel coordinates of the current block $(x_\text{f}, y_\text{f}) \in \boldsymbol{B}_\text{cur}$ are projected to the unit sphere in 3D space. Spherical coordinates are used to describe the pixel coordinates $(\rho_\text{s}, \theta_\text{s}, \varphi_\text{s})$ on the unit sphere. As such, the radius is fixed to $\rho_\text{s} = 1$, $\theta_s$ is the incident angle obtained from the inverse fisheye projection, e.g.\ the inverse equisolid projection \begin{align} \theta_\text{s} = 2 \arcsin\left(\frac{r_\text{f}}{2f}\right), \end{align} and $\varphi_\text{s} = \varphi_\text{f}$ is equal to the angle of the pixel in polar coordinates $(r_\text{f}, \varphi_\text{f})$. In the following, we use the different coordinate systems interchangeably. Matching coordinates in the same context can be identified based on their subscripts. In a next step, the viewport rotation according to the desired virtual camera orientation is performed. This means that the pixel coordinates $(x_\text{s}, y_\text{s}, z_\text{s})$ on the unit sphere need to be rotated in 3D space using a suitable method for describing 3D rotations. As we only perform a rotation by $\pi/2$ around the $x$- and the $y$-axis, respectively, it is sufficient to define the rotations as simple transpositions of the 3D coordinates with \begin{align} (x_\text{sr}, y_\text{sr}, z_\text{sr}) = (x_\text{s}, -z_\text{s}, y_\text{s}) \end{align} for the bottom/top viewport and \begin{align} (x_\text{sr}, y_\text{sr}, z_\text{sr}) = (z_\text{s}, y_\text{s}, -x_\text{s}) \end{align} for the left/right viewport. For the front/back viewport, no rotation has to be performed. The rotated coordinates on the unit sphere are then projected to the perspective domain, obtaining $(r_\text{pr}, \varphi_\text{pr})$, where $r_\text{pr} = r_\text{p}(\theta_\text{sr})$ and $\varphi_\text{pr} = \varphi_\text{sr}$. The motion vector $\boldsymbol{m} = (\Delta x, \Delta y)$ is then applied to the viewport rotated coordinates, resulting in the viewport rotated, motion compensated coordinates \begin{align} (x_\text{prm}, y_\text{prm}) = (x_\text{pr} + \Delta x, y_\text{pr} + \Delta y). \end{align} The coordinates $(x_\text{prm}, y_\text{prm})$ are further projected back onto the unit sphere using the inverse perspective projection \begin{align} \theta_\text{srm} = \arctan\left(\frac{r_\text{prm}}{f}\right), \end{align} yielding $(\rho_\text{srm}, \theta_\text{srm}, \varphi_\text{srm})$ with $\rho_\text{srm} = 1$ and $\varphi_\text{srm} = \varphi_\text{prm}$. Afterwards, the viewport rotation is reversed according to \begin{align} (x_\text{sm}, y_\text{sm}, z_\text{sm}) = (x_\text{srm}, z_\text{srm}, -y_\text{srm}) \end{align} for the bottom/top viewport and \begin{align} (x_\text{sm}, y_\text{sm}, z_\text{sm}) = (-z_\text{srm}, y_\text{srm}, x_\text{srm}) \end{align} for the left/right viewport. Finally, the pixel coordinates are projected back to the fisheye domain, obtaining $(r_\text{fm}, \varphi_\text{fm})$, where $r_\text{fm} = r_\text{f}(\theta_\text{sm})$ and $\varphi_\text{fm} = \varphi_\text{sm}$. The resulting cartesian coordinates $(x_\text{fm}, y_\text{fm})$ are then used to extract the corresponding pixel values from the interpolated reference frame, yielding the motion compensated block $\boldsymbol{\hat{B}}_\text{cur}$ for the regarded motion vector and viewport candidate. Hence, besides the different motion vector candidates, the viewport-adaptive motion estimation procedure additionally tests the different viewports. The candidate yielding the minimum residual error (here: SSD) between the current block $\boldsymbol{B}_\text{cur}$ and the motion compensated block $\boldsymbol{\hat{B}}_\text{cur}$ is selected adaptively. The depicted procedure is repeated for all blocks in the current image to obtain the entire motion compensated frame $\boldsymbol{\hat{I}}_\text{cur}$. We want to emphasize that all calculations are solely based on the coordinates of the regarded block pixels and no projection of the image data into the perspective domain viewports is performed at any point. \begin{figure}[t] \centering \includegraphics[width=0.91\columnwidth]{images/virtual-image-plane} \caption{Schematic of the perspective lens projection. Point $A$ with incident angle $\theta_A$ is projected onto the real image plane. Point $B$ with incident angle $\theta_B$ is projected onto the virtual image plane.} \label{image:virtual-image-plane} \end{figure} As the perspective projection is only valid for incident angles $\theta < \pi/2$, special care has be taken regarding higher incident angles that occur in fisheye images. The basic problem is depicted in \mbox{Fig. \ref{image:virtual-image-plane}}, where the light ray with incident angle $\theta_A < \pi/2$ originating at point $A$ is mapped to the real image plane, while the light ray with incident angle $\theta_B > \pi/2$ originating at point $B$ is mapped to the virtual image plane. In the context of the performed projection of the viewport rotated pixel coordinates $(\rho_\text{sr}, \theta_\text{sr}, \varphi_\text{sr})$ to the perspective domain, any coordinates with $\theta_\text{sr} > \pi/2$ are therefore mapped to the virtual image plane. Regarding the investigated viewport pairs (e.g.\ front/back), the first viewport (e.g.\ front) always lies on the real image plane while the second viewport (e.g.\ back) lies on the virtual image plane. In \cite{Eichenseer2019}, a so-called ultra wide-angle compensation is performed to account for the virtual image plane. However, it does not provide exact reprojections into the spherical domain as it performs the compensation based on the reprojected radius, and hence, does not consider the nonlinearity of the projection functions. Therefore, we employ an advancement of the ultra wide-angle compensation called virtual image plane \mbox{compensation (VIPC)}, which conditionally performs three adjustments to the described viewport-adaptive procedure. If a pixel coordinate lies on the virtual image plane, (1) the motion vector $\boldsymbol{m}$ for this coordinate is inverted, \mbox{(2) the} incident angle $\theta_\text{srm}$ received by the inverse perspective projection is corrected to $\theta_\text{srm}^\prime = \pi - \theta_\text{srm}$, and (3) the angle $\varphi_\text{srm}$ is corrected to $\varphi_\text{srm}^\prime = \varphi_\text{srm} - \pi$. By following this procedure for all pixel coordinates on the virtual image plane, exact reprojections are achieved and the calculations for both viewports in a viewport pair can be performed simultaneously. \section{Motion Compensation For Fisheye Video} \label{sec:ptmc} In traditional block matching, a motion compensated block $\boldsymbol{\hat{B}}_\text{cur}$ for the current block $\boldsymbol{B}_\text{cur}$ is obtained from a reference frame $\boldsymbol{I}_\text{ref}$ by shifting the regarded block in the reference frame according to a given motion vector candidate $\boldsymbol{m} = (\Delta x, \Delta y)$. The motion vector that leads to the minimum residual error, e.g., sum of squared differences (SSD), between $\boldsymbol{\hat{B}}_\text{cur}$ and $\boldsymbol{B}_\text{cur}$ is then selected. An entire motion compensated frame $\boldsymbol{\hat{I}}_\text{cur}$ can be obtained by taking over the best matches for all blocks in the image. While this approach provides good motion compensation quality for perspective lenses, the quality decreases notably, when fisheye lenses are applied. Thereby, the perspective projection is defined as \begin{align} r_\text{p}(\theta) = f \cdot \tan(\theta) \label{eq:perspective} \end{align} with the focal length $f$, the incident angle $\theta$ and the radius on the image plane $r_p$. While there exist four typical fisheye projectons \cite{Miyamoto1964}, \cite{Kannala2006}, we restrict our investigations to the equisolid projection without loss of generality \begin{align} r_\text{f}(\theta) = 2f \cdot \sin(\theta/2). \label{eq:fisheye} \end{align} The projection-based approach from \cite{Eichenseer2019} adapts the block matching procedure according to the fisheye projection as follows. While the overall procedure remains the same, the motion vectors are interpreted in the perspective domain instead of the fisheye domain directly. This is done using a so-called reprojection, where the pixel coordinates of the regarded block are projected into the perspective domain, first. The motion vector is then added to the pixel coordinates in the perspective domain and the obtained motion compensated coordinates are projected back to the fisheye domain. The pixel values corresponding to the motion compensated coordinates can then be extracted from the original fisheye image. Note that an interpolation of the original fisheye image is necessary, as the resulting pixel values do not necessarily lie on the integer grid.
{'timestamp': '2022-03-01T02:52:37', 'yymm': '2202', 'arxiv_id': '2202.13892', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13892'}
arxiv
\section{Introduction} Let $\mathcal{L} : \R^m\to\R$ be the log-density of a smooth distribution, known up to an additive constant. A critical problem in Bayesian inference is the design of procedures that generate samples from a target density $\pi(q) \propto \exp(\mathcal{L}(q))$. Hamiltonian Monte Carlo (HMC) \citep{Duane1987216,betancourt2017conceptual} is a Markov chain Monte Carlo (MCMC) method for sampling from arbitrary differentiable probability distributions based on numerical solutions to Hamilton's equations of motion. Unlike random walk Metropolis or the Metropolis-adjusted Langevin algorithm, HMC can propose distant states, thereby dramatically decreasing the autocorrelation between states of the chain and increasing sampling efficiency. The efficiency of HMC can be further improved by incorporating geometric concepts into the proposal mechanism. Information geometry \citep{10.5555/3019383} provides a framework for representing sets of probability densities as a Riemannian manifold whose metric can be chosen as the Fisher information matrix. When $\mathcal{L}$ decomposes into the sum of a log-likelihood and a log-prior terms, \citet{rmhmc} proposed Riemannian manifold Hamiltonian Monte Carlo (RMHMC), which sought to precondition Hamiltonian dynamics with the inverse of the sum of Fisher information of the log-likelihood and the negative Hessian of the log-prior. In general, both the Fisher information and the Hessian of the log-prior depend on the parameter, denoted here by $q$, to be sampled; this dependency produces a complicated Hamiltonian. In order to maintain the detailed balance condition of the RMHMC Markov chain, elaborate numerical integrators such as the generalized leapfrog or implicit midpoint methods must be used \citep{pourzanjani2019implicit,rmhmc,pmlr-v139-brofos21a}. These numerical integrators involve implicitly defined updates, wherein updates are defined as the solution to a fixed point equation, which are typically resolved to a prescribed convergence tolerance by fixed point iteration. \citet{lan2015} introduced Lagrangian Monte Carlo (LMC) as an alternative to RMHMC. Unlike RMHMC, which is based on numerical solutions to Hamiltonian mechanics, LMC is instead inspired by the Lagrangian formalism of classical mechanics. Although Lagrangian and Hamiltonian mechanics are formally equivalent from a physical perspective, methods of numerical integration assume a simplified form when expressed as Lagrangian mechanics. Indeed, the simplification is so significant that \citet{lan2015} was able to devise a fully explicit numerical integrator for which detailed balance could be maintained when used as a proposal operator in MCMC. However, the elimination of fixed point iterations was replaced by the requirement that four Jacobian determinants be computed in a single step of the explicit integrator. Moreover, it was stated that the explicit method had only first-order accuracy as a numerical integrator, supposedly producing less accurate solutions than the generalized leapfrog method, whose accuracy is second-order. The purpose of the present work is three-fold. First, we propose a simple mechanism by which to reduce the number of Jacobian determinant evaluations from four to two in a single step of the integrator. This is achieved by inverting the sequence in which position and velocity are integrated. Second, we will clarify that the order of the explicit integrator, with or without inversion, actually has second-order accuracy, the same as those integrators which are commonly used in RMHMC. Third, we discuss how LMC enjoys a greater robustness to human error than RMHMC. The outline of the remainder of this paper is as follows. In \cref{lagrangian-remarks:sec:preliminaries} we discuss preliminary material on Hamiltonian and Lagrangian mechanics, numerical integrators, and MCMC methods based off of these physical models. In \cref{lagrangian-remarks:sec:related-work} we review some related work in the literature on integration methods for RMHMC. In \cref{lagrangian-remarks:sec:analytical-apparatus} we proceed to our analysis of the LMC integrator, where we describe how one may reduce the number of Jacobian determinant computations while maintaining a fully explicit integration method and give a proof that the integrator has second-order accuracy. In \cref{lagrangian-remarks:sec:experimentation} we turn to the evaluation of the proposed modifications to LMC; we evaluate performance on several benchmark Bayesian inference tasks and give numerical evidence to support the claim of second-order accuracy. \section{Preliminaries}\label{lagrangian-remarks:sec:preliminaries} In this section we review the necessary background for Hamiltonian and Lagrangian Monte Carlo. \Cref{lagrangian-remarks:subsec:essentials} reviews the most important concepts from RMHMC and LMC, giving perspective on the varieties of integrators and how they are employed in a Markov chain Monte Carlo procedure. We then proceed in \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-mechanics} to recall the Hamiltonian and Lagrangian formalisms from physics. \Cref{lagrangian-remarks:subsec:numerical-integrators} then treats the matter of numerical integration of the Hamiltonian and Lagrangian mechanics. In \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-monte-carlo} we then review Hamiltonian and Lagrangian Monte Carlo using the framework of involutive Monte Carlo, wherein we give special attention to the Jacobian determinant computations that are necessitated in the Lagrangian construction. \subsection{Notation} In the context of classical mechanics, we denote by $q$ the position variable, $v$ the velocity variable, $p$ the momentum variable, and $a$ the acceleration variable, all elements of $\R^m$. We adopt the notation $q^{(k)}$ to refer to the $k$-th element of $q$, with similar conventions being employed for $v$ and $p$. Denoting $z=(q, p)$; we call $z$ a point in phase space. We denote by $\mathrm{PD}(m)$ the set of $m\times m$ positive definite matrices. Given a map $\Phi : \R^m\to\R^m$, we use the notation $\Phi^k$ to mean the composition $\Phi\circ\cdots\circ\Phi$ ($k$ times). We write $\mathrm{Id}_m$ to denote the identity matrix of size $m\times m$. We denote the Borel $\sigma$-algebra on $\R^m$ by $\mathfrak{B}(\R^m)$. \subsection{Lagrangian Monte Carlo: The Essentials}\label{lagrangian-remarks:subsec:essentials} Lagrangian Monte Carlo (LMC) is a geometric method of Bayesian inference that seeks to incorporate second-order information about the posterior in order to produce effective proposals, similar to Riemannian manifold Hamiltonian Monte Carlo (RMHMC). In this section we review the fundamentals of these methods. For applications in HMC, an important class of Hamiltonians have the following form: \begin{definition}\label{lagrangian-remarks:def:riemannian-hamiltonian} The {\it Riemannian Hamiltonian} \begin{align} \label{lagrangian-remarks:eq:hamiltonian-form} H(q, p) = U(q) + K(q, p) \end{align} where $U : \R^m\to\R$ is called the {\it potential energy} function and $K:\R^m\times\R^m\to\R$ is the {\it kinetic energy} function, having the form $K(q, p) = \frac{1}{2} p^\top \mathbf{G}^{-1}(q) p$, where $\mathbf{G} :\R^m\to \mathrm{PD}(m)$ where $\mathbf{G}$ is called the {\it metric}. \end{definition} The Riemannian metric defines Christoffel symbols which convey information about the curvature and shape of $\R^m$ imbued with the metric $\mathbf{G}$. \begin{definition}\label{lagrangian-remarks:def:christoffel-symbols} The Christoffel symbols are the $m^3$ functions defined by \begin{align} \label{lagrangian-remarks:eq:christoffel} \Gamma^k_{ij}(q) = \frac{1}{2} \sum_{l=1}^m \mathbf{G}^{-1}_{kl}(q) \paren{\frac{\partial}{\partial q^{(i)}} \mathbf{G}_{lj}(q) + \frac{\partial}{\partial q^{(j)}} \mathbf{G}_{li}(q) - \frac{\partial}{\partial q^{(l)}} \mathbf{G}_{ij}(q)}. \end{align} \end{definition} We note that the Christoffel symbols are symmetric in their lower indices (i.e. $\Gamma^k_{ij}(q) = \Gamma^k_{ji}(q)$). The Christoffel symbols play a prominent role in the development of Lagrangian mechanics. As a notational convenience, we will define the matrix-valued function $\Omega : \R\times\R^m\times\R^m\to \R^{m\times m}$ whose $(i, j)$-th entry is \begin{align} \label{lagrangian-remarks:eq:omega}\Omega_{ij}(\epsilon, q, v) = \frac{\epsilon}{2} \sum_{k=1}^m \Gamma^i_{kj}(q) v^{(k)}. \end{align} The Riemannian Hamiltonian in \cref{lagrangian-remarks:def:riemannian-hamiltonian} produces equations of motion (see \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-mechanics} for details), which do not have closed-form solutions. This necessitates the use of numerical integrators. We now review two integrators that form the basis of our evaluations: the generalized leapfrog integrator, which is a reversible, volume-preserving, and second-order accurate, and the Lagrangian leapfrog method of \citet{lan2015}. \begin{definition}\label{lagrangian-remarks:def:generalized-leapfrog} The {\it generalized leapfrog integrator} for the Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} is a map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ defined by, \begin{align} \label{lagrangian-remarks:eq:generalized-leapfrog-momentum-i} \breve{p}^{(k)} &= p^{(k)} - \frac{\epsilon}{2} \paren{-\frac{1}{2} \breve{p}^\top \mathbf{G}^{-1}(q) \paren{\frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)} \mathbf{G}^{-1}(q) \breve{p} + \frac{\partial U}{\partial q^{(k)}}(q)} \\ \label{lagrangian-remarks:eq:generalized-leapfrog-position} \tilde{q} &= q + \frac{\epsilon}{2} \paren{\mathbf{G}^{-1}(q)\breve{p} + \mathbf{G}^{-1}(\tilde{q})\breve{p}} \\ \label{lagrangian-remarks:eq:generalized-leapfrog-momentum-ii} \tilde{p}^{(k)} &= \breve{p}^{(k)} - \frac{\epsilon}{2} \paren{-\frac{1}{2} \breve{p}^\top \mathbf{G}^{-1}(q) \paren{\frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)} \mathbf{G}^{-1}(q) \breve{p} + \frac{\partial U}{\partial q^{(k)}}(\tilde{q})}. \end{align} \end{definition} Pseudo-code implementing the generalized leapfrog algorithm is given in \cref{lagrangian-remarks:alg:generalized-leapfrog} in \cref{app:algorithms}. \begin{definition}\label{lagrangian-remarks:def:lagrangian-leapfrog} The {\it Lagrangian leapfrog integrator} for the Lagrangian equations of motion given in \cref{lagrangian-remarks:eq:lagrangian-acceleration} is a map $(q, v)\mapsto (\tilde{q}, \tilde{v})$ defined by, \begin{align} \label{lagrangian-remarks:eq:lagrangian-velocity-i} \breve{v} &= \left[\mathrm{Id}_m + \Omega(\epsilon, q, v)\right]^{-1} \left[v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q)\right] \\ \label{lagrangian-remarks:eq:lagrangian-position-update} \tilde{q} &= q + \epsilon ~\breve{v} \\ \label{lagrangian-remarks:eq:lagrangian-velocity-ii} \tilde{v} &= \left[\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, \breve{v})\right]^{-1} \left[\breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q})\right]. \end{align} \end{definition} Pseudo-code implementing the Lagrangian leapfrog algorithm is given in \cref{lagrangian-remarks:alg:lagrangian-leapfrog} in \cref{app:algorithms}. Unlike the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}), which is a symplectic transformation and therefore necessarily volume-preserving, the Lagrangian leapfrog (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) is not volume-preserving. Its Jacobian determinant is computed in \cref{lagrangian-remarks:eq:lagrangian-jacobian-determinant}. A thorough treatment of numerical integrators is provided in \cref{lagrangian-remarks:subsec:numerical-integrators} In the context of Monte Carlo, this means that Markov chains constructed from repeated applications of the Lagrangian leapfrog integrator will require a Jacobian determinant computation, whereas methods based on the generalized leapfrog will not (its Jacobian determinant is one). Such a Markov chain is the subject of the following example. \begin{example} Let $H:\R^m\times\R^m \to\R$ be as in \cref{lagrangian-remarks:def:riemannian-hamiltonian} and define a probability density $\pi(q, p)\propto \exp(-H(q, p))$. Let $q\in\R^m$ be given; a single Markov chain step is constructed as follows. Sample $p \sim \mathrm{Normal}(0, \mathbf{G}(q))$. Fix $k\in\mathbb{N}$. We consider RMHMC and LMC separately: \begin{description} \item[LMC] Let $\tilde{\Phi}_\epsilon$ denote the Lagrangian leapfrog (\cref{lagrangian-remarks:def:lagrangian-leapfrog}). Compute the proposal $(\tilde{q}, \tilde{v}) = \tilde{\Phi}(q, \mathbf{G}^{-1}(q) p)$ and set $\tilde{p} = \mathbf{G}(\tilde{q}) \tilde{v}$. Compute the Jacobian determinant $J$ of the map $(q, p)\mapsto (\tilde{q},\tilde{p})$ using \cref{lagrangian-remarks:eq:lagrangian-jacobian-determinant}. \item[RMHMC] Let $\hat{\Phi}_\epsilon$ denote the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}). Compute the proposal $(\tilde{q}, \tilde{p}) = \hat{\Phi}(q, p)$ and set $J=1$. \end{description} Accept the proposal state $\tilde{q}$ with probability $\alpha((q, p), (\tilde{q},\tilde{p}), J) = \min\set{1, \frac{\pi(\tilde{q}, \tilde{p})}{\pi(q, p)} \cdot J}$; otherwise remain at the current state $q$. \end{example} A more rigorous treatment of the LMC and RMHMC Markov chains is given in \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-monte-carlo} using the framework of diffeomorphism Monte Carlo. Pseudo-code is provided in \cref{lagrangian-remarks:alg:hmc} in \cref{app:algorithms}. \section{Related Work}\label{lagrangian-remarks:sec:related-work} The focus of the present work is to investigate the numerical methods of integration that were proposed in \citet{lan2015}. \Citet{pmlr-v139-brofos21a} gave an evaluation of the implicit midpoint integrator for RMHMC with special attention paid to the errors in reversibility and volume preservation that were produced by the implicit midpoint algorithm compared to the generalized leapfrog method, as well as the energy conservation properties enjoyed by the implicit midpoint integrator. Other mechanisms of explicit integration have been considered with applications to RMHMC foremost in mind, such as \citet{cobb2019introducing} which produced a reversible, volume-preserving numerical method in an expanded phase-space. Due to the expansion of phase-space, this integrator cannot be used to produce a Markov chain satisfying detailed balance. The work of \citet{NIPS2014_a87ff679} explored alternating blockwise Metropolis-within-Gibbs-like strategies with Riemannian metrics chosen to produce separable Hamiltonians within each block; each block can then be integrated using the standard leapfrog integrator. LMC has previously been criticized in the literature for having unfavorable performance in high dimensions; this failure of LMC in relation to RMHMC is discussed in \citet{geometric-foundations} and we will see evidence of this degradation in \cref{lagrangian-remarks:subsec:student-t}. \section{Analytical Apparatus}\label{lagrangian-remarks:sec:analytical-apparatus} In this section we describe an algorithmic recommendation for the numerical integrator used in Lagrangian Monte Carlo and we clarify certain statements around the order of this numerical method. Specifically, we show how to reduce the number of determinant computations from four to two, and that the integrator of Lagrangian dynamics has third-order local error, comparable to the error of the (generalized) leapfrog method used in HMC. \subsection{Inversion of the Integration Sequence} A disadvantage of the Lagrangian integrator is that it involves four Jacobian determinant computations at each step of the integrator. In general, computing the Jacobian determinant of an $m\times m$ matrix incurs a computational cost like $\mathcal{O}(m^3)$. Therefore, it seems worthwhile to investigate mechanisms by which to reduce the number of these calculations that are required. \Citet{lan2015} proposed one method that has only two Jacobian determinant computations, but necessitates the return to implicit methods of integration. To retain the advantages of explicit integration, we propose a method that computes two Jacobian determinants in every step and consists only of {\it explicit} integration steps. To achieve this, we propose a conceptually simple procedure: invert the sequence in which position and velocity are updated in the Lagrangian integrator so that position is updated twice at the beginning and end of each step and velocity is updated once in between each update to position. Formally: \begin{definition}\label{lagrangian-remarks:def:inverted-lagrangian-leapfrog} The {\it inverted Lagrangian leapfrog integrator} for the Lagrangian equations of motion given in \cref{lagrangian-remarks:eq:lagrangian-acceleration} is a map $(q, v)\mapsto (\tilde{q}, \tilde{v})$ defined by, \begin{align} \label{lagrangian-remarks:eq:inverted-lagrangian-position-i} \breve{q} &= q + \frac{\epsilon}{2} ~v \\ \label{lagrangian-remarks:eq:inverted-lagrangian-velocity} \tilde{v} &= \left[\mathrm{Id}_m + 2\Omega(\epsilon, \breve{q}, v)\right]^{-1} \left[v - \epsilon \mathbf{G}^{-1}(\breve{q}) \nabla U(\breve{q})\right] \\ \label{lagrangian-remarks:eq:inverted-lagrangian-position-ii} \tilde{q} &= \breve{q} + \frac{\epsilon}{2} \tilde{v}. \end{align} \end{definition} Pseudo-code for this procedure is provided in \cref{lagrangian-remarks:alg:inverted-lagrangian-leapfrog} in \cref{app:algorithms}. The basic modification requires only two Jacobian determinant computations per step since the two updates to position in \cref{lagrangian-remarks:eq:inverted-lagrangian-position-i,lagrangian-remarks:eq:inverted-lagrangian-position-ii}, being shear transformations, are volume-preserving in $(q, v)$-space \citep{modi2021delayed}. The required change in volume due to the mapping $(q, p)\mapsto (\tilde{q}, \tilde{p})$ is readily obtained as \begin{align} \begin{split} \label{lagrangian-remarks:eq:inverted-lagrangian-jacobian-determinant} &\abs{\mathrm{det}\paren{\frac{\partial (\tilde{q}, \tilde{p})}{\partial (q, p)}}} = \abs{\frac{\mathrm{det}(\mathbf{G}(\tilde{q}))}{\mathrm{det}(\mathbf{G}(q))} \frac{\mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, \breve{q}, \tilde{v}))}{\mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, \breve{q}, v))}}. \end{split} \end{align} Although this Jacobian determinant differs from that produced by \cref{lagrangian-remarks:alg:lagrangian-leapfrog} in \cref{app:algorithms}, we still have the following important property. \begin{lemma}\label{lagrangian-remarks:lem:inverted-lagrangian-properties} The inverted Lagrangian leapfrog integrator is self-adjoint and has at least first-order local error. \end{lemma} A proof is given in \cref{lagrangian-remarks:app:proofs-concerning-numerical-order}. \begin{corollary} The inverted Lagrangian leapfrog integrator has at least second-order local error. \end{corollary} \begin{proof} This follows as an immediate corollary of \cref{lagrangian-remarks:lem:inverted-lagrangian-properties} \end{proof} \begin{definition}\label{lagrangian-remarks:def:ilmc} Let $\Phi_\epsilon$ be the inverted Lagrangian leapfrog integrator with step-size $\epsilon\in\R$ (\cref{lagrangian-remarks:def:inverted-lagrangian-leapfrog}). Let $k\in\mathbb{N}$ be the number of integration steps. The {\it inverted Lagrangian Monte Carlo (ILMC)} is an instance involutive Monte Carlo (\cref{lagrangian-remarks:def:involutive-monte-carlo}) with involution $\mathbf{F} \circ \Phi_{\epsilon}^k$ where $\mathbf{F}$ is the momentum flip operator (\cref{lagrangian-remarks:def:momentum-flip}). \end{definition} Let us denote by $\hat{\Phi}_\epsilon$ the Lagrangian leapfrog integrator (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) and $\check{\Phi}_{\epsilon}$ the inverted Lagrangian leapfrog (\cref{lagrangian-remarks:def:inverted-lagrangian-leapfrog}). Let $\Phi_\epsilon$ be the exact time $\epsilon$ solution of \cref{lagrangian-remarks:eq:lagrangian-acceleration}. Because both methods are second-order accurate, it follows that \begin{align} \Vert \hat{\Phi}_\epsilon - \check{\Phi}_\epsilon \Vert &\leq \Vert \hat{\Phi}_\epsilon - \Phi_\epsilon \Vert + \Vert \check{\Phi}_\epsilon - \Phi_\epsilon \Vert \\ &= \mathcal{O}(\epsilon^3) \end{align} Intuitively, in the limit of small step-sizes, the difference in proposals generated by the Lagrangian leapfrog and the inverted Lagrangian leapfrog will be minimal, but ILMC (\cref{lagrangian-remarks:def:ilmc}) involves half the number of Jacobian determinant computations compared to LMC (\cref{lagrangian-remarks:def:lmc}) and should therefore be preferred. On the other hand, for large step-sizes, the situation is less clear. \subsection{Aversions to Inverting the Integration Sequence} \input{figures/position-difference} In the case when $\mathbf{G} = \mathrm{Id}_m$, the Lagrangian integrator devolve into the standard leapfrog integrator (\cref{lagrangian-remarks:def:standard-leapfrog}) that is ubiquitous in HMC. There are good reasons why implementations of HMC integrate in the order of an initial half-step in momentum, a full step in position, and then a second half-step of momentum. This is described visually by \citet{bou-rabee_sanz-serna_2018} for the Hamiltonian $H(q, p) = q^2 / 2 + p^2 / 2$, who make the argument that the leapfrog integrator produces high acceptance probabilities along the $q$-axis, which are desirable. By contrast, inverted leapfrog (\cref{lagrangian-remarks:def:inverted-leapfrog}) produces large acceptance probabilities along the $p$-axis, which are not valuable in HMC. Here we wish to expand on this example to consider what happens when HMC Markov chains based on the standard leapfrog and inverted leapfrog are initialized at stationarity. Based on the symmetric roles of $q$ and $p$ in the Hamiltonian, it is tempting to conclude that these Markov chains would exhibit similar performance profiles; surprisingly, this is not the case as shown in the following example. \begin{example}\label{lagrangian-remarks:ex:inverted-order-inferior} Consider a Hamiltonian of the form $H(q, p) = \omega^2 q^2 / 2 + p^2 / 2$. This Hamiltonian corresponds to the distributions $q\sim\mathrm{Normal}(0, 1/\omega^2)$ and $p\sim \mathrm{Normal}(0, 1)$. Let $\hat{\Phi}_\epsilon : \R^m\times\R^m\to \R^m\times\R^m$ and $\check{\Phi}_\epsilon : \R^m\times\R^m\to\R^m\times\R^m$ be the single step leapfrog (\cref{lagrangian-remarks:def:standard-leapfrog}) and inverted leapfrog (\cref{lagrangian-remarks:def:inverted-leapfrog}) methods with step-size $\epsilon$, respectively. Let $\mathrm{Proj}_q(q, p) = q$ be the projection onto the $q$-variables. Then, \begin{align} \mathbb{E} \left[(\mathrm{Proj}_q\circ\hat{\Phi}_\epsilon(q, p) - q)^2\right] &= \frac{\epsilon^4\omega^2}{4} + \epsilon^2 \\ \mathbb{E} \left[(\mathrm{Proj}_q\circ\check{\Phi}_\epsilon(q, p) - q)^2\right] &= \frac{\epsilon^4\omega^2}{4} + \epsilon^2 \paren{1 - \frac{\epsilon^2\omega^2}{4}}. \end{align} Both the leapfrog and inverted leapfrog methods are only numerically stable when $\epsilon^2 \omega^2 < 4$ \citep{leimkuhler_reich_2005}. Hence, $\mathbb{E} \left[(\mathrm{Proj}_q\circ\check{\Phi}_\epsilon(q, p) - q)^2\right] < \mathbb{E} \left[(\mathrm{Proj}_q\circ\hat{\Phi}_\epsilon(q, p) - q)^2\right]$, which we interpret to mean that, in a single step of the integrator, the expected squared distance between initial and terminal position is greater for the leapfrog integrator than for the inverted leapfrog. By deriving the propagator matrices (see \cref{lagrangian-remarks:app:propagator-matrices}) of the leapfrog and inverted leapfrog integrators, we may deduce exact formulas for the $k$-step quantities $\mathbb{E} \left[(\mathrm{Proj}_q\circ\hat{\Phi}^k_\epsilon(q, p) - q)^2\right]$ and $\mathbb{E} \left[(\mathrm{Proj}_q\circ\check{\Phi}^k_\epsilon(q, p) - q)^2\right]$. In \cref{lagrangian-remarks:fig:position-difference} we show the difference of these expected squared distances as a function of the number of steps and for several step-sizes. Notably, this difference is always non-negative, indicating that one expects the leapfrog to produce more distant proposals than the inverted leapfrog in the Gaussian case. \end{example} Because autocorrelation is related to the distance to subsequent samples, one expects the inverted leapfrog method to exhibit fewer effective samples. This will be true even if LMC Markov chain is initialized in the stationary distribution. This illustrates an important short-coming of inverting the integration sequence, which must be balanced against computational savings obtained by the reduction in Jacobian determinant computations in the LMC setting. \subsection{The Order of the Explicit Integrators} In \citet{lan2015}, the authors showed that the local error rate of the Lagrangian integrator is at least $\mathcal{O}(\epsilon^2)$. We now build on this foundation in order to deduce that the local error rate of the Lagrangian leapfrog is at least $\mathcal{O}(\epsilon^3)$. This means that the order of the LMC integrator matches the local and global error rates of the integrators used in HMC and RMHMC. Proofs of \cref{lagrangian-remarks:lem:second-order-local-error,lagrangian-remarks:lem:self-adjoint} may be found in \cref{lagrangian-remarks:app:proofs-concerning-numerical-order}. \begin{lemma}\label{lagrangian-remarks:lem:second-order-local-error} The explicit integrator of the Lagrangian dynamics has at least first-order local error. \end{lemma} \begin{lemma}\label{lagrangian-remarks:lem:self-adjoint} The explicit integrator of Lagrangian dynamics is self-adjoint. \end{lemma} \begin{proposition}\label{lagrangian-remarks:prop:third-order-local-error} The explicit integrator of the Lagrangian dynamics has at least third-order local error. \end{proposition} \begin{proof} From \cref{lagrangian-remarks:lem:second-order-local-error} we know that $r\geq 1$. Suppose $r=1$. From \cref{lagrangian-remarks:lem:self-adjoint} we know that the integrator is self-adjoint. From \cref{lagrangian-remarks:thm:self-adjoint-even-order} we know that the order of a self-adjoint method must be even; hence $r$ cannot be odd. But $r=1$ by assumption, a contradiction. Therefore, it must be that $r\geq 2$ so that the explicit integrator has, at least, third-order local error. \end{proof} Denote by $\hat{\Phi}_\epsilon$ the second-order integrator of Lagrangian dynamics. If $\hat{\Phi}_\epsilon(q_0, v_0) = (\hat{q}_\epsilon, \hat{v}_\epsilon)$, one wonders if $(\hat{q}_\epsilon, \hat{p}_\epsilon)$ is a second-order approximation of the {\it Hamiltonian dynamics}, where $\hat{p}_\epsilon = \mathbf{G}(\hat{q}_\epsilon) \hat{v}_\epsilon$. Indeed, this is true and follows as an immediate consequence of \cref{lagrangian-remarks:prop:composition-order} with diffeomorphism $(q, v)\mapsto (q, \mathbf{G}v)$. \subsection{Efficient Computation of the Jacobian Determinant and the Update to Velocity} The update to the velocity in \cref{lagrangian-remarks:eq:inverted-lagrangian-velocity,lagrangian-remarks:eq:lagrangian-velocity-i,lagrangian-remarks:eq:lagrangian-velocity-ii} and the associated change-in-volume in \cref{lagrangian-remarks:eq:inverted-lagrangian-jacobian-determinant,lagrangian-remarks:eq:inverted-lagrangian-jacobian-determinant} involve manipulations of a matrix of the form $\mathrm{Id} + \Omega(\epsilon, q, v)$: in the former case, we must solve a linear system involving this matrix while in the latter case we must compute the absolute value of its Jacobian determinant. An efficient procedure by which to achieve both of these objectives is to compute the PLU decomposition of $\mathrm{Id} + \Omega(\epsilon, q, v)=\mathbf{P}\mathbf{L}\mathbf{U}$ where $\mathbf{P}$ is a permutation matrix, $\mathbf{L}$ is a lower-triangular matrix with unit diagonal, and $\mathbf{U}$ is an upper-triangular matrix. The computational cost of this decomposition is $\frac{2}{3}m^3 + \mathcal{O}(m^2)$. Linear systems can be solved using the PLU decomposition by applying the permutation and solving the triangular systems via forward-backward substitution. Moreover, the required Jacobian determinant is simply $\prod_{i=1}^m \mathbf{U}_{ii}$, since the determinant of the permutation matrix has unit magnitude and the lower-triangular matrix $\mathbf{L}$ has unit Jacobian determinant since all of its diagonal elements are equal to one. \subsection{Built-In Robustness of the Lagrangian Integrator}\label{lagrangian-remarks:subsec:robustness} As shown in \citet{brofos2021numerical}, the volume-preservation property (i.e. $J=1$ in \cref{lagrangian-remarks:alg:generalized-leapfrog} in \cref{app:algorithms}) of the generalized leapfrog integrator is predicated on the symmetry of partial derivatives $\nabla_q^\top \nabla_p H(q, p) = \nabla_p \nabla_q H(q,p)$. In an {\it implementation} of the generalized leapfrog integrator we may suppose that we have functions $g_{k}(q)$ representing $\frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$. Substituting this function into the definition of the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}) yields the following map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ \begin{align} \breve{p}^{(k)} &= p^{(k)} - \frac{\epsilon}{2} \delta_k(q, \breve{p}) \\ \tilde{q} &= q + \frac{\epsilon}{2} \paren{\Delta(q, \breve{p}) + \Delta(\tilde{q}, \breve{p})} \\ \tilde{p}^{(k)} &= \breve{p}^{(k)} - \frac{\epsilon}{2} \delta_k(\tilde{q}, \breve{p}), \end{align} where \begin{align} \delta_k(q, p) &= -\frac{1}{2} p^\top \mathbf{G}^{-1}(q) g_k(q) \mathbf{G}^{-1}(q) p + \frac{\partial U}{\partial q^{(k)}}(q) \\ \Delta(q, p) &= \mathbf{G}^{-1}(q)p \end{align} When $g_k(q) = \frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$, the resulting map is necessarily volume-preserving. However, we may then ask the question, ``What happens when $g_k(q)$ is {\it incorrectly implemented} so that, in fact, $g_k(q) \neq \frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$?'' The symmetry of partial derivatives has therefore been violated since \begin{align} \frac{\partial\Delta}{\partial q^{(k)}}(q, p) = \frac{\partial \mathbf{G}^{-1}}{\partial q^{(k)}}(q) p \neq -\mathbf{G}^{-1}(q) g_k(q) \mathbf{G}^{-1}(q) p = \frac{\partial \delta_k}{\partial p}(q, p). \end{align} In the case of the RMHMC Markov chain (\cref{lagrangian-remarks:def:rmhmc}), detailed balance is no longer satisfied and there is no expectation that the RMHMC will converge to the target distribution. The situation is different in the case of the LMC Markov chain (\cref{lagrangian-remarks:def:lmc}). The fundamental difference is that LMC {\it expects} the transformation $(q, v)\mapsto (\tilde{q},\tilde{v})$ to be non-volume-preserving, hence necessitating the Jacobian determinant correction in \cref{lagrangian-remarks:eq:acceptance-probability}. To see that the change-in-volume is still correctly computed even when $g_k(q) \neq \frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$, we observe that the Lagrangian leapfrog's (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) update to velocity in \cref{lagrangian-remarks:eq:lagrangian-velocity-i} is a special case of the following map: \begin{align} \breve{v} = \paren{\mathrm{Id}_m + \mathbf{A}(q, v)}^{-1} \paren{v - \mathbf{b}(q)} \end{align} where $\mathbf{A} : \R^m\times\R^m\to\R^{m\times m}$ and $\mathbf{b} : \R^m\to\R^m$. Under the assumption that $\mathbf{A}(q, v)\tilde{v} = \mathbf{A}(q, \tilde{v}) v$ (which holds for the correctly implemented LMC with $\mathbf{A} = \Omega(\epsilon, q, v)$ by \cref{lagrangian-remarks:prop:omega-properties}), the Jacobian determinant of the map $(q, v)\mapsto (q, \breve{v})$ is \begin{align} \label{lagrangian-remarks:eq:general-determinant} \abs{\mathrm{det}\paren{\frac{\partial (q, \breve{v})}{\partial (q, v)}}} = \abs{\frac{\mathrm{det}(\mathrm{Id}_m + \mathbf{A}(q, \breve{v}))}{\mathrm{det}(\mathrm{Id}_m + \mathbf{A}(q, v))}}. \end{align} Hence, if we adopt the notation $g_{k,ij}(q)$ as the $(i,j)$-th element of $g_k(q)$, and substitute \begin{align} \tilde{\Gamma}^k_{ij}(q) = \frac{1}{2} \sum_{l=1}^m \mathbf{G}^{-1}_{kl}(q) \paren{g_{i,lj}(q) + g_{j,li}(q) - g_{l, ij}(q)} \end{align} for \cref{lagrangian-remarks:eq:christoffel} and define $\tilde{\Omega}_{ij}(\epsilon, q, v) = \frac{\epsilon}{2} \sum_{k=1}^m \tilde{\Gamma}^i_{kl}(q) v^{(k)}$ then we still have $\tilde{\Omega}(\epsilon, q, v) \breve{v} = \tilde{\Omega}(\epsilon, q, \breve{v})v$ using the fact that $\tilde{\Gamma}^k_{ij}(q) = \tilde{\Gamma}^k_{ji}(q)$. Hence, with $\mathbf{A}(q, v) = \tilde{\Omega}(\epsilon, q, v)$, \cref{lagrangian-remarks:eq:general-determinant} applies to compute the Jacobian determinant. \section{Experimentation}\label{lagrangian-remarks:sec:experimentation} We now turn our attention to the empirical evaluation of the numerical integrator of Lagrangian dynamics in terms of its numerical order, its inverted variant, and its robustness to misspecification of the derivatives of the metric. We begin in \cref{lagrangian-remarks:subsec:second-order} by numerically validating the second-order behavior of the numerical integrator. In the subsequent material, we evaluate the integrator with and without inversion in a banana-shaped distribution, in Bayesian logistic regression, in a multiscale Student-$t$ distribution, and in a stochastic volatility model. As baselines, we consider RMHMC and HMC. Code to reproduce these experiments may be found at \if00 { \url{https://github.com/JamesBrofos/Rethinking-Lagrangian-Monte-Carlo}. } \fi \if10 { \url{https://github.com/Anonymous/GitHubLink}. } \fi We consider three metrics by which to assess the convergence of the Markov chain produced by ILMC and the baselines. First, we consider the expected squared jump distance (ESJD) as described in \citet{esjd}; this measures the expected squared distance between the current state and the next state, where the expectation is computed over the acceptance probability. The larger the ESJD, the less serial autocorrelation in the Markov chain samples. We also consider the effective sample size (ESS) normalized by time elapsed, which gives an indication of the sampling efficiency of each method. We use the implementation of ESS as given in \citet{arviz_2019}. We also consider the method of \citet{brofos2021numerical} for measuring the ergodicity of the Markov chain given i.i.d. samples. Under this procedure, we project the i.i.d. samples and the Markov chain samples along one-hundred random directions and measure the average value of the Kolmogorov-Smirnov statistics of these one-dimensional distributions. By the Cram\'{e}r-Wold theorem, the closer these Kolmogorov-Smirnov statistics are concentrated toward zero, the higher the fidelity between the Markov chain samples and the i.i.d. samples. In implementing the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}), we resolve the fixed point equations \cref{lagrangian-remarks:eq:generalized-leapfrog-momentum-i,lagrangian-remarks:eq:generalized-leapfrog-position} using fixed point iteration to a convergence tolerance of $1\times 10^{-6}$, with convergence measured in $\Vert\cdot\Vert_\infty$. \subsection{Demonstration of Second-Order Error}\label{lagrangian-remarks:subsec:second-order} \input{figures/second-order} We consider the following non-separable Hamiltonian $H(q, p) = \frac{q^2 p^2}{2}$, which describes geodesic motion in $\R$ when equipped with the metric $G(q) = 1 / q^2$. After converting from momentum to velocity $v_t = \frac{p_t}{q_t^2}$, we obtain the second-order differential equation $a_t = \frac{v_t^2}{q_t}$. Given initial conditions $q_0$ and $p_0$ (in the Hamiltonian formalism), the exact solution to this differential equation is $q_t = q_0 \exp(q_0 p_0 t)$ and $v_t = q_0^2p_0 \exp(q_0 p_0 t)$. If, as claimed, the Lagrangian integrator is indeed second-order, then it should exhibit third-order local error according to \cref{lagrangian-remarks:def:integrator-order}. We evaluate this by examing the squared error between the output of the numerical integrator and the analytical solution for a decreasing sequence of step-sizes $\epsilon$; that is, denoting the output of a single step of the Lagrangian integrator by $(\hat{q}_\epsilon,\hat{v}_\epsilon)$, we measure $\Vert \hat{q}_\epsilon - q_\epsilon\Vert_2^2 + \Vert \hat{v}_\epsilon - v_\epsilon\Vert_2^2$. We observe in \cref{lagrangian-remarks:fig:second-order-error} that this error decreases linearly on a log-log scale and, critically, the slope of this linear relation is three. This demonstrates numerically the third-order local error of the Lagrangian integrator and gives support to the claim that the method is of second-order accuracy. \subsection{Banana-Shaped Posterior Distribution} \input{figures/banana/banana} The banana-shaped distribution was proposed in \citet{rmhmc} by Cornebise and Julien as an example of Bayesian inference in non-identifiable models. In this example, a non-identifiable likelihood function in Bayesian linear regression is regularized according to a normal prior, the effect of which is to produce a density with symmetric, elongated tails. The generative model of this distribution is as follows: \begin{align} (\theta_1,\theta_2) &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(0, \sigma^2_\theta) \\ y_i \vert \theta_1,\theta_2 &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(\theta_1 + \theta_2^2, \sigma^2_y) ~~~~~ \mathrm{for}~~ i = 1,\ldots, n. \end{align} This distribution also illustrates a short-coming of the generalized leapfrog method. For large step-sizes, the implicit update to the momentum variable will not have a solution; therefore, the generalized leapfrog integrator is compelled to adopt a significantly smaller step-size than can be used even by the standard leapfrog method. Indeed, an advantage of explicit numerical integrators is that one does not need to fret that constituent update steps in the integrator will not have solutions. We seek to draw 1,000,000 samples from this posterior. In our experiments we set $\sigma^2_\theta = \sigma^2_y = 2$, $n = 100$, and set parameter values $\theta_1 = 1/2$ and $\theta_2 = \sqrt{1 - 1/2}$ for generating synthetic data. For HMC we use a step-size of $0.1$ and ten integration steps, which was found to produce an acceptance probability between eighty and ninety percent. As for the Riemannian metric, we adopt the sum of the Fisher information of the log-likelihood and the negative Hessian of the log-prior. For RMHMC, we use a step-size of $0.04$ and twenty integration steps, which produces an acceptance probability of around ninety percent. For LMC and ILMC, we use twenty integration steps with a step-size of $0.1$, which yields an acceptance probability of around ninety percent. These parameter configurations were found to produce reasonable Markov chains based on hand-tuning. Results showing the effective sample size (ESS) per second are provided in \cref{lagrangian-remarks:fig:banana}; we see that RMHMC struggles in this distribution, being even worse than ordinary HMC due to the requirement to use a small step-size. By contrast, LMC and ILMC do significantly better, with ILMC having the best ESS per second due to its elimination of two Jacobian determinant computations. We also show the distribution of this average value over ten trials for each sampling method. We find that the geometric methods based on the Lagrangian formalism perform similarly under this ergodicity measure and outperform competing methods. \subsection{Bayesian Logistic Regression} \input{figures/logistic-regression/logistic-breast} \input{figures/logistic-regression/logistic-thyroid} We consider Bayesian logistic regression on a breast cancer and a thyroid cancer dataset. The breast cancer dataset has 277 observations and ten covariates while the thyroid cancer dataset has 215 observations and six covariates. The Bayesian generative model is assumed to have the following form: \begin{align} \beta &\sim\mathrm{Normal}(0,\alpha^{-1} \mathrm{Id}) \\ y_i \vert \mathbf{x}_i, \beta &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Bernoulli}(\sigma(\mathbf{x}_i^\top\beta))~~~~~ \mathrm{for}~~ i = 1,\ldots, n, \end{align} where $\sigma : \R\to(0,1)$ denotes the sigmoid function. As the Riemannian metric, we adopt the sum of the Fisher information of the log-likelihood and the negative Hessian of the log-prior. We show in \cref{lagrangian-remarks:fig:logistic-breast,lagrangian-remarks:fig:logistic-thyroid} the minimum ESS per second, where we have also considered varying the convergence threshold used to solve fixed point iterations in RMHMC; as discussed in detail by \citet{brofos2021numerical}, implementations of RMHMC require that the implicit updates to momentum and position be resolved using an iterative procedure such as fixed point iteration or Newton's method. The tolerance in these numerical methods directly controls the degree to which reversibility and volume preservation are violated by the implementation of the generalized leapfrog method: For small values of the threshold, these theoretical properties are closely respected by the numerical method, while for large thresholds, violations occur. Reversibility and volume preservation imply detailed balance in HMC, and violations imply that the detailed balance may not hold in an implementation of RMHMC with large thresholds. By contrast, LMC and ILMC are fully explicit and detailed balance is respected to machine precision for either method. We observe that both sampling methods based on Lagrangian mechanics exhibit higher ESS per second than their counterpart based on the Hamiltonian formalism except for the largest thresholds (with the greatest bias); we refer the interested reader to \citet{brofos2021numerical} for a detailed discussion on the effects of the convergence threshold on the bias of the RMHMC Markov chain. Moreover, ILMC outperforms LMC on this metric. When comparing the ESJD, we observe that, consistent with our understanding in the Gaussian case, the ILMC method has the smallest expected distance traveled. However, this is offset by a faster sampling iteration due to only requiring two Jacobian determinant calculations instead of four. \subsection{Multiscale Student's $t$-Distribution}\label{lagrangian-remarks:subsec:student-t} \input{figures/t/t-5} \input{figures/t/t-5000} Multiscale distributions can be challenging for HMC since trajectories integrated by the leapfrog method will exhibit significant oscillations along directions of the distributions possessing the smallest spatial scale. To investigate this phenomenon, we consider sampling from a multivariate Student-$t$ distribution with a multiscale covariance; in particular we consider a distribution with density function, \begin{align} \pi(x) \propto \left[1 + \frac{1}{\eta} x^\top\Sigma^{-1}x\right]^{-(\eta + m)/2}, \end{align} where $x\in\R^m$, $\eta > 2$ is the degrees-of-freedom, and $\Sigma$ is the scale matrix. We consider scale matrices of the form $\Sigma = \mathrm{diag}(1, \ldots, 1, \sigma^2) \in \R^{m\times m}$. In our experiments we set $m=20$ and $\eta \in \set{5\times 10^0, 5\times 10^3}$ and consider multiscale distributions for $\sigma^2\in \set{1\times 10^1, 1\times 10^2,1\times 10^3, 1\times 10^4}$. We choose these two values of the degrees-of-freedom to demonstrate two distinct sampling behaviors. For the Riemannian methods, we consider a step-size of $0.7$ and twenty integration steps. As the Riemannian metric, we use the positive definite term in the negative Hessian of the log-density of the distribution. For $\nu = 5\times 10^0$, we observe that the ESJD is largest for RMHMC; this occurs because RMHMC enjoys a far superior acceptance probability in this scenario at 95\% whereas LMC and ILMC have acceptance probabilities of 40\% and 62\%, respectively. This degraded performance of the Lagrangian methods is then reflected in the time-normalized ESS, which shows RMHMC dominating LMC, ILMC, and HMC. For the case of $\eta = 5\times 10^3$, circumstances are more favorable to the Lagrangian methods, with ILMC exhibiting the best performance in terms of time-normalized ESS, with the LMC method giving the second best results. In terms of ESJD, we observe that ILMC moves less far in sample space than LMC, but that this is offset by the faster sampling. As in the case of the banana-shaped distribution, we may sample from this target density analytically in order to assess the ergodicity properties of the samplers. We find that the ergodicity of the geometric methods is essentially constant with respect to the multiscale parameter, whereas the performance of Euclidean HMC noticeably degenerates. For both $\nu = 5\times 10^3$ and $\nu = 5\times 10^0$, one observes that the performance of the geometric methods is essentially constant over the multiple scales of the target distribution, demonstrating the beneficial effect of capturing the geometry of the target. \subsection{Stochastic Volatility Model} \input{figures/stochastic-volatility/stochastic-volatility} We consider Bayesian inference in a stochastic volatility model. We consider the following generative model: \begin{align} \label{lagrangian-remarks:eq:stochastic-volatility-x} x_t\vert x_{t-1}, \phi,\sigma^2 &\sim\mathrm{Normal}(\phi x_{t-1}, \sigma^2) \\ \label{lagrangian-remarks:eq:stochastic-volatility-y} y_t \vert \beta, x_t &\sim \mathrm{Normal}(0, \beta^2\exp(x_t)) \end{align} for $t = 2,\ldots, T$ in \cref{lagrangian-remarks:eq:stochastic-volatility-x} and $t=1,\ldots, T$ in \cref{lagrangian-remarks:eq:stochastic-volatility-y} and with priors $x_1\sim \mathrm{Normal}(0, \sigma^2 / (1- \phi^2))$, $(\phi+1)/2\sim\mathrm{Beta}(20, 3/2)$, $1/\sigma^2\sim \xi^2(10, 1/20)$, and the prior over $\beta$ being proportional to $1/\beta^2$. Given $(y_1,\ldots, y_T)$, we seek to sample the posterior of $(x_1,\ldots, x_T, \phi, \beta, \sigma^2)$. We follow \citet{rmhmc} and employ a Metropolis-within-Gibbs-like alternating procedure for sampling the posteriors of $(x_1,\ldots, x_T)$ and $(\phi,\beta,\sigma^2)$. In our experiments we set $T=1,000$ and use values of $\phi=0.98$, $\beta=0.65$, and $\sigma^2 = 0.15^2$. For HMC, we use a step-size of 0.01 and fifty integration steps when sampling $(\phi,\beta,\sigma^2)$; for the geometric methods, we use a step-size of 0.5 and six integration steps. As for the Riemannian metric, we adopt the sum of the Fisher information of the log-likelihood and the negative Hessian of the log-prior. We compare the average ESS per second among the three latent variables $(\phi, \beta, \sigma^2)$ with results reported in \cref{lagrangian-remarks:fig:stochastic-volatility}. We find that LMC and ILMC are the strongest performing methods, with LMC having better ESS per second due to its more efficient traversal of the sample space. Indeed, ILMC has degraded performance in this example, owing to its greater autocorrelation, but nevertheless outperforms HMC and RMHMC. \subsection{Fitzhugh-Nagumo Model} \input{figures/fitzhugh-nagumo/fitzhugh-nagumo} We now investigate the LMC and RMHMC in the Fitzhugh-Nagumo posterior distribution. The Fitzhugh-Nagumo posterior distribution has the following generative model, \begin{align} (a, b , c) &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(0, 1) \\ \hat{r}_{t_k} &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(r_{t_k}, \sigma^2) \\ \hat{v}_{t_k} &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(v_{t_k}, \sigma^2) ~~~\mathrm{for}~k=1,\ldots, n, \end{align} where $t_1,\ldots, t_n$ are evenly spaced time points in $[0, 10)$ and $r_t$ and $v_t$ obey the differential equations, \begin{align} \dot{r}_t &= -\frac{v_t - a + b r_t}{c} \\ \dot{v}_t &= cv_t - \frac{cv_t^3}{3} + cr_t. \end{align} In our experiments we give initial conditions $v_0 = 1$, $r_0 = -1$, $\sigma^2 = 1/4$, and $n=200$. The objective is to infer the posterior of $q=(a,b,c)$ given observations $\set{(\hat{v}_{t_k}, \hat{r}_{t_k})}_{k=1}^{200}$. Here we emphasize a different aspect of the computation: its robustness to misspecification. As described in \cref{lagrangian-remarks:subsec:robustness}, the proof that the generalized leapfrog integrator is a volume-preserving transformation when used to integrate Hamiltonian vector fields is the symmetry of partial derivatives. We therefore consider the repercussions of an error in the implementation of partial derivatives that invalidates this requirement. To give further context to this experiment, we quote from \citet{dahlquist2003numerical}: ``In all numerical work, one must expect that clerical errors, errors in hand calculation, and misunderstandings will occur. [...] Most of the errors depend on the so-called human factor. [...] We take up these sources of error in order to emphasize that both the person who carries out a calculation and the person who guides the work of others can plan so that such sources of error are not damaging.'' It seems to us, therefore, that the robustness of a Markov chain procedure to human misspecification is a most desirable circumstance. As described in \citet{rmhmc}, computing the gradient of the log-posterior, the Riemannian metric, and the Jacobian of the Riemannian metric requires us to compute sensitivity equations of the form $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial r_t}{\partial q_i}$, $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial v_t}{\partial q_i}$, $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial^2 r_t}{\partial q_i \partial q_j}$, and $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial^2 v_t}{\partial q_i \partial q_j}$ for $i=1,2, 3$ and $j=1,2,3$. We employ a Riemannian metric of the form, \begin{align} \mathbf{G}_{ij}(q) = \frac{1}{\sigma^2}\sum_{k=1}^{n} \paren{\frac{\partial v_{t_k}}{\partial q_i}\frac{\partial v_{t_k}}{\partial q_j} + \frac{\partial r_{t_k}}{\partial q_i}\frac{\partial r_{t_k}}{\partial q_j}} + \mathbf{1}\set{i=j}. \end{align} If any of these sensitivity equations are misspecified, then we will destroy the symmetry of partial derivatives required by the leapfrog integrator to preserve volume. However, the integrator used in LMC and ILMC is non-volume-preserving by design, and the appropriate volume correction is readily computable during sampling. We expect, therefore, that the volume correction employed in LMC and ILMC will provide robustness against these incorrectly computed quantities. We note that, in this case, there is no obvious mechanism by which to compute the required Jacobian determinant when the generalized leapfrog integrator is no longer a symplectic transformation. In \cref{lagrangian-remarks:fig:fitzhugh-nagumo} we show the minimum ESS per second and Kolmogorov-Smirnov statistics for sampling from the Fitzhugh-Nagumo posterior. We observe that LMC outperforms ILMC in this example, but that both Lagrangian methods outperform HMC and RMHMC. In terms of ergodicity, all methods perform similarly. When we introduce changes to the sensitivity equations, we observe that RMHMC's ergodicity severely degrades. For HMC, for which higher-order sensitivities are not required (because of the Euclidean metric), ergodicity is identical to the previous case. However, for LMC and ILMC, in which the higher-order sensitivities are required to compute the Christoffel symbols, the fact that the sensitivities have been incorrectly specified has not noticeably degraded ergodicity. This is a virtue of the LMC and ILMC Markov chains that they are more robust to human errors of this variety. \section{Conclusion} This work has examined the numerical integrator for Lagrangian Monte Carlo (LMC). Motivated by the observation that LMC requires four Jacobian determinant evaluations, mechanisms by which this number may be reduced were examined. By inverting the sequence of integration so that position, rather than velocity, is updated twice, the number of Jacobian determinant evaluations in each step was reduced from four to two while still maintaining a fully explicit method. Empirical evaluations of this method were provided to show several situations in which the proposed integration strategy enjoys the best time-normalized performance among several alternatives. Moreover, it has been demonstrated in this work that the local error of the Lagrangian leapfrog (and its inverted counterpart) is third order, which improves the previously known order. Additionally, an important robustness property was characterized that LMC possesses and an illustration wherein human error will invalidate stationarity in RMHMC but not in LMC was given. Methods of Bayesian inference that incorporate geometric understanding exhibit a pleasing aesthetic, yet they are burdened by numerical considerations -- among which are fixed points and cubic complexity -- that have limited their adoption. We hope that this research sparks renewed interest in mechanisms of improving these geometric methods. \bigskip \begin{center} {\large\bf SUPPLEMENTARY MATERIAL} \end{center} \section{Involutive Monte Carlo}\label{lagrangian-remarks:app:involutive-monte-carlo} \begin{proof}[Proof of \Cref{lagrangian-remarks:prop:involutive-monte-carlo-detailed-balance}] The detailed balance condition states that for any Borel sets $(A, B), (C, D) \in \mathfrak{B}(\R^m\times\R^m)$ we have, \begin{align} \int_{(A, B)} K((q, p), (C, D)) ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p =\int_{(C, D)} K((q, p), (A, B)) ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p. \end{align} Let $\pi(q, p)$ be the probability density on $\R^m\times\R^m$ that is proportional to $\exp(-H(q, p))$. Using the fact that $\Phi$ is an involution, it suffices to verify \begin{align} &\int_{(A, B)} \alpha((q, p), \Phi(q, p), \abs{\mathrm{det}\paren{\nabla \Phi(x)}}) \mathbf{1}\set{(\tilde{q},\tilde{p})\in (C, D)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{1, \frac{\pi(\Phi(q, p))}{\pi(q, p)} \abs{\mathrm{det}\paren{\nabla \Phi(x)}}} \mathbf{1}\set{\Phi(q, p)\in (C, D)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{\pi(q, p), \pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}} \mathbf{1}\set{\Phi(q, p)\in (C, D)} ~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{\frac{\pi(q, p)}{\pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}}, 1} \mathbf{1}\set{\Phi(q, p)\in (C, D)} \pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{\frac{\pi(q, p)}{\pi(\Phi(q, p))} \abs{\mathrm{det}\paren{\nabla \Phi(\Phi(x))}}, 1} \mathbf{1}\set{\Phi(q, p)\in (C, D)} \pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}~\mathrm{d}q~\mathrm{d}p \\ =& \int_{\Phi(A, B)} \min\set{1, \frac{\pi(\Phi(\tilde{q}, \tilde{p}))}{\pi(\tilde{q}, \tilde{p})} \abs{\mathrm{det}\paren{\nabla \Phi(\tilde{q}, \tilde{p})}}} \mathbf{1}\set{(\tilde{q},\tilde{p})\in (C, D)} ~\pi(\tilde{q}, \tilde{p}) ~\mathrm{d}\tilde{q}~\mathrm{d}\tilde{p} \\ =& \int_{(C, D)} \alpha((q, p), \Phi(q, p), \abs{\mathrm{det}\paren{\nabla \Phi(q, p)}}) \mathbf{1}\set{(q, p)\in \Phi(A, B)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(C, D)} \alpha((q, p), \Phi(q, p), \abs{\mathrm{det}\paren{\nabla \Phi(q, p)}}) \mathbf{1}\set{\Phi(q, p)\in (A, B)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \end{align} Moreover, integrating over the rejection components of the transition kernel already have symmetry in $(A, B)$ and $(C, D)$: \begin{align} &\int_{(A, B)} (1- \alpha((q, p), (\tilde{q}, \tilde{p}), \abs{\mathrm{det}\paren{\nabla \Phi(x)}})) \mathbf{1}\set{(q, p)\in (C, D)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(C, D)} (1- \alpha((q, p), (\tilde{q}, \tilde{p}), \abs{\mathrm{det}\paren{\nabla \Phi(x)}})) \mathbf{1}\set{(q, p)\in (A, B)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p. \end{align} Detailed balance follows as a consequence. \end{proof} \begin{lemma} Let $\Phi_\epsilon : \R^m\times\R^m\to\R^m\times\R^m$ be the Lagrangian leapfrog integrator with step-size $\epsilon\in \R$. Then $\mathbf{F}\circ \Phi_\epsilon$ is an involution. \end{lemma} \begin{proof} Let $(\tilde{q},\tilde{v}) = \Phi_\epsilon(q, v)$. Now we apply the Lagrangian leapfrog to $(\tilde{q},-\tilde{v})$. \begin{align} \breve{v}'' &= (\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, -\tilde{v}))^{-1} \paren{-\tilde{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q})} \\ &= -(\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v}))^{-1} \paren{\tilde{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q})} \\ &= -\breve{v} \end{align} from \cref{lagrangian-remarks:eq:negated-i}. Moreover, \begin{align} \tilde{q}'' &= \tilde{q} + \epsilon \breve{v}'' \\ &= \tilde{q} - \epsilon \breve{v} \\ &= q. \end{align} Finally, \begin{align} \tilde{v}'' &= (\mathrm{Id}_m + \Omega(\epsilon, q, -\breve{v}))^{-1} \paren{-\breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q)} \\ &= -(\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v}))^{-1} \paren{\breve{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q)} \\ &= -v \end{align} from \cref{lagrangian-remarks:eq:negated-ii}. \end{proof} \section{Propagator Matrices for the Leapfrog and Inverted Leapfrog}\label{lagrangian-remarks:app:propagator-matrices} \begin{definition}\label{lagrangian-remarks:def:standard-leapfrog} The {\it generalized leapfrog integrator} for the Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} with Hamiltonian $H(q, p) = U(q) + p^\top p / 2$ is a map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ defined by, \begin{align} \breve{p} &= p - \frac{\epsilon}{2} \nabla U(q) \\ \tilde{q} &= q + \epsilon ~\breve{p} \\ \tilde{p} &= \breve{p} - \frac{\epsilon}{2} \nabla U(\tilde{q}). \end{align} \end{definition} \begin{definition}\label{lagrangian-remarks:def:inverted-leapfrog} The {\it generalized leapfrog integrator} for the Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} with Hamiltonian $H(q, p) = U(q) + p^\top p / 2$ is a map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ defined by, \begin{align} \breve{q} &= q + \frac{\epsilon}{2} p \\ \tilde{p} &= p - \epsilon \nabla U(q) \\ \tilde{q} &= \breve{q} + \frac{\epsilon}{2} \tilde{p}. \end{align} \end{definition} For Hamiltonians of the form $H(q, p) = \omega^2 q^2 / 2 + p^2 / 2$, the action of the leapfrog and inverted leapfrog integrators are linear. This means that there are matrices, called ``propagator matrices,'' which, when acting on the vector $(q, p)\in\R^2$, produce the same position in phase space as the integrators themselves. Computing integer matrix powers of these matrices can then produce the multi-step output of the integrators. In the case of the leapfrog integrator, the propagator matrix is \citep{leimkuhler_reich_2005}, \begin{align} \begin{pmatrix} \tilde{q} \\ \tilde{p} \end{pmatrix} = \underbrace{\begin{pmatrix} 1 - \frac{\epsilon^2\omega^2}{2} & \epsilon \\ \epsilon\omega^2\paren{1 - \frac{\epsilon^2\omega^2}{4}} & 1 - \frac{\epsilon^2\omega^2}{2} \end{pmatrix}}_{\mathbf{R}'} \begin{pmatrix} q \\ p \end{pmatrix}. \end{align} The propagator matrix for the inverted leapfrog is, \begin{align} \begin{pmatrix} \tilde{q} \\ \tilde{p} \end{pmatrix} = \underbrace{\begin{pmatrix} 1 - \frac{\epsilon^2\omega^2}{2} & \epsilon\paren{1 - \frac{\epsilon^2\omega^2}{4}} \\ -\epsilon\omega^2 & 1 - \frac{\epsilon^2\omega^2}{2} \end{pmatrix}}_{\mathbf{R}''} \begin{pmatrix} q \\ p \end{pmatrix}. \end{align} At stationarity, \begin{align} \begin{pmatrix} q \\ p \end{pmatrix} \sim \mathrm{Normal}\paren{\begin{pmatrix} 0 \\ 0 \end{pmatrix}, \begin{pmatrix} 1 / \omega^2 & 0 \\ 0 & 1 \end{pmatrix}}. \end{align} Therefore, for an integrator with propagator matrix $\mathbf{R}$, the distribution of the $k$-step transition is, \begin{align} \mathrm{Normal}\paren{\begin{pmatrix} 0 \\ 0 \end{pmatrix}, \mathbf{R}^k\begin{pmatrix} 1 / \omega^2 & 0 \\ 0 & 1 \end{pmatrix} (\mathbf{R}^k)^\top}, \end{align} \section{Algorithms}\label{app:algorithms} \input{algorithms/generalized-leapfrog} \input{algorithms/lagrangian-leapfrog} \input{algorithms/hmc} \input{algorithms/inverted-lagrangian-leapfrog} In this appendix we give pseudo-code implementations of algorithms featured in this work. In \cref{lagrangian-remarks:alg:generalized-leapfrog} we show the generalized leapfrog, which contrasts with the Lagrangian leapfrog in \cref{lagrangian-remarks:alg:lagrangian-leapfrog} in the presence of implicitly-defined integration steps. \Cref{lagrangian-remarks:alg:inverted-lagrangian-leapfrog} shows the Lagrangian integrator but with an inverted sequence of integration (updating position before velocity). In \cref{lagrangian-remarks:alg:hmc} we show an algorithmic implementation of a single-step of the Hamiltonian Monte Carlo Markov chain, which can be carried out using any of the integrators considered in this work. \section{Proofs Concerning Mechanics Systems}\label{lagrangian-remarks:app:proofs-concerning-mechanics} We give a proof of \cref{lagrangian-remarks:thm:hamiltonian-mechanics}. \begin{proof} We first show that the Hamiltonian energy is conserved. \begin{align} \frac{\mathrm{d}}{\mathrm{d}t} H(q_t, p_t) &= \nabla_q H(q_t, p_t) \cdot v_t + \nabla_p H(q_t, p_t) \cdot \dot{p}_t \\ &= \nabla_q H(q_t, p_t) \cdot \nabla_p H(q_t, p_t) - \nabla_p H(q_t, p_t) \cdot \nabla_q H(q_t, p_t) \\ &= 0. \end{align} Next we show that Hamiltonian mechanics conserve volume in $(q, p)$-space. This is equivalent to the vector field $(v_t, \dot{p}_t)$ having zero divergence, which we now verify. \begin{align} \mathrm{div}(v_t, \dot{p}_t) &= \nabla_q \cdot v_t + \nabla_p \cdot \dot{p}_t \\ &= \nabla_q \cdot \nabla_p H(q_t, p_t) - \nabla_p \cdot \nabla_q H(q_t, p_t) \\ &= \sum_{i=1}^m \frac{\partial^2 H}{\partial q_i \partial p_i} H(q_t, p_t) - \sum_{i=1}^m \frac{\partial^2 H}{\partial p_i \partial q_i} H(q_t, p_t) \\ &= 0, \end{align} by symmetry of partial derivatives. Finally we show that under the conditions that $\nabla_q H(q, -p) = \nabla_q H(q, p)$ and $\nabla_p H(q, -p) = -\nabla_p H(q, p)$ that the equations of motion are reversible under negation of the momentum variable. To see this, fix $\tau \in \R_+$ and consider $(q_t, p_t)$ satisfying \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} for $t\in [0, \tau]$. Let $\tilde{p}_t = -p_{\tau-t}$ and $\tilde{q}_t = q_{\tau-t}$. We find that $\tilde{q}_t$ and $\tilde{p}_t$ obey the following equations of motion: \begin{align} \frac{\mathrm{d}}{\mathrm{d}t} \tilde{q}_t &= -v_{\tau-t} \\ &= -\nabla_p H(q_{\tau-t}, p_{\tau-t}) \\ &= \nabla_p H(\tilde{q}_t, -p_{\tau-t}) \\ &= \nabla_p H(\tilde{q}_t, \tilde{p}_{t}) \\ \frac{\mathrm{d}}{\mathrm{d}t} \tilde{p}_t &= \dot{p}_{\tau-t} \\ &= -\nabla_q H(q_{\tau-t}, p_{\tau-t}) \\ &= -\nabla_q H(q_{\tau-t}, -p_{\tau-t}) \\ &= -\nabla_q H(\tilde{q}_t, \tilde{p}_t). \end{align} Thus we see that $(\tilde{q}_t, \tilde{p}_t)$ are also solutions to Hamilton's equations of motion and satisfy $\tilde{q}_\tau = q_0$ and $\tilde{p}_\tau = -p_0$, demonstrating reversibility. \end{proof} \section{Proofs Concerning the Numerical Order of the Lagrangian Integrators}\label{lagrangian-remarks:app:proofs-concerning-numerical-order} The claim of first order accuracy was derived in \citet{lan2015}; we have included a proof for completeness. \begin{proof}[Proof of \cref{lagrangian-remarks:lem:second-order-local-error}] Let $q_t$ and $v_t$ be solutions to the initial value problem, \begin{align} \dot{q}_t &= v_t \\ \dot{v}_t &= -\Omega(2, q_t, v_t) v_t - \mathbf{G}^{-1}(q_t) \nabla U(q_t). \end{align} Given the initial value $q_0 = q$ and $v_0 = v$, we can expand the solution in a Taylor series about $t=0$. \begin{align} q_t &= q_0 + t \dot{q}_0 + \mathcal{O}(t^2) \\ &= q + t v + \mathcal{O}(t^2) \\ v_t &= v_0 - t \paren{\Omega(2, q_0, v_0) v_0 - \mathbf{G}^{-1}(q_0) \nabla U(q_0)} + \mathcal{O}(t^2) \\ &= v - \Omega(2t, q, v) v - t \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(t^2). \end{align} Letting $t=\epsilon$ gives the following approximations, \begin{align} q_{\epsilon} &= q + \epsilon v + \mathcal{O}(\epsilon^2) \\ v_{\epsilon} &= v - \Omega(2\epsilon, q, v) v - \epsilon \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \end{align} Now we expand the steps of the explicit numerical integrator. We begin with the first update to velocity. \begin{align} \breve{v} &= \paren{\mathrm{Id}_m + \Omega(\epsilon, q, v)}^{-1} \paren{v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)} \\ &= \paren{\mathrm{Id}_m - \Omega(\epsilon, q, v) + \mathcal{O}(\epsilon^2)}\paren{v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)} \\ &= v - \Omega(\epsilon, q, v) v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \end{align} Now we expand the update to position. \begin{align} \tilde{q} &= q + \epsilon \breve{v} \\ &= q + \epsilon v + \mathcal{O}(\epsilon^2) \end{align} We conclude by expanding the second update to velocity in terms of the initial conditions. \begin{align} \tilde{v} &= \paren{\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, \breve{v})}^{-1} \paren{\breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q})\nabla U(\tilde{q})} \\ &= \breve{v} - \Omega(\epsilon, \tilde{q}, \breve{v}) \breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q}) + \mathcal{O}(\epsilon^2) \\ &= \breve{v} - \Omega(\epsilon, q, v) v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \\ &= v - \Omega(2\epsilon, q, v) v - \epsilon \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2). \end{align} Therefore, a single step of the numerical integrator with step-size $\epsilon$ agrees with the analytical solution to the initial value problem (from the same initial condition) to at least first order in $\epsilon$. \end{proof} \begin{proof}[Proof of \Cref{lagrangian-remarks:lem:inverted-lagrangian-properties}] To demonstrate that the inverted integrator has at least first-order error, we expand the steps of the integrator as follows. First, \begin{align} \breve{q} &= q + \frac{\epsilon}{2} ~v \\ \tilde{v} &= \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, v)}^{-1} \paren{v - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ &= \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, v)} \paren{v - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} + \mathcal{O}(\epsilon^2) \\ &= v - \Omega(2\epsilon, q, v) v - \epsilon \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \\ \tilde{q} &= \breve{q} + \frac{\epsilon}{2} \tilde{v} \\ &= q + \frac{\epsilon}{2} ~v + \frac{\epsilon}{2} ~v + \mathcal{O}(\epsilon^2) \\ &= q + \epsilon ~v. \end{align} This verifies that the inverted Lagrangian leapfrog has at least first order accuracy. In order to show that the inverted leapfrog integrator is symmetric, we proceed as follows. Recall that the three steps of the inverted Lagrangian leapfrog are \begin{align} \breve{q} &= q + \frac{\epsilon}{2} ~v \\ \tilde{v} &= \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, v)}^{-1} \paren{v - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ \tilde{q} &= \breve{q} + \frac{\epsilon}{2} ~\tilde{v}. \end{align} Therefore, we consider integrating from initial position $(\tilde{q},\tilde{v})$ with a negated step-size $-\epsilon$ as follows: \begin{align} \breve{q}' &= \tilde{q} - \frac{\epsilon}{2} ~\tilde{v} \\ &= \breve{q} \end{align} For the velocity we have, \begin{align} & \tilde{v}' = \paren{\mathrm{Id}_m - \Omega(2\epsilon, \breve{q}, \tilde{v})}^{-1} \paren{\tilde{v} + \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ \implies& \paren{\mathrm{Id}_m - \Omega(2\epsilon, \breve{q}, \tilde{v})} \tilde{v}' = \tilde{v} + \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q}) \\ \implies& \tilde{v} + \Omega(2\epsilon, \breve{q}, \tilde{v}')\tilde{v} = \tilde{v}' - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q}) \\ \implies& \tilde{v} = \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, \tilde{v}'}^{-1} \paren{\tilde{v}' - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ \implies \tilde{v}' = v \end{align} Finally, the last update to the position is, \begin{align} \tilde{q}' &= \breve{q} - \frac{\epsilon}{2} v \\ &= q. \end{align} Hence we see that the inverted Lagrangian leapfrog is also self-adjoint. As noted in the main text, the combination of self-adjointness and at least first-order accuracy immediately imply second-order accuracy. \end{proof} \begin{proof}[Proof of \cref{lagrangian-remarks:lem:self-adjoint}] Self-adjointness of a numerical integrator follows immediately from the condition $\Phi_{-\epsilon}\circ \Phi_{\epsilon} = \mathrm{Id}$. Therefore, to demonstrate that a numerical method is self-adjoint it suffices to establish this condition. Consider the first update to the velocity: \begin{align} &\breve{v} = \paren{\mathrm{Id}_m + \Omega(\epsilon, q, v)}^{-1}\paren{v - \frac{\epsilon}{2} \mathbf{G}(q)^{-1}\nabla U(q)} \\ \iff& \breve{v} + \Omega(\epsilon, q, v) \breve{v} = v - \frac{\epsilon}{2} \mathbf{G}(q)^{-1} \nabla U(q) \\ \iff & \breve{v} + \frac{\epsilon}{2} \mathbf{G}(q)^{-1} \nabla U(q) = v - \Omega(\epsilon, q, \breve{v}) v \\ \iff & \breve{v} + \frac{\epsilon}{2} \mathbf{G}(q)^{-1} \nabla U(q) = \paren{\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v})} v \\ \iff & v = \paren{\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v})}^{-1}\paren{\breve{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)}. \end{align} An identical series of computations reveals, \begin{align} \breve{v} = \paren{\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v})}^{-1}\paren{\tilde{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q})\nabla U(\tilde{q})}. \end{align} Hence, applying $\Phi_{-\epsilon}$ to $(\tilde{q}, \tilde{v})$ yields the following series of updates, \begin{align} \label{lagrangian-remarks:eq:negated-i} \breve{v}' &= \paren{\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v})}^{-1}\paren{\tilde{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q})\nabla U(\tilde{q})} \\ &= \breve{v} \\ q' &= \tilde{q} - \epsilon \breve{v}' \\ &= \tilde{q} - \epsilon \breve{v} \\ &= q \\ \label{lagrangian-remarks:eq:negated-ii} v' &= \paren{\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v})}^{-1}\paren{\breve{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)} \\ &= v. \end{align} Hence we return to the initial condition $(q, v)$. This verifies that the explicit integrator employed in LMC is self-adjoint. \end{proof} \begin{proof}[Proof of \Cref{lagrangian-remarks:prop:composition-order}] Since $\hat{\Phi}_\epsilon$ is $p$-th order accurate for $\Phi_\epsilon$ we have, by Taylor series expansion, that, \begin{align} \label{eq:2021-12-19-taylor-i} \hat{\Phi}_0 &= \Phi_0 \\ \label{eq:2021-12-19-taylor-ii} \frac{\mathrm{d}^k}{\mathrm{d}\epsilon^k} \hat{\Phi}_\epsilon(z_0) \bigg|_{\epsilon=0} &= \frac{\mathrm{d}^k}{\mathrm{d}\epsilon^k} \Phi_\epsilon(z_0) \bigg|_{\epsilon=0}, \end{align} for $k=1,\ldots, p$. Let $f : \R\to\R^m$, then the Taylor series of expansion of $\Xi\circ f(\epsilon)$ is, \begin{align} \label{eq:2021-12-19-taylor-composition} \Xi \circ f(\epsilon) &= \Xi\circ f(0) + \sum_{k=1}^p \epsilon^k g^{[k]}\paren{f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0), \ldots, \frac{\mathrm{d}^k}{\mathrm{d}\epsilon^k} f(0)} + \mathcal{O}(\epsilon^{p+1}), \end{align} where $g^{[k]}$ are functions determining the Taylor series coefficients which depend on the derivatives of $f$. For instance, \begin{align} g^{[1]}\paren{f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0)} &= \nabla \Xi(f(0)) \cdot \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0) \\ g^{[2]}\paren{f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0), \frac{\mathrm{d}^2}{\mathrm{d}\epsilon^2} f(0)} &= \nabla^2 \Xi(f(0))\paren{\frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0)} + \nabla\Xi(f(0)) \cdot \frac{\mathrm{d}^2}{\mathrm{d}\epsilon^2} f(0). \end{align} By the equality of the Taylor series expansion coefficients in \cref{eq:2021-12-19-taylor-i,eq:2021-12-19-taylor-ii} it follows from \cref{eq:2021-12-19-taylor-composition} that, \begin{align} \Xi\circ\Phi_\epsilon(z_0) - \Xi\circ\hat{\Phi}_\epsilon(z_0) = \mathcal{O}(\epsilon^{p+1}). \end{align} This proves that $\Xi\circ\hat{\Phi}_\epsilon$ is also $p$-th order accurate for $\Xi\circ\Phi_\epsilon$. \end{proof} \section{Expanded Preliminaries} \subsection{Hamiltonian and Lagrangian Mechanics}\label{lagrangian-remarks:subsec:hamiltonian-lagrangian-mechanics} \begin{definition}\label{lagrangian-remarks:def:hamiltonian-mechanics} Let $H : \R^m\times\R^m\to\R$ be a smooth function, which we call the Hamiltonian. Hamilton's equations of motion are defined as the solutions to the initial value problem \begin{align} \label{lagrangian-remarks:eq:hamiltonian-position} v_t &= \nabla_p H(q_t, p_t) \\ \label{lagrangian-remarks:eq:hamiltonian-momentum} \dot{p}_t &= -\nabla_q H(q_t, p_t), \end{align} with $(q_0, p_0)$ a given initial position in phase space. \end{definition} \Cref{lagrangian-remarks:def:hamiltonian-mechanics} gives us a system of coupled first-order differential equations. Hamilton's equations of motion exhibit several key properties \citep{mechanics-and-symmetry}, which we summarize. \begin{theorem}\label{lagrangian-remarks:thm:hamiltonian-mechanics} The Hamiltonian mechanics given in \cref{lagrangian-remarks:def:hamiltonian-mechanics} possess the following three properties: \begin{enumerate} \item They preserve the Hamiltonian $\frac{\mathrm{d}}{\mathrm{d}t} H(q_t, p_t) = 0$. \item Denoting $\dot{z}_t = (v_t,\dot{p}_t)$ the equations of motion in phase space, Hamiltonian mechanics preserve volume in phase space: $\mathrm{div}(\dot{z}_t) = 0$. \item Under the conditions that $\nabla_q H(q, -p) = \nabla_q H(q, p)$ and $-\nabla_p H(q,p)= \nabla_pH(q, -p)$, the equations of motion are reversible via negation of the momentum variable. \end{enumerate} \end{theorem} A proof is given in \cref{lagrangian-remarks:app:proofs-concerning-mechanics}. In the special case when $U(q) = 0$ in \cref{lagrangian-remarks:eq:hamiltonian-form} for all $q\in\R^m$, Hamilton's equations of motion produce geodesic motion on the Riemannian manifold $(\R^m, \mathbf{G})$, where $\mathbf{G}$ assumes the role of the Riemannian metric \citep{Calin2004GeometricMO}. \begin{definition} Given a Riemannian Hamiltonian (\cref{lagrangian-remarks:def:riemannian-hamiltonian}), define the associated {\it Lagrangian} function by, \begin{align} \label{lagrangian-remarks:eq:lagrangian-form} L(q, v) &= \tilde{K}(q, v) - U(q), \end{align} where $\tilde{K}(q, v) = \frac{1}{2}v^\top \mathbf{G}(q) v$. \end{definition} Hamiltonian mechanics are related to Lagrangian dynamics by the Legendre transform which converts between momentum and velocity \citep{marsden_west_2001}. \begin{definition}\label{lagrangian-remarks:def:legendre-transform} Let $L : \R^m\times\R^m\to\R$ be a Lagrangian of the form in \cref{lagrangian-remarks:eq:lagrangian-form}. The {\it Legendre transform} relates the momentum and velocity according to $p = \frac{\partial L}{\partial v}(q, v) = \mathbf{G}(q) v$. \end{definition} \begin{definition}\label{lagrangian-remarks:def:inverse-legendre-transform} Let $H:\R^m\times\R^m\to\R$ be a Hamiltonian of the form in \cref{lagrangian-remarks:eq:hamiltonian-form}. The {\it inverse Legendre transform} relates velocity and momentum according to $v = \frac{\partial H}{\partial p}(q, p) = \mathbf{G}^{-1}(q)p$. \end{definition} The Lagrangian then determines equations of motion in accordance with the following physical principle. \begin{definition}\label{lagrangian-remarks:def:hamiltons-principle} {\it Hamilton's principle} states that the equations of motion $(q_t, v_t)$ over an interval of time $[a, b]$, with known boundary conditions $q_a$ and $q_b$, are solutions of the variational equation \begin{align} \frac{\delta \mathcal{S}[q_t]}{\delta q_t} = 0 \end{align} where \begin{align} \mathcal{S}[q_t] = \int_a^b L(q_t, v_t) ~\mathrm{d}t \end{align} where $q_t$ and $v_t$ are related by $v_t = \frac{\mathrm{d}}{\mathrm{d}t} q_t$. \end{definition} Hamilton's principle states that equations of motion (as specified by $q$ and $v$) should {\it extremize} the Lagrangian subject to the boundary conditions on $q_a$ and $q_b$. \begin{theorem}\label{lagrangian-remarks:thm:euler-lagrange} Under Hamilton's principle (\cref{lagrangian-remarks:def:hamiltons-principle}), the equations of motion $(q_t, v_t)$ must be solutions of the {\it Euler-Lagrange equation} \begin{align} \nabla_q L(q_t, v_t) = \frac{\mathrm{d}}{\mathrm{d}t} \nabla_{v} L(q_t, v_t). \end{align} \end{theorem} The equations of motion from \cref{lagrangian-remarks:thm:euler-lagrange} (or \cref{lagrangian-remarks:def:hamiltons-principle}) are, in fact, equivalent to the motion produced under Hamiltonian mechanics in \cref{lagrangian-remarks:def:hamiltonian-mechanics} \citep{mechanics-and-symmetry}. For Lagrangians of the form in \cref{lagrangian-remarks:eq:lagrangian-form}, the $k$-th element of the acceleration is, \begin{align} \label{lagrangian-remarks:eq:lagrangian-acceleration} a_t^{(k)} = -\sum_{i=1}^m\sum_{j=1}^m \Gamma^k_{ij}(q_t) v_t^{(i)} v_t^{(j)} - \sum_{l=1}^m \mathbf{G}^{-1}_{kl}(q_t) \frac{\partial U}{\partial q^{(l)}} (q_t), \end{align} where $\Gamma^k_{ij}$ are the Christoffel symbols (\cref{lagrangian-remarks:def:christoffel-symbols}). We conclude this section by noting that $\Omega$ in \cref{lagrangian-remarks:eq:omega} enjoys the following properties: \begin{proposition}\label{lagrangian-remarks:prop:omega-properties} The function $\Omega : \R\times\R^m\times\R^m\to\R^{m\times m}$ in \cref{lagrangian-remarks:eq:omega} satisfies \begin{align} \label{lagrangian-remarks:eq:omega-symmetry} \Omega(\epsilon, q, v)\breve{v} &= \Omega(\epsilon, q, \breve{v}) v \\ \label{lagrangian-remarks:eq:omega-derivative} \frac{\partial}{\partial v} (\Omega(\epsilon, q, v)\breve{v}) &= \Omega(\epsilon, q, \breve{v}). \end{align} \end{proposition} \begin{proof} The result in \cref{lagrangian-remarks:eq:omega-symmetry} can be seen from \begin{align} (\Omega(\epsilon, q, v)\breve{v})_i &= \frac{\epsilon}{2} \sum_{j=1}^m \sum_{k=1}^m \Gamma^i_{kj}(q) v^{(k)} \breve{v}^{(j)} \\ &= \frac{\epsilon}{2} \sum_{j=1}^m \sum_{k=1}^m \Gamma^i_{jk}(q) v^{(k)} \breve{v}^{(j)} \\ &= \frac{\epsilon}{2} \sum_{k=1}^m \sum_{j=1}^m \Gamma^i_{jk}(q) v^{(k)} \breve{v}^{(j)} \\ &= (\Omega(\epsilon, q, \breve{v})v)_i. \end{align} \Cref{lagrangian-remarks:eq:omega-derivative} then follows as an immediate corollary. \end{proof} Like Hamiltonian mechanics, Lagrangian dynamics conserve the Hamiltonian (when $p_t = \mathbf{G}(q_t) v_t$) and are reversible. However, Lagrangian dynamics do not conserve volume in $(q, v)$-space. \subsection{Background on Numerical Integrators}\label{lagrangian-remarks:subsec:numerical-integrators} The Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} and the Lagrangian motion described in \cref{lagrangian-remarks:eq:lagrangian-acceleration} rarely have closed-form solutions. Therefore, it is necessary to investigate methods of numerical integration to produce approximate solutions to these initial value problems. In the following section, we review key ideas from \citet{Hairer:1250576}. \begin{definition}\label{lagrangian-remarks:def:initial-value-problem} Let $g : \R^m\to\R^m$. {\it The solution to an initial value problem} is a function $z_{(\cdot)} : \R\to\R^m$ for which $\frac{\mathrm{d}}{\mathrm{d}t} z_t = g(z_t)$ and for which the {\it initial value} $z_0\in\R^m$ is known. In this case $g$ is called a {\it (time-homogenous) vector field}. \end{definition} \begin{definition}\label{lagrangian-remarks:def:integrator-order} Let $z_t$ be the solution to an initial value problem (\cref{lagrangian-remarks:def:initial-value-problem}) with initial value $z_0$. A {\it numerical integrator with step-size $\epsilon$} is a mapping $\Phi_{\epsilon} : \R^m\to\R^m$ and is said to have order $p$ if $\Vert \Phi_{\epsilon}(z_0) - z_{\epsilon}\Vert = \mathcal{O}(\epsilon^{p+1})$. \end{definition} \begin{definition}\label{lagrangian-remarks:def:self-adjoint} The adjoint of a numerical method $\Phi_\epsilon : \R^m \to\R^m$ is defined by the relation $\Phi_\epsilon^*(z) = \Phi^{-1}_{-\epsilon}(z)$. The numerical method $\Phi_\epsilon$ is said to be self-adjoint if $\Phi^*_\epsilon = \Phi_\epsilon$. \end{definition} \begin{theorem}[\citet{Hairer:1250576}]\label{lagrangian-remarks:thm:self-adjoint-even-order} Consider an initial value problem $\dot{z}_t = g(z_t)$ with initial condition $z_0 \in \R^m$. Let $\Phi_\epsilon$ be a one-step numerical integrator of (maximal) order $r\in\mathbb{N}$. If $\Phi_\epsilon$ is self-adjoint, then $r$ is even. \end{theorem} \begin{proposition}\label{lagrangian-remarks:prop:composition-order} Let $g : \R^m\to\R^m$ be a time-homogenous vector field. Let $\Xi:\R^m\to\R^m$ be a diffeomorphism. Let $z_t$ be the solution to the initial value problem $\dot{z}_t = g(z_t)$ given $z_0$. Let $\Phi_\epsilon : \R^m\to\R^m$ be the flow map of $z_\epsilon$ and suppose that $\hat{\Phi}_\epsilon$ is a $p$-th order approximation of $\Phi_\epsilon$. Then $\Xi\circ \hat{\Phi}_\epsilon$ is a $p$-th order approximation of $\Xi\circ \Phi_\epsilon$. \end{proposition} A proof is given in \cref{lagrangian-remarks:app:proofs-concerning-numerical-order}. \begin{proposition} The generalized leapfrog integrator is a second-order (\cref{lagrangian-remarks:def:integrator-order}), self-adjoint (\cref{lagrangian-remarks:def:self-adjoint}) numerical method. \end{proposition} \subsection{Hamiltonian and Lagrangian Monte Carlo}\label{lagrangian-remarks:subsec:hamiltonian-lagrangian-monte-carlo} Our objective in Bayesian inference is to draw samples from the distribution whose density is $\pi(q) \propto \exp(\mathcal{L}(q))$. We now review basic concepts from Markov chain Monte Carlo. \begin{definition} A {\it Markov chain transition kernel} is a map $K : \R^m\times\mathfrak{B}(\R^m) \to [0,1]$ satisfying (i) for every $x\in \R^m$ the map $A\mapsto K(x, A)$ is a probability measure and (ii) for every $A \in\mathfrak{B}(\R^m)$, the map $x\mapsto K(x, A)$ is measurable. Given a Markov chain transition kernel $K$, a {\it Markov chain} is defined inductively by $x_{n+1} \vert x_n \sim K(x_n, \cdot)$. \end{definition} HMC accomplishes this by artificially expanding the distribution to incorporate a momentum variable. Defining $U(q) = -\mathcal{L}(q) + \frac{1}{2} \log\mathrm{det}(\mathbf{G}(q))$, let $H(q, p)$ be the Hamiltonian given in \cref{lagrangian-remarks:eq:hamiltonian-form} and observe that the density $\pi(q, p) \propto \exp(-H(q, p))$ has $\pi(q) = \int_{\R^m} \pi(q, p) ~\mathrm{d}p$ and $p \vert q \sim\mathrm{Normal}(0, \mathbf{G}(q))$. In order to unify methods of Bayesian inference based on either the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}) or the Lagrangian leapfrog (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) under one framework, we now introduce the Markov chain transition kernel based on smooth involutions. \begin{definition}[\citet{DBLP:conf/icml/NeklyudovWEV20}]\label{lagrangian-remarks:def:involutive-monte-carlo} Let $\Phi : \R^m\times\R^m\to\R^m\times\R^m$ be a smooth involution (i.e. $\Phi=\Phi^{-1}$). Let $\pi:\R^m\times\R^m\to\R_+$ be a probability density with respect to Lebesgue measure. Then we define the Markov chain transition kernel of {\it involutive Monte Carlo} by \begin{align} \begin{split} K((q, p), (A, B)) &= \alpha((q, p), (\tilde{q},\tilde{p}), J)~\mathbf{1}\set{(\tilde{q}, \tilde{p})\in (A, B)} \\ &\qquad + \paren{1-\alpha((q, p), (\tilde{q},\tilde{p}), J)} ~\mathbf{1}\set{(q, p)\in (A, B)} \end{split} \\ \label{lagrangian-remarks:eq:acceptance-probability} \alpha((q, p), (\tilde{q}, \tilde{p}), J) &= \min\set{1, \frac{\exp(-H(\tilde{q}, \tilde{p}))}{\exp(-H(q, p))}\cdot J} \\ J &= \abs{\mathrm{det}\paren{\frac{\partial (\tilde{q}, \tilde{p})}{\partial (q, p)}}}, \end{align} where $(A, B)\in\mathfrak{B}(\R^m\times\R^m)$ and $(\tilde{q}, \tilde{p}) = \Phi(q, p)$. \end{definition} \begin{proposition}\label{lagrangian-remarks:prop:involutive-monte-carlo-detailed-balance} The Markov chain transition kernel of involutive Monte Carlo satisfies detailed balance with respect to the distribution whose density is $\pi(q, p)\propto \exp(-H(q, p))$. \end{proposition} A proof is provided in \cref{lagrangian-remarks:app:involutive-monte-carlo}. Central to the construction of involutions of interest to us is the momentum flip operator, defined as follows. \begin{definition}\label{lagrangian-remarks:def:momentum-flip} The {\it momentum flip operator} is the map $\mathbf{F}(q, p) = (q, -p)$. \end{definition} The fact that numerical integrators can be combined with the momentum flip operator in order to produce involutions is covered in \cref{lagrangian-remarks:app:involutive-monte-carlo} in the case of the Lagrangian leapfrog; other integrators are handled similarly. We provide pseudo-code implementing a single step of involutive Monte Carlo in \cref{lagrangian-remarks:alg:hmc} with involutions provided by the generalized leapfrog or Lagrangian leapfrog integrator. Given an initial point $(q_0, p_0)$ in phase space drawn from the distribution $\pi(q, p)$, the sequence of states $((q_1,p_1), (q_2, p_2), \ldots)$ computed by \cref{lagrangian-remarks:alg:hmc} are guaranteed to have $\pi(q, p)$ as their marginal distributions. Under the additional conditions that the HMC Markov chain is irreducible and aperiodic, HMC also produces an ergodic chain. The generalized leapfrog integrator is volume preserving. However, the integrator of Lagrangian dynamics is not. The required change-of-volume can be deduced as follows. First, observe that the update \cref{lagrangian-remarks:eq:lagrangian-position-update} is immediately volume-preserving since it is merely the translation of the position variable by a quantity. The change of volume incurred in \cref{lagrangian-remarks:eq:lagrangian-velocity-i} has a Jacobian determinant given by, \begin{align} \abs{\mathrm{det}\paren{\frac{\partial (q, \breve{v})}{\partial (q, v)}}} = \abs{\frac{\mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v}))}{\mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, q, v))}}. \end{align} The update in \cref{lagrangian-remarks:eq:lagrangian-velocity-ii} incurs a similar change of volume. Thus, when employing \cref{lagrangian-remarks:alg:lagrangian-leapfrog}, the Jacobian determinant of the transformation $(q, p)\mapsto (\tilde{q}, \tilde{p})$ is, \begin{align} \begin{split} \label{lagrangian-remarks:eq:lagrangian-jacobian-determinant} &\abs{\mathrm{det}\paren{\frac{\partial (\tilde{q}, \tilde{p})}{\partial (q, p)}}} = \mathrm{det}(\mathbf{G}^{-1}(q))\mathrm{det}(\mathbf{G}(\tilde{q})) ~\times \\ &\qquad \abs{\frac{\mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v})) \mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v}))}{\mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, \breve{v})) \mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, q, v))}}. \end{split} \end{align} \begin{definition}\label{lagrangian-remarks:def:rmhmc} Let $\Phi_\epsilon$ be the generalized leapfrog integrator with step-size $\epsilon\in\R$ (\cref{lagrangian-remarks:def:generalized-leapfrog}). Let $k\in\mathbb{N}$ be a number of integration steps. The {\it Riemannian manifold Hamiltonian Monte Carlo (RMHMC) Markov chain} is an instance involutive Monte Carlo (\cref{lagrangian-remarks:def:involutive-monte-carlo}) with involution $\mathbf{F} \circ \Phi_{\epsilon}^k$. \end{definition} \begin{definition}\label{lagrangian-remarks:def:lmc} Let $\Phi_\epsilon$ be the Lagrangian leapfrog integrator with step-size $\epsilon\in\R$ (\cref{lagrangian-remarks:def:lagrangian-leapfrog}). Let $k\in\mathbb{N}$ be a number of integration steps. The {\it Lagrangian Monte Carlo (LMC) Markov chain} is an instance involutive Monte Carlo (\cref{lagrangian-remarks:def:involutive-monte-carlo}) with involution $\mathbf{F} \circ \Phi_{\epsilon}^k$. \end{definition} \section{Involutive Monte Carlo}\label{lagrangian-remarks:app:involutive-monte-carlo} \begin{proof}[Proof of \Cref{lagrangian-remarks:prop:involutive-monte-carlo-detailed-balance}] The detailed balance condition states that for any Borel sets $(A, B), (C, D) \in \mathfrak{B}(\R^m\times\R^m)$ we have, \begin{align} \int_{(A, B)} K((q, p), (C, D)) ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p =\int_{(C, D)} K((q, p), (A, B)) ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p. \end{align} Let $\pi(q, p)$ be the probability density on $\R^m\times\R^m$ that is proportional to $\exp(-H(q, p))$. Using the fact that $\Phi$ is an involution, it suffices to verify \begin{align} &\int_{(A, B)} \alpha((q, p), \Phi(q, p), \abs{\mathrm{det}\paren{\nabla \Phi(x)}}) \mathbf{1}\set{(\tilde{q},\tilde{p})\in (C, D)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{1, \frac{\pi(\Phi(q, p))}{\pi(q, p)} \abs{\mathrm{det}\paren{\nabla \Phi(x)}}} \mathbf{1}\set{\Phi(q, p)\in (C, D)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{\pi(q, p), \pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}} \mathbf{1}\set{\Phi(q, p)\in (C, D)} ~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{\frac{\pi(q, p)}{\pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}}, 1} \mathbf{1}\set{\Phi(q, p)\in (C, D)} \pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(A, B)} \min\set{\frac{\pi(q, p)}{\pi(\Phi(q, p))} \abs{\mathrm{det}\paren{\nabla \Phi(\Phi(x))}}, 1} \mathbf{1}\set{\Phi(q, p)\in (C, D)} \pi(\Phi(q, p)) \abs{\mathrm{det}\paren{\nabla \Phi(x)}}~\mathrm{d}q~\mathrm{d}p \\ =& \int_{\Phi(A, B)} \min\set{1, \frac{\pi(\Phi(\tilde{q}, \tilde{p}))}{\pi(\tilde{q}, \tilde{p})} \abs{\mathrm{det}\paren{\nabla \Phi(\tilde{q}, \tilde{p})}}} \mathbf{1}\set{(\tilde{q},\tilde{p})\in (C, D)} ~\pi(\tilde{q}, \tilde{p}) ~\mathrm{d}\tilde{q}~\mathrm{d}\tilde{p} \\ =& \int_{(C, D)} \alpha((q, p), \Phi(q, p), \abs{\mathrm{det}\paren{\nabla \Phi(q, p)}}) \mathbf{1}\set{(q, p)\in \Phi(A, B)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(C, D)} \alpha((q, p), \Phi(q, p), \abs{\mathrm{det}\paren{\nabla \Phi(q, p)}}) \mathbf{1}\set{\Phi(q, p)\in (A, B)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \end{align} Moreover, integrating over the rejection components of the transition kernel already have symmetry in $(A, B)$ and $(C, D)$: \begin{align} &\int_{(A, B)} (1- \alpha((q, p), (\tilde{q}, \tilde{p}), \abs{\mathrm{det}\paren{\nabla \Phi(x)}})) \mathbf{1}\set{(q, p)\in (C, D)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p \\ =& \int_{(C, D)} (1- \alpha((q, p), (\tilde{q}, \tilde{p}), \abs{\mathrm{det}\paren{\nabla \Phi(x)}})) \mathbf{1}\set{(q, p)\in (A, B)} ~\pi(q, p)~\mathrm{d}q~\mathrm{d}p. \end{align} Detailed balance follows as a consequence. \end{proof} \begin{lemma} Let $\Phi_\epsilon : \R^m\times\R^m\to\R^m\times\R^m$ be the Lagrangian leapfrog integrator with step-size $\epsilon\in \R$. Then $\mathbf{F}\circ \Phi_\epsilon$ is an involution. \end{lemma} \begin{proof} Let $(\tilde{q},\tilde{v}) = \Phi_\epsilon(q, v)$. Now we apply the Lagrangian leapfrog to $(\tilde{q},-\tilde{v})$. \begin{align} \breve{v}'' &= (\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, -\tilde{v}))^{-1} \paren{-\tilde{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q})} \\ &= -(\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v}))^{-1} \paren{\tilde{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q})} \\ &= -\breve{v} \end{align} from \cref{lagrangian-remarks:eq:negated-i}. Moreover, \begin{align} \tilde{q}'' &= \tilde{q} + \epsilon \breve{v}'' \\ &= \tilde{q} - \epsilon \breve{v} \\ &= q. \end{align} Finally, \begin{align} \tilde{v}'' &= (\mathrm{Id}_m + \Omega(\epsilon, q, -\breve{v}))^{-1} \paren{-\breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q)} \\ &= -(\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v}))^{-1} \paren{\breve{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q)} \\ &= -v \end{align} from \cref{lagrangian-remarks:eq:negated-ii}. \end{proof} \section{Propagator Matrices for the Leapfrog and Inverted Leapfrog}\label{lagrangian-remarks:app:propagator-matrices} \begin{definition}\label{lagrangian-remarks:def:standard-leapfrog} The {\it generalized leapfrog integrator} for the Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} with Hamiltonian $H(q, p) = U(q) + p^\top p / 2$ is a map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ defined by, \begin{align} \breve{p} &= p - \frac{\epsilon}{2} \nabla U(q) \\ \tilde{q} &= q + \epsilon ~\breve{p} \\ \tilde{p} &= \breve{p} - \frac{\epsilon}{2} \nabla U(\tilde{q}). \end{align} \end{definition} \begin{definition}\label{lagrangian-remarks:def:inverted-leapfrog} The {\it generalized leapfrog integrator} for the Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} with Hamiltonian $H(q, p) = U(q) + p^\top p / 2$ is a map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ defined by, \begin{align} \breve{q} &= q + \frac{\epsilon}{2} p \\ \tilde{p} &= p - \epsilon \nabla U(q) \\ \tilde{q} &= \breve{q} + \frac{\epsilon}{2} \tilde{p}. \end{align} \end{definition} For Hamiltonians of the form $H(q, p) = \omega^2 q^2 / 2 + p^2 / 2$, the action of the leapfrog and inverted leapfrog integrators are linear. This means that there are matrices, called ``propagator matrices,'' which, when acting on the vector $(q, p)\in\R^2$, produce the same position in phase space as the integrators themselves. Computing integer matrix powers of these matrices can then produce the multi-step output of the integrators. In the case of the leapfrog integrator, the propagator matrix is \citep{leimkuhler_reich_2005}, \begin{align} \begin{pmatrix} \tilde{q} \\ \tilde{p} \end{pmatrix} = \underbrace{\begin{pmatrix} 1 - \frac{\epsilon^2\omega^2}{2} & \epsilon \\ \epsilon\omega^2\paren{1 - \frac{\epsilon^2\omega^2}{4}} & 1 - \frac{\epsilon^2\omega^2}{2} \end{pmatrix}}_{\mathbf{R}'} \begin{pmatrix} q \\ p \end{pmatrix}. \end{align} The propagator matrix for the inverted leapfrog is, \begin{align} \begin{pmatrix} \tilde{q} \\ \tilde{p} \end{pmatrix} = \underbrace{\begin{pmatrix} 1 - \frac{\epsilon^2\omega^2}{2} & \epsilon\paren{1 - \frac{\epsilon^2\omega^2}{4}} \\ -\epsilon\omega^2 & 1 - \frac{\epsilon^2\omega^2}{2} \end{pmatrix}}_{\mathbf{R}''} \begin{pmatrix} q \\ p \end{pmatrix}. \end{align} At stationarity, \begin{align} \begin{pmatrix} q \\ p \end{pmatrix} \sim \mathrm{Normal}\paren{\begin{pmatrix} 0 \\ 0 \end{pmatrix}, \begin{pmatrix} 1 / \omega^2 & 0 \\ 0 & 1 \end{pmatrix}}. \end{align} Therefore, for an integrator with propagator matrix $\mathbf{R}$, the distribution of the $k$-step transition is, \begin{align} \mathrm{Normal}\paren{\begin{pmatrix} 0 \\ 0 \end{pmatrix}, \mathbf{R}^k\begin{pmatrix} 1 / \omega^2 & 0 \\ 0 & 1 \end{pmatrix} (\mathbf{R}^k)^\top}, \end{align} \section{Algorithms}\label{app:algorithms} \input{algorithms/generalized-leapfrog} \input{algorithms/lagrangian-leapfrog} \input{algorithms/hmc} \input{algorithms/inverted-lagrangian-leapfrog} In this appendix we give pseudo-code implementations of algorithms featured in this work. In \cref{lagrangian-remarks:alg:generalized-leapfrog} we show the generalized leapfrog, which contrasts with the Lagrangian leapfrog in \cref{lagrangian-remarks:alg:lagrangian-leapfrog} in the presence of implicitly-defined integration steps. \Cref{lagrangian-remarks:alg:inverted-lagrangian-leapfrog} shows the Lagrangian integrator but with an inverted sequence of integration (updating position before velocity). In \cref{lagrangian-remarks:alg:hmc} we show an algorithmic implementation of a single-step of the Hamiltonian Monte Carlo Markov chain, which can be carried out using any of the integrators considered in this work. \section{Proofs Concerning Mechanics Systems}\label{lagrangian-remarks:app:proofs-concerning-mechanics} We give a proof of \cref{lagrangian-remarks:thm:hamiltonian-mechanics}. \begin{proof} We first show that the Hamiltonian energy is conserved. \begin{align} \frac{\mathrm{d}}{\mathrm{d}t} H(q_t, p_t) &= \nabla_q H(q_t, p_t) \cdot v_t + \nabla_p H(q_t, p_t) \cdot \dot{p}_t \\ &= \nabla_q H(q_t, p_t) \cdot \nabla_p H(q_t, p_t) - \nabla_p H(q_t, p_t) \cdot \nabla_q H(q_t, p_t) \\ &= 0. \end{align} Next we show that Hamiltonian mechanics conserve volume in $(q, p)$-space. This is equivalent to the vector field $(v_t, \dot{p}_t)$ having zero divergence, which we now verify. \begin{align} \mathrm{div}(v_t, \dot{p}_t) &= \nabla_q \cdot v_t + \nabla_p \cdot \dot{p}_t \\ &= \nabla_q \cdot \nabla_p H(q_t, p_t) - \nabla_p \cdot \nabla_q H(q_t, p_t) \\ &= \sum_{i=1}^m \frac{\partial^2 H}{\partial q_i \partial p_i} H(q_t, p_t) - \sum_{i=1}^m \frac{\partial^2 H}{\partial p_i \partial q_i} H(q_t, p_t) \\ &= 0, \end{align} by symmetry of partial derivatives. Finally we show that under the conditions that $\nabla_q H(q, -p) = \nabla_q H(q, p)$ and $\nabla_p H(q, -p) = -\nabla_p H(q, p)$ that the equations of motion are reversible under negation of the momentum variable. To see this, fix $\tau \in \R_+$ and consider $(q_t, p_t)$ satisfying \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} for $t\in [0, \tau]$. Let $\tilde{p}_t = -p_{\tau-t}$ and $\tilde{q}_t = q_{\tau-t}$. We find that $\tilde{q}_t$ and $\tilde{p}_t$ obey the following equations of motion: \begin{align} \frac{\mathrm{d}}{\mathrm{d}t} \tilde{q}_t &= -v_{\tau-t} \\ &= -\nabla_p H(q_{\tau-t}, p_{\tau-t}) \\ &= \nabla_p H(\tilde{q}_t, -p_{\tau-t}) \\ &= \nabla_p H(\tilde{q}_t, \tilde{p}_{t}) \\ \frac{\mathrm{d}}{\mathrm{d}t} \tilde{p}_t &= \dot{p}_{\tau-t} \\ &= -\nabla_q H(q_{\tau-t}, p_{\tau-t}) \\ &= -\nabla_q H(q_{\tau-t}, -p_{\tau-t}) \\ &= -\nabla_q H(\tilde{q}_t, \tilde{p}_t). \end{align} Thus we see that $(\tilde{q}_t, \tilde{p}_t)$ are also solutions to Hamilton's equations of motion and satisfy $\tilde{q}_\tau = q_0$ and $\tilde{p}_\tau = -p_0$, demonstrating reversibility. \end{proof} \section{Proofs Concerning the Numerical Order of the Lagrangian Integrators}\label{lagrangian-remarks:app:proofs-concerning-numerical-order} The claim of first order accuracy was derived in \citet{lan2015}; we have included a proof for completeness. \begin{proof}[Proof of \cref{lagrangian-remarks:lem:second-order-local-error}] Let $q_t$ and $v_t$ be solutions to the initial value problem, \begin{align} \dot{q}_t &= v_t \\ \dot{v}_t &= -\Omega(2, q_t, v_t) v_t - \mathbf{G}^{-1}(q_t) \nabla U(q_t). \end{align} Given the initial value $q_0 = q$ and $v_0 = v$, we can expand the solution in a Taylor series about $t=0$. \begin{align} q_t &= q_0 + t \dot{q}_0 + \mathcal{O}(t^2) \\ &= q + t v + \mathcal{O}(t^2) \\ v_t &= v_0 - t \paren{\Omega(2, q_0, v_0) v_0 - \mathbf{G}^{-1}(q_0) \nabla U(q_0)} + \mathcal{O}(t^2) \\ &= v - \Omega(2t, q, v) v - t \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(t^2). \end{align} Letting $t=\epsilon$ gives the following approximations, \begin{align} q_{\epsilon} &= q + \epsilon v + \mathcal{O}(\epsilon^2) \\ v_{\epsilon} &= v - \Omega(2\epsilon, q, v) v - \epsilon \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \end{align} Now we expand the steps of the explicit numerical integrator. We begin with the first update to velocity. \begin{align} \breve{v} &= \paren{\mathrm{Id}_m + \Omega(\epsilon, q, v)}^{-1} \paren{v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)} \\ &= \paren{\mathrm{Id}_m - \Omega(\epsilon, q, v) + \mathcal{O}(\epsilon^2)}\paren{v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)} \\ &= v - \Omega(\epsilon, q, v) v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \end{align} Now we expand the update to position. \begin{align} \tilde{q} &= q + \epsilon \breve{v} \\ &= q + \epsilon v + \mathcal{O}(\epsilon^2) \end{align} We conclude by expanding the second update to velocity in terms of the initial conditions. \begin{align} \tilde{v} &= \paren{\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, \breve{v})}^{-1} \paren{\breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q})\nabla U(\tilde{q})} \\ &= \breve{v} - \Omega(\epsilon, \tilde{q}, \breve{v}) \breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q}) + \mathcal{O}(\epsilon^2) \\ &= \breve{v} - \Omega(\epsilon, q, v) v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \\ &= v - \Omega(2\epsilon, q, v) v - \epsilon \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2). \end{align} Therefore, a single step of the numerical integrator with step-size $\epsilon$ agrees with the analytical solution to the initial value problem (from the same initial condition) to at least first order in $\epsilon$. \end{proof} \begin{proof}[Proof of \Cref{lagrangian-remarks:lem:inverted-lagrangian-properties}] To demonstrate that the inverted integrator has at least first-order error, we expand the steps of the integrator as follows. First, \begin{align} \breve{q} &= q + \frac{\epsilon}{2} ~v \\ \tilde{v} &= \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, v)}^{-1} \paren{v - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ &= \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, v)} \paren{v - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} + \mathcal{O}(\epsilon^2) \\ &= v - \Omega(2\epsilon, q, v) v - \epsilon \mathbf{G}^{-1}(q) \nabla U(q) + \mathcal{O}(\epsilon^2) \\ \tilde{q} &= \breve{q} + \frac{\epsilon}{2} \tilde{v} \\ &= q + \frac{\epsilon}{2} ~v + \frac{\epsilon}{2} ~v + \mathcal{O}(\epsilon^2) \\ &= q + \epsilon ~v. \end{align} This verifies that the inverted Lagrangian leapfrog has at least first order accuracy. In order to show that the inverted leapfrog integrator is symmetric, we proceed as follows. Recall that the three steps of the inverted Lagrangian leapfrog are \begin{align} \breve{q} &= q + \frac{\epsilon}{2} ~v \\ \tilde{v} &= \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, v)}^{-1} \paren{v - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ \tilde{q} &= \breve{q} + \frac{\epsilon}{2} ~\tilde{v}. \end{align} Therefore, we consider integrating from initial position $(\tilde{q},\tilde{v})$ with a negated step-size $-\epsilon$ as follows: \begin{align} \breve{q}' &= \tilde{q} - \frac{\epsilon}{2} ~\tilde{v} \\ &= \breve{q} \end{align} For the velocity we have, \begin{align} & \tilde{v}' = \paren{\mathrm{Id}_m - \Omega(2\epsilon, \breve{q}, \tilde{v})}^{-1} \paren{\tilde{v} + \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ \implies& \paren{\mathrm{Id}_m - \Omega(2\epsilon, \breve{q}, \tilde{v})} \tilde{v}' = \tilde{v} + \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q}) \\ \implies& \tilde{v} + \Omega(2\epsilon, \breve{q}, \tilde{v}')\tilde{v} = \tilde{v}' - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q}) \\ \implies& \tilde{v} = \paren{\mathrm{Id}_m + \Omega(2\epsilon, \breve{q}, \tilde{v}'}^{-1} \paren{\tilde{v}' - \epsilon \mathbf{G}^{-1}(\breve{q})\nabla U(\breve{q})} \\ \implies \tilde{v}' = v \end{align} Finally, the last update to the position is, \begin{align} \tilde{q}' &= \breve{q} - \frac{\epsilon}{2} v \\ &= q. \end{align} Hence we see that the inverted Lagrangian leapfrog is also self-adjoint. As noted in the main text, the combination of self-adjointness and at least first-order accuracy immediately imply second-order accuracy. \end{proof} \begin{proof}[Proof of \cref{lagrangian-remarks:lem:self-adjoint}] Self-adjointness of a numerical integrator follows immediately from the condition $\Phi_{-\epsilon}\circ \Phi_{\epsilon} = \mathrm{Id}$. Therefore, to demonstrate that a numerical method is self-adjoint it suffices to establish this condition. Consider the first update to the velocity: \begin{align} &\breve{v} = \paren{\mathrm{Id}_m + \Omega(\epsilon, q, v)}^{-1}\paren{v - \frac{\epsilon}{2} \mathbf{G}(q)^{-1}\nabla U(q)} \\ \iff& \breve{v} + \Omega(\epsilon, q, v) \breve{v} = v - \frac{\epsilon}{2} \mathbf{G}(q)^{-1} \nabla U(q) \\ \iff & \breve{v} + \frac{\epsilon}{2} \mathbf{G}(q)^{-1} \nabla U(q) = v - \Omega(\epsilon, q, \breve{v}) v \\ \iff & \breve{v} + \frac{\epsilon}{2} \mathbf{G}(q)^{-1} \nabla U(q) = \paren{\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v})} v \\ \iff & v = \paren{\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v})}^{-1}\paren{\breve{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)}. \end{align} An identical series of computations reveals, \begin{align} \breve{v} = \paren{\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v})}^{-1}\paren{\tilde{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q})\nabla U(\tilde{q})}. \end{align} Hence, applying $\Phi_{-\epsilon}$ to $(\tilde{q}, \tilde{v})$ yields the following series of updates, \begin{align} \label{lagrangian-remarks:eq:negated-i} \breve{v}' &= \paren{\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v})}^{-1}\paren{\tilde{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q})\nabla U(\tilde{q})} \\ &= \breve{v} \\ q' &= \tilde{q} - \epsilon \breve{v}' \\ &= \tilde{q} - \epsilon \breve{v} \\ &= q \\ \label{lagrangian-remarks:eq:negated-ii} v' &= \paren{\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v})}^{-1}\paren{\breve{v} + \frac{\epsilon}{2} \mathbf{G}^{-1}(q)\nabla U(q)} \\ &= v. \end{align} Hence we return to the initial condition $(q, v)$. This verifies that the explicit integrator employed in LMC is self-adjoint. \end{proof} \begin{proof}[Proof of \Cref{lagrangian-remarks:prop:composition-order}] Since $\hat{\Phi}_\epsilon$ is $p$-th order accurate for $\Phi_\epsilon$ we have, by Taylor series expansion, that, \begin{align} \label{eq:2021-12-19-taylor-i} \hat{\Phi}_0 &= \Phi_0 \\ \label{eq:2021-12-19-taylor-ii} \frac{\mathrm{d}^k}{\mathrm{d}\epsilon^k} \hat{\Phi}_\epsilon(z_0) \bigg|_{\epsilon=0} &= \frac{\mathrm{d}^k}{\mathrm{d}\epsilon^k} \Phi_\epsilon(z_0) \bigg|_{\epsilon=0}, \end{align} for $k=1,\ldots, p$. Let $f : \R\to\R^m$, then the Taylor series of expansion of $\Xi\circ f(\epsilon)$ is, \begin{align} \label{eq:2021-12-19-taylor-composition} \Xi \circ f(\epsilon) &= \Xi\circ f(0) + \sum_{k=1}^p \epsilon^k g^{[k]}\paren{f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0), \ldots, \frac{\mathrm{d}^k}{\mathrm{d}\epsilon^k} f(0)} + \mathcal{O}(\epsilon^{p+1}), \end{align} where $g^{[k]}$ are functions determining the Taylor series coefficients which depend on the derivatives of $f$. For instance, \begin{align} g^{[1]}\paren{f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0)} &= \nabla \Xi(f(0)) \cdot \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0) \\ g^{[2]}\paren{f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0), \frac{\mathrm{d}^2}{\mathrm{d}\epsilon^2} f(0)} &= \nabla^2 \Xi(f(0))\paren{\frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0), \frac{\mathrm{d}}{\mathrm{d}\epsilon} f(0)} + \nabla\Xi(f(0)) \cdot \frac{\mathrm{d}^2}{\mathrm{d}\epsilon^2} f(0). \end{align} By the equality of the Taylor series expansion coefficients in \cref{eq:2021-12-19-taylor-i,eq:2021-12-19-taylor-ii} it follows from \cref{eq:2021-12-19-taylor-composition} that, \begin{align} \Xi\circ\Phi_\epsilon(z_0) - \Xi\circ\hat{\Phi}_\epsilon(z_0) = \mathcal{O}(\epsilon^{p+1}). \end{align} This proves that $\Xi\circ\hat{\Phi}_\epsilon$ is also $p$-th order accurate for $\Xi\circ\Phi_\epsilon$. \end{proof} \section{Expanded Preliminaries} \subsection{Hamiltonian and Lagrangian Mechanics}\label{lagrangian-remarks:subsec:hamiltonian-lagrangian-mechanics} \begin{definition}\label{lagrangian-remarks:def:hamiltonian-mechanics} Let $H : \R^m\times\R^m\to\R$ be a smooth function, which we call the Hamiltonian. Hamilton's equations of motion are defined as the solutions to the initial value problem \begin{align} \label{lagrangian-remarks:eq:hamiltonian-position} v_t &= \nabla_p H(q_t, p_t) \\ \label{lagrangian-remarks:eq:hamiltonian-momentum} \dot{p}_t &= -\nabla_q H(q_t, p_t), \end{align} with $(q_0, p_0)$ a given initial position in phase space. \end{definition} \Cref{lagrangian-remarks:def:hamiltonian-mechanics} gives us a system of coupled first-order differential equations. Hamilton's equations of motion exhibit several key properties \citep{mechanics-and-symmetry}, which we summarize. \begin{theorem}\label{lagrangian-remarks:thm:hamiltonian-mechanics} The Hamiltonian mechanics given in \cref{lagrangian-remarks:def:hamiltonian-mechanics} possess the following three properties: \begin{enumerate} \item They preserve the Hamiltonian $\frac{\mathrm{d}}{\mathrm{d}t} H(q_t, p_t) = 0$. \item Denoting $\dot{z}_t = (v_t,\dot{p}_t)$ the equations of motion in phase space, Hamiltonian mechanics preserve volume in phase space: $\mathrm{div}(\dot{z}_t) = 0$. \item Under the conditions that $\nabla_q H(q, -p) = \nabla_q H(q, p)$ and $-\nabla_p H(q,p)= \nabla_pH(q, -p)$, the equations of motion are reversible via negation of the momentum variable. \end{enumerate} \end{theorem} A proof is given in \cref{lagrangian-remarks:app:proofs-concerning-mechanics}. In the special case when $U(q) = 0$ in \cref{lagrangian-remarks:eq:hamiltonian-form} for all $q\in\R^m$, Hamilton's equations of motion produce geodesic motion on the Riemannian manifold $(\R^m, \mathbf{G})$, where $\mathbf{G}$ assumes the role of the Riemannian metric \citep{Calin2004GeometricMO}. \begin{definition} Given a Riemannian Hamiltonian (\cref{lagrangian-remarks:def:riemannian-hamiltonian}), define the associated {\it Lagrangian} function by, \begin{align} \label{lagrangian-remarks:eq:lagrangian-form} L(q, v) &= \tilde{K}(q, v) - U(q), \end{align} where $\tilde{K}(q, v) = \frac{1}{2}v^\top \mathbf{G}(q) v$. \end{definition} Hamiltonian mechanics are related to Lagrangian dynamics by the Legendre transform which converts between momentum and velocity \citep{marsden_west_2001}. \begin{definition}\label{lagrangian-remarks:def:legendre-transform} Let $L : \R^m\times\R^m\to\R$ be a Lagrangian of the form in \cref{lagrangian-remarks:eq:lagrangian-form}. The {\it Legendre transform} relates the momentum and velocity according to $p = \frac{\partial L}{\partial v}(q, v) = \mathbf{G}(q) v$. \end{definition} \begin{definition}\label{lagrangian-remarks:def:inverse-legendre-transform} Let $H:\R^m\times\R^m\to\R$ be a Hamiltonian of the form in \cref{lagrangian-remarks:eq:hamiltonian-form}. The {\it inverse Legendre transform} relates velocity and momentum according to $v = \frac{\partial H}{\partial p}(q, p) = \mathbf{G}^{-1}(q)p$. \end{definition} The Lagrangian then determines equations of motion in accordance with the following physical principle. \begin{definition}\label{lagrangian-remarks:def:hamiltons-principle} {\it Hamilton's principle} states that the equations of motion $(q_t, v_t)$ over an interval of time $[a, b]$, with known boundary conditions $q_a$ and $q_b$, are solutions of the variational equation \begin{align} \frac{\delta \mathcal{S}[q_t]}{\delta q_t} = 0 \end{align} where \begin{align} \mathcal{S}[q_t] = \int_a^b L(q_t, v_t) ~\mathrm{d}t \end{align} where $q_t$ and $v_t$ are related by $v_t = \frac{\mathrm{d}}{\mathrm{d}t} q_t$. \end{definition} Hamilton's principle states that equations of motion (as specified by $q$ and $v$) should {\it extremize} the Lagrangian subject to the boundary conditions on $q_a$ and $q_b$. \begin{theorem}\label{lagrangian-remarks:thm:euler-lagrange} Under Hamilton's principle (\cref{lagrangian-remarks:def:hamiltons-principle}), the equations of motion $(q_t, v_t)$ must be solutions of the {\it Euler-Lagrange equation} \begin{align} \nabla_q L(q_t, v_t) = \frac{\mathrm{d}}{\mathrm{d}t} \nabla_{v} L(q_t, v_t). \end{align} \end{theorem} The equations of motion from \cref{lagrangian-remarks:thm:euler-lagrange} (or \cref{lagrangian-remarks:def:hamiltons-principle}) are, in fact, equivalent to the motion produced under Hamiltonian mechanics in \cref{lagrangian-remarks:def:hamiltonian-mechanics} \citep{mechanics-and-symmetry}. For Lagrangians of the form in \cref{lagrangian-remarks:eq:lagrangian-form}, the $k$-th element of the acceleration is, \begin{align} \label{lagrangian-remarks:eq:lagrangian-acceleration} a_t^{(k)} = -\sum_{i=1}^m\sum_{j=1}^m \Gamma^k_{ij}(q_t) v_t^{(i)} v_t^{(j)} - \sum_{l=1}^m \mathbf{G}^{-1}_{kl}(q_t) \frac{\partial U}{\partial q^{(l)}} (q_t), \end{align} where $\Gamma^k_{ij}$ are the Christoffel symbols (\cref{lagrangian-remarks:def:christoffel-symbols}). We conclude this section by noting that $\Omega$ in \cref{lagrangian-remarks:eq:omega} enjoys the following properties: \begin{proposition}\label{lagrangian-remarks:prop:omega-properties} The function $\Omega : \R\times\R^m\times\R^m\to\R^{m\times m}$ in \cref{lagrangian-remarks:eq:omega} satisfies \begin{align} \label{lagrangian-remarks:eq:omega-symmetry} \Omega(\epsilon, q, v)\breve{v} &= \Omega(\epsilon, q, \breve{v}) v \\ \label{lagrangian-remarks:eq:omega-derivative} \frac{\partial}{\partial v} (\Omega(\epsilon, q, v)\breve{v}) &= \Omega(\epsilon, q, \breve{v}). \end{align} \end{proposition} \begin{proof} The result in \cref{lagrangian-remarks:eq:omega-symmetry} can be seen from \begin{align} (\Omega(\epsilon, q, v)\breve{v})_i &= \frac{\epsilon}{2} \sum_{j=1}^m \sum_{k=1}^m \Gamma^i_{kj}(q) v^{(k)} \breve{v}^{(j)} \\ &= \frac{\epsilon}{2} \sum_{j=1}^m \sum_{k=1}^m \Gamma^i_{jk}(q) v^{(k)} \breve{v}^{(j)} \\ &= \frac{\epsilon}{2} \sum_{k=1}^m \sum_{j=1}^m \Gamma^i_{jk}(q) v^{(k)} \breve{v}^{(j)} \\ &= (\Omega(\epsilon, q, \breve{v})v)_i. \end{align} \Cref{lagrangian-remarks:eq:omega-derivative} then follows as an immediate corollary. \end{proof} Like Hamiltonian mechanics, Lagrangian dynamics conserve the Hamiltonian (when $p_t = \mathbf{G}(q_t) v_t$) and are reversible. However, Lagrangian dynamics do not conserve volume in $(q, v)$-space. \subsection{Background on Numerical Integrators}\label{lagrangian-remarks:subsec:numerical-integrators} The Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} and the Lagrangian motion described in \cref{lagrangian-remarks:eq:lagrangian-acceleration} rarely have closed-form solutions. Therefore, it is necessary to investigate methods of numerical integration to produce approximate solutions to these initial value problems. In the following section, we review key ideas from \citet{Hairer:1250576}. \begin{definition}\label{lagrangian-remarks:def:initial-value-problem} Let $g : \R^m\to\R^m$. {\it The solution to an initial value problem} is a function $z_{(\cdot)} : \R\to\R^m$ for which $\frac{\mathrm{d}}{\mathrm{d}t} z_t = g(z_t)$ and for which the {\it initial value} $z_0\in\R^m$ is known. In this case $g$ is called a {\it (time-homogenous) vector field}. \end{definition} \begin{definition}\label{lagrangian-remarks:def:integrator-order} Let $z_t$ be the solution to an initial value problem (\cref{lagrangian-remarks:def:initial-value-problem}) with initial value $z_0$. A {\it numerical integrator with step-size $\epsilon$} is a mapping $\Phi_{\epsilon} : \R^m\to\R^m$ and is said to have order $p$ if $\Vert \Phi_{\epsilon}(z_0) - z_{\epsilon}\Vert = \mathcal{O}(\epsilon^{p+1})$. \end{definition} \begin{definition}\label{lagrangian-remarks:def:self-adjoint} The adjoint of a numerical method $\Phi_\epsilon : \R^m \to\R^m$ is defined by the relation $\Phi_\epsilon^*(z) = \Phi^{-1}_{-\epsilon}(z)$. The numerical method $\Phi_\epsilon$ is said to be self-adjoint if $\Phi^*_\epsilon = \Phi_\epsilon$. \end{definition} \begin{theorem}[\citet{Hairer:1250576}]\label{lagrangian-remarks:thm:self-adjoint-even-order} Consider an initial value problem $\dot{z}_t = g(z_t)$ with initial condition $z_0 \in \R^m$. Let $\Phi_\epsilon$ be a one-step numerical integrator of (maximal) order $r\in\mathbb{N}$. If $\Phi_\epsilon$ is self-adjoint, then $r$ is even. \end{theorem} \begin{proposition}\label{lagrangian-remarks:prop:composition-order} Let $g : \R^m\to\R^m$ be a time-homogenous vector field. Let $\Xi:\R^m\to\R^m$ be a diffeomorphism. Let $z_t$ be the solution to the initial value problem $\dot{z}_t = g(z_t)$ given $z_0$. Let $\Phi_\epsilon : \R^m\to\R^m$ be the flow map of $z_\epsilon$ and suppose that $\hat{\Phi}_\epsilon$ is a $p$-th order approximation of $\Phi_\epsilon$. Then $\Xi\circ \hat{\Phi}_\epsilon$ is a $p$-th order approximation of $\Xi\circ \Phi_\epsilon$. \end{proposition} A proof is given in \cref{lagrangian-remarks:app:proofs-concerning-numerical-order}. \begin{proposition} The generalized leapfrog integrator is a second-order (\cref{lagrangian-remarks:def:integrator-order}), self-adjoint (\cref{lagrangian-remarks:def:self-adjoint}) numerical method. \end{proposition} \subsection{Hamiltonian and Lagrangian Monte Carlo}\label{lagrangian-remarks:subsec:hamiltonian-lagrangian-monte-carlo} Our objective in Bayesian inference is to draw samples from the distribution whose density is $\pi(q) \propto \exp(\mathcal{L}(q))$. We now review basic concepts from Markov chain Monte Carlo. \begin{definition} A {\it Markov chain transition kernel} is a map $K : \R^m\times\mathfrak{B}(\R^m) \to [0,1]$ satisfying (i) for every $x\in \R^m$ the map $A\mapsto K(x, A)$ is a probability measure and (ii) for every $A \in\mathfrak{B}(\R^m)$, the map $x\mapsto K(x, A)$ is measurable. Given a Markov chain transition kernel $K$, a {\it Markov chain} is defined inductively by $x_{n+1} \vert x_n \sim K(x_n, \cdot)$. \end{definition} HMC accomplishes this by artificially expanding the distribution to incorporate a momentum variable. Defining $U(q) = -\mathcal{L}(q) + \frac{1}{2} \log\mathrm{det}(\mathbf{G}(q))$, let $H(q, p)$ be the Hamiltonian given in \cref{lagrangian-remarks:eq:hamiltonian-form} and observe that the density $\pi(q, p) \propto \exp(-H(q, p))$ has $\pi(q) = \int_{\R^m} \pi(q, p) ~\mathrm{d}p$ and $p \vert q \sim\mathrm{Normal}(0, \mathbf{G}(q))$. In order to unify methods of Bayesian inference based on either the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}) or the Lagrangian leapfrog (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) under one framework, we now introduce the Markov chain transition kernel based on smooth involutions. \begin{definition}[\citet{DBLP:conf/icml/NeklyudovWEV20}]\label{lagrangian-remarks:def:involutive-monte-carlo} Let $\Phi : \R^m\times\R^m\to\R^m\times\R^m$ be a smooth involution (i.e. $\Phi=\Phi^{-1}$). Let $\pi:\R^m\times\R^m\to\R_+$ be a probability density with respect to Lebesgue measure. Then we define the Markov chain transition kernel of {\it involutive Monte Carlo} by \begin{align} \begin{split} K((q, p), (A, B)) &= \alpha((q, p), (\tilde{q},\tilde{p}), J)~\mathbf{1}\set{(\tilde{q}, \tilde{p})\in (A, B)} \\ &\qquad + \paren{1-\alpha((q, p), (\tilde{q},\tilde{p}), J)} ~\mathbf{1}\set{(q, p)\in (A, B)} \end{split} \\ \label{lagrangian-remarks:eq:acceptance-probability} \alpha((q, p), (\tilde{q}, \tilde{p}), J) &= \min\set{1, \frac{\exp(-H(\tilde{q}, \tilde{p}))}{\exp(-H(q, p))}\cdot J} \\ J &= \abs{\mathrm{det}\paren{\frac{\partial (\tilde{q}, \tilde{p})}{\partial (q, p)}}}, \end{align} where $(A, B)\in\mathfrak{B}(\R^m\times\R^m)$ and $(\tilde{q}, \tilde{p}) = \Phi(q, p)$. \end{definition} \begin{proposition}\label{lagrangian-remarks:prop:involutive-monte-carlo-detailed-balance} The Markov chain transition kernel of involutive Monte Carlo satisfies detailed balance with respect to the distribution whose density is $\pi(q, p)\propto \exp(-H(q, p))$. \end{proposition} A proof is provided in \cref{lagrangian-remarks:app:involutive-monte-carlo}. Central to the construction of involutions of interest to us is the momentum flip operator, defined as follows. \begin{definition}\label{lagrangian-remarks:def:momentum-flip} The {\it momentum flip operator} is the map $\mathbf{F}(q, p) = (q, -p)$. \end{definition} The fact that numerical integrators can be combined with the momentum flip operator in order to produce involutions is covered in \cref{lagrangian-remarks:app:involutive-monte-carlo} in the case of the Lagrangian leapfrog; other integrators are handled similarly. We provide pseudo-code implementing a single step of involutive Monte Carlo in \cref{lagrangian-remarks:alg:hmc} with involutions provided by the generalized leapfrog or Lagrangian leapfrog integrator. Given an initial point $(q_0, p_0)$ in phase space drawn from the distribution $\pi(q, p)$, the sequence of states $((q_1,p_1), (q_2, p_2), \ldots)$ computed by \cref{lagrangian-remarks:alg:hmc} are guaranteed to have $\pi(q, p)$ as their marginal distributions. Under the additional conditions that the HMC Markov chain is irreducible and aperiodic, HMC also produces an ergodic chain. The generalized leapfrog integrator is volume preserving. However, the integrator of Lagrangian dynamics is not. The required change-of-volume can be deduced as follows. First, observe that the update \cref{lagrangian-remarks:eq:lagrangian-position-update} is immediately volume-preserving since it is merely the translation of the position variable by a quantity. The change of volume incurred in \cref{lagrangian-remarks:eq:lagrangian-velocity-i} has a Jacobian determinant given by, \begin{align} \abs{\mathrm{det}\paren{\frac{\partial (q, \breve{v})}{\partial (q, v)}}} = \abs{\frac{\mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v}))}{\mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, q, v))}}. \end{align} The update in \cref{lagrangian-remarks:eq:lagrangian-velocity-ii} incurs a similar change of volume. Thus, when employing \cref{lagrangian-remarks:alg:lagrangian-leapfrog}, the Jacobian determinant of the transformation $(q, p)\mapsto (\tilde{q}, \tilde{p})$ is, \begin{align} \begin{split} \label{lagrangian-remarks:eq:lagrangian-jacobian-determinant} &\abs{\mathrm{det}\paren{\frac{\partial (\tilde{q}, \tilde{p})}{\partial (q, p)}}} = \mathrm{det}(\mathbf{G}^{-1}(q))\mathrm{det}(\mathbf{G}(\tilde{q})) ~\times \\ &\qquad \abs{\frac{\mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, \tilde{q}, \tilde{v})) \mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, q, \breve{v}))}{\mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, \breve{v})) \mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, q, v))}}. \end{split} \end{align} \begin{definition}\label{lagrangian-remarks:def:rmhmc} Let $\Phi_\epsilon$ be the generalized leapfrog integrator with step-size $\epsilon\in\R$ (\cref{lagrangian-remarks:def:generalized-leapfrog}). Let $k\in\mathbb{N}$ be a number of integration steps. The {\it Riemannian manifold Hamiltonian Monte Carlo (RMHMC) Markov chain} is an instance involutive Monte Carlo (\cref{lagrangian-remarks:def:involutive-monte-carlo}) with involution $\mathbf{F} \circ \Phi_{\epsilon}^k$. \end{definition} \begin{definition}\label{lagrangian-remarks:def:lmc} Let $\Phi_\epsilon$ be the Lagrangian leapfrog integrator with step-size $\epsilon\in\R$ (\cref{lagrangian-remarks:def:lagrangian-leapfrog}). Let $k\in\mathbb{N}$ be a number of integration steps. The {\it Lagrangian Monte Carlo (LMC) Markov chain} is an instance involutive Monte Carlo (\cref{lagrangian-remarks:def:involutive-monte-carlo}) with involution $\mathbf{F} \circ \Phi_{\epsilon}^k$. \end{definition} \section{Introduction} Let $\mathcal{L} : \R^m\to\R$ be the log-density of a smooth distribution, known up to an additive constant. A critical problem in Bayesian inference is the design of procedures that generate samples from a target density $\pi(q) \propto \exp(\mathcal{L}(q))$. Hamiltonian Monte Carlo (HMC) \citep{Duane1987216,betancourt2017conceptual} is a Markov chain Monte Carlo (MCMC) method for sampling from arbitrary differentiable probability distributions based on numerical solutions to Hamilton's equations of motion. Unlike random walk Metropolis or the Metropolis-adjusted Langevin algorithm, HMC can propose distant states, thereby dramatically decreasing the autocorrelation between states of the chain and increasing sampling efficiency. The efficiency of HMC can be further improved by incorporating geometric concepts into the proposal mechanism. Information geometry \citep{10.5555/3019383} provides a framework for representing sets of probability densities as a Riemannian manifold whose metric can be chosen as the Fisher information matrix. When $\mathcal{L}$ decomposes into the sum of a log-likelihood and a log-prior terms, \citet{rmhmc} proposed Riemannian manifold Hamiltonian Monte Carlo (RMHMC), which sought to precondition Hamiltonian dynamics with the inverse of the sum of Fisher information of the log-likelihood and the negative Hessian of the log-prior. In general, both the Fisher information and the Hessian of the log-prior depend on the parameter, denoted here by $q$, to be sampled; this dependency produces a complicated Hamiltonian. In order to maintain the detailed balance condition of the RMHMC Markov chain, elaborate numerical integrators such as the generalized leapfrog or implicit midpoint methods must be used \citep{pourzanjani2019implicit,rmhmc,pmlr-v139-brofos21a}. These numerical integrators involve implicitly defined updates, wherein updates are defined as the solution to a fixed point equation, which are typically resolved to a prescribed convergence tolerance by fixed point iteration. \citet{lan2015} introduced Lagrangian Monte Carlo (LMC) as an alternative to RMHMC. Unlike RMHMC, which is based on numerical solutions to Hamiltonian mechanics, LMC is instead inspired by the Lagrangian formalism of classical mechanics. Although Lagrangian and Hamiltonian mechanics are formally equivalent from a physical perspective, methods of numerical integration assume a simplified form when expressed as Lagrangian mechanics. Indeed, the simplification is so significant that \citet{lan2015} was able to devise a fully explicit numerical integrator for which detailed balance could be maintained when used as a proposal operator in MCMC. However, the elimination of fixed point iterations was replaced by the requirement that four Jacobian determinants be computed in a single step of the explicit integrator. Moreover, it was stated that the explicit method had only first-order accuracy as a numerical integrator, supposedly producing less accurate solutions than the generalized leapfrog method, whose accuracy is second-order. The purpose of the present work is three-fold. First, we propose a simple mechanism by which to reduce the number of Jacobian determinant evaluations from four to two in a single step of the integrator. This is achieved by inverting the sequence in which position and velocity are integrated. Second, we will clarify that the order of the explicit integrator, with or without inversion, actually has second-order accuracy, the same as those integrators which are commonly used in RMHMC. Third, we discuss how LMC enjoys a greater robustness to human error than RMHMC. The outline of the remainder of this paper is as follows. In \cref{lagrangian-remarks:sec:preliminaries} we discuss preliminary material on Hamiltonian and Lagrangian mechanics, numerical integrators, and MCMC methods based off of these physical models. In \cref{lagrangian-remarks:sec:related-work} we review some related work in the literature on integration methods for RMHMC. In \cref{lagrangian-remarks:sec:analytical-apparatus} we proceed to our analysis of the LMC integrator, where we describe how one may reduce the number of Jacobian determinant computations while maintaining a fully explicit integration method and give a proof that the integrator has second-order accuracy. In \cref{lagrangian-remarks:sec:experimentation} we turn to the evaluation of the proposed modifications to LMC; we evaluate performance on several benchmark Bayesian inference tasks and give numerical evidence to support the claim of second-order accuracy. \section{Preliminaries}\label{lagrangian-remarks:sec:preliminaries} In this section we review the necessary background for Hamiltonian and Lagrangian Monte Carlo. \Cref{lagrangian-remarks:subsec:essentials} reviews the most important concepts from RMHMC and LMC, giving perspective on the varieties of integrators and how they are employed in a Markov chain Monte Carlo procedure. We then proceed in \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-mechanics} to recall the Hamiltonian and Lagrangian formalisms from physics. \Cref{lagrangian-remarks:subsec:numerical-integrators} then treats the matter of numerical integration of the Hamiltonian and Lagrangian mechanics. In \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-monte-carlo} we then review Hamiltonian and Lagrangian Monte Carlo using the framework of involutive Monte Carlo, wherein we give special attention to the Jacobian determinant computations that are necessitated in the Lagrangian construction. \subsection{Notation} In the context of classical mechanics, we denote by $q$ the position variable, $v$ the velocity variable, $p$ the momentum variable, and $a$ the acceleration variable, all elements of $\R^m$. We adopt the notation $q^{(k)}$ to refer to the $k$-th element of $q$, with similar conventions being employed for $v$ and $p$. Denoting $z=(q, p)$; we call $z$ a point in phase space. We denote by $\mathrm{PD}(m)$ the set of $m\times m$ positive definite matrices. Given a map $\Phi : \R^m\to\R^m$, we use the notation $\Phi^k$ to mean the composition $\Phi\circ\cdots\circ\Phi$ ($k$ times). We write $\mathrm{Id}_m$ to denote the identity matrix of size $m\times m$. We denote the Borel $\sigma$-algebra on $\R^m$ by $\mathfrak{B}(\R^m)$. \subsection{Lagrangian Monte Carlo: The Essentials}\label{lagrangian-remarks:subsec:essentials} Lagrangian Monte Carlo (LMC) is a geometric method of Bayesian inference that seeks to incorporate second-order information about the posterior in order to produce effective proposals, similar to Riemannian manifold Hamiltonian Monte Carlo (RMHMC). In this section we review the fundamentals of these methods. For applications in HMC, an important class of Hamiltonians have the following form: \begin{definition}\label{lagrangian-remarks:def:riemannian-hamiltonian} The {\it Riemannian Hamiltonian} \begin{align} \label{lagrangian-remarks:eq:hamiltonian-form} H(q, p) = U(q) + K(q, p) \end{align} where $U : \R^m\to\R$ is called the {\it potential energy} function and $K:\R^m\times\R^m\to\R$ is the {\it kinetic energy} function, having the form $K(q, p) = \frac{1}{2} p^\top \mathbf{G}^{-1}(q) p$, where $\mathbf{G} :\R^m\to \mathrm{PD}(m)$ where $\mathbf{G}$ is called the {\it metric}. \end{definition} The Riemannian metric defines Christoffel symbols which convey information about the curvature and shape of $\R^m$ imbued with the metric $\mathbf{G}$. \begin{definition}\label{lagrangian-remarks:def:christoffel-symbols} The Christoffel symbols are the $m^3$ functions defined by \begin{align} \label{lagrangian-remarks:eq:christoffel} \Gamma^k_{ij}(q) = \frac{1}{2} \sum_{l=1}^m \mathbf{G}^{-1}_{kl}(q) \paren{\frac{\partial}{\partial q^{(i)}} \mathbf{G}_{lj}(q) + \frac{\partial}{\partial q^{(j)}} \mathbf{G}_{li}(q) - \frac{\partial}{\partial q^{(l)}} \mathbf{G}_{ij}(q)}. \end{align} \end{definition} We note that the Christoffel symbols are symmetric in their lower indices (i.e. $\Gamma^k_{ij}(q) = \Gamma^k_{ji}(q)$). The Christoffel symbols play a prominent role in the development of Lagrangian mechanics. As a notational convenience, we will define the matrix-valued function $\Omega : \R\times\R^m\times\R^m\to \R^{m\times m}$ whose $(i, j)$-th entry is \begin{align} \label{lagrangian-remarks:eq:omega}\Omega_{ij}(\epsilon, q, v) = \frac{\epsilon}{2} \sum_{k=1}^m \Gamma^i_{kj}(q) v^{(k)}. \end{align} The Riemannian Hamiltonian in \cref{lagrangian-remarks:def:riemannian-hamiltonian} produces equations of motion (see \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-mechanics} for details), which do not have closed-form solutions. This necessitates the use of numerical integrators. We now review two integrators that form the basis of our evaluations: the generalized leapfrog integrator, which is a reversible, volume-preserving, and second-order accurate, and the Lagrangian leapfrog method of \citet{lan2015}. \begin{definition}\label{lagrangian-remarks:def:generalized-leapfrog} The {\it generalized leapfrog integrator} for the Hamiltonian equations of motion in \cref{lagrangian-remarks:eq:hamiltonian-position,lagrangian-remarks:eq:hamiltonian-momentum} is a map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ defined by, \begin{align} \label{lagrangian-remarks:eq:generalized-leapfrog-momentum-i} \breve{p}^{(k)} &= p^{(k)} - \frac{\epsilon}{2} \paren{-\frac{1}{2} \breve{p}^\top \mathbf{G}^{-1}(q) \paren{\frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)} \mathbf{G}^{-1}(q) \breve{p} + \frac{\partial U}{\partial q^{(k)}}(q)} \\ \label{lagrangian-remarks:eq:generalized-leapfrog-position} \tilde{q} &= q + \frac{\epsilon}{2} \paren{\mathbf{G}^{-1}(q)\breve{p} + \mathbf{G}^{-1}(\tilde{q})\breve{p}} \\ \label{lagrangian-remarks:eq:generalized-leapfrog-momentum-ii} \tilde{p}^{(k)} &= \breve{p}^{(k)} - \frac{\epsilon}{2} \paren{-\frac{1}{2} \breve{p}^\top \mathbf{G}^{-1}(q) \paren{\frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)} \mathbf{G}^{-1}(q) \breve{p} + \frac{\partial U}{\partial q^{(k)}}(\tilde{q})}. \end{align} \end{definition} Pseudo-code implementing the generalized leapfrog algorithm is given in \cref{lagrangian-remarks:alg:generalized-leapfrog} in \cref{app:algorithms}. \begin{definition}\label{lagrangian-remarks:def:lagrangian-leapfrog} The {\it Lagrangian leapfrog integrator} for the Lagrangian equations of motion given in \cref{lagrangian-remarks:eq:lagrangian-acceleration} is a map $(q, v)\mapsto (\tilde{q}, \tilde{v})$ defined by, \begin{align} \label{lagrangian-remarks:eq:lagrangian-velocity-i} \breve{v} &= \left[\mathrm{Id}_m + \Omega(\epsilon, q, v)\right]^{-1} \left[v - \frac{\epsilon}{2} \mathbf{G}^{-1}(q) \nabla U(q)\right] \\ \label{lagrangian-remarks:eq:lagrangian-position-update} \tilde{q} &= q + \epsilon ~\breve{v} \\ \label{lagrangian-remarks:eq:lagrangian-velocity-ii} \tilde{v} &= \left[\mathrm{Id}_m + \Omega(\epsilon, \tilde{q}, \breve{v})\right]^{-1} \left[\breve{v} - \frac{\epsilon}{2} \mathbf{G}^{-1}(\tilde{q}) \nabla U(\tilde{q})\right]. \end{align} \end{definition} Pseudo-code implementing the Lagrangian leapfrog algorithm is given in \cref{lagrangian-remarks:alg:lagrangian-leapfrog} in \cref{app:algorithms}. Unlike the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}), which is a symplectic transformation and therefore necessarily volume-preserving, the Lagrangian leapfrog (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) is not volume-preserving. Its Jacobian determinant is computed in \cref{lagrangian-remarks:eq:lagrangian-jacobian-determinant}. A thorough treatment of numerical integrators is provided in \cref{lagrangian-remarks:subsec:numerical-integrators} In the context of Monte Carlo, this means that Markov chains constructed from repeated applications of the Lagrangian leapfrog integrator will require a Jacobian determinant computation, whereas methods based on the generalized leapfrog will not (its Jacobian determinant is one). Such a Markov chain is the subject of the following example. \begin{example} Let $H:\R^m\times\R^m \to\R$ be as in \cref{lagrangian-remarks:def:riemannian-hamiltonian} and define a probability density $\pi(q, p)\propto \exp(-H(q, p))$. Let $q\in\R^m$ be given; a single Markov chain step is constructed as follows. Sample $p \sim \mathrm{Normal}(0, \mathbf{G}(q))$. Fix $k\in\mathbb{N}$. We consider RMHMC and LMC separately: \begin{description} \item[LMC] Let $\tilde{\Phi}_\epsilon$ denote the Lagrangian leapfrog (\cref{lagrangian-remarks:def:lagrangian-leapfrog}). Compute the proposal $(\tilde{q}, \tilde{v}) = \tilde{\Phi}(q, \mathbf{G}^{-1}(q) p)$ and set $\tilde{p} = \mathbf{G}(\tilde{q}) \tilde{v}$. Compute the Jacobian determinant $J$ of the map $(q, p)\mapsto (\tilde{q},\tilde{p})$ using \cref{lagrangian-remarks:eq:lagrangian-jacobian-determinant}. \item[RMHMC] Let $\hat{\Phi}_\epsilon$ denote the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}). Compute the proposal $(\tilde{q}, \tilde{p}) = \hat{\Phi}(q, p)$ and set $J=1$. \end{description} Accept the proposal state $\tilde{q}$ with probability $\alpha((q, p), (\tilde{q},\tilde{p}), J) = \min\set{1, \frac{\pi(\tilde{q}, \tilde{p})}{\pi(q, p)} \cdot J}$; otherwise remain at the current state $q$. \end{example} A more rigorous treatment of the LMC and RMHMC Markov chains is given in \cref{lagrangian-remarks:subsec:hamiltonian-lagrangian-monte-carlo} using the framework of diffeomorphism Monte Carlo. Pseudo-code is provided in \cref{lagrangian-remarks:alg:hmc} in \cref{app:algorithms}. \section{Related Work}\label{lagrangian-remarks:sec:related-work} The focus of the present work is to investigate the numerical methods of integration that were proposed in \citet{lan2015}. \Citet{pmlr-v139-brofos21a} gave an evaluation of the implicit midpoint integrator for RMHMC with special attention paid to the errors in reversibility and volume preservation that were produced by the implicit midpoint algorithm compared to the generalized leapfrog method, as well as the energy conservation properties enjoyed by the implicit midpoint integrator. Other mechanisms of explicit integration have been considered with applications to RMHMC foremost in mind, such as \citet{cobb2019introducing} which produced a reversible, volume-preserving numerical method in an expanded phase-space. Due to the expansion of phase-space, this integrator cannot be used to produce a Markov chain satisfying detailed balance. The work of \citet{NIPS2014_a87ff679} explored alternating blockwise Metropolis-within-Gibbs-like strategies with Riemannian metrics chosen to produce separable Hamiltonians within each block; each block can then be integrated using the standard leapfrog integrator. LMC has previously been criticized in the literature for having unfavorable performance in high dimensions; this failure of LMC in relation to RMHMC is discussed in \citet{geometric-foundations} and we will see evidence of this degradation in \cref{lagrangian-remarks:subsec:student-t}. \section{Analytical Apparatus}\label{lagrangian-remarks:sec:analytical-apparatus} In this section we describe an algorithmic recommendation for the numerical integrator used in Lagrangian Monte Carlo and we clarify certain statements around the order of this numerical method. Specifically, we show how to reduce the number of determinant computations from four to two, and that the integrator of Lagrangian dynamics has third-order local error, comparable to the error of the (generalized) leapfrog method used in HMC. \subsection{Inversion of the Integration Sequence} A disadvantage of the Lagrangian integrator is that it involves four Jacobian determinant computations at each step of the integrator. In general, computing the Jacobian determinant of an $m\times m$ matrix incurs a computational cost like $\mathcal{O}(m^3)$. Therefore, it seems worthwhile to investigate mechanisms by which to reduce the number of these calculations that are required. \Citet{lan2015} proposed one method that has only two Jacobian determinant computations, but necessitates the return to implicit methods of integration. To retain the advantages of explicit integration, we propose a method that computes two Jacobian determinants in every step and consists only of {\it explicit} integration steps. To achieve this, we propose a conceptually simple procedure: invert the sequence in which position and velocity are updated in the Lagrangian integrator so that position is updated twice at the beginning and end of each step and velocity is updated once in between each update to position. Formally: \begin{definition}\label{lagrangian-remarks:def:inverted-lagrangian-leapfrog} The {\it inverted Lagrangian leapfrog integrator} for the Lagrangian equations of motion given in \cref{lagrangian-remarks:eq:lagrangian-acceleration} is a map $(q, v)\mapsto (\tilde{q}, \tilde{v})$ defined by, \begin{align} \label{lagrangian-remarks:eq:inverted-lagrangian-position-i} \breve{q} &= q + \frac{\epsilon}{2} ~v \\ \label{lagrangian-remarks:eq:inverted-lagrangian-velocity} \tilde{v} &= \left[\mathrm{Id}_m + 2\Omega(\epsilon, \breve{q}, v)\right]^{-1} \left[v - \epsilon \mathbf{G}^{-1}(\breve{q}) \nabla U(\breve{q})\right] \\ \label{lagrangian-remarks:eq:inverted-lagrangian-position-ii} \tilde{q} &= \breve{q} + \frac{\epsilon}{2} \tilde{v}. \end{align} \end{definition} Pseudo-code for this procedure is provided in \cref{lagrangian-remarks:alg:inverted-lagrangian-leapfrog} in \cref{app:algorithms}. The basic modification requires only two Jacobian determinant computations per step since the two updates to position in \cref{lagrangian-remarks:eq:inverted-lagrangian-position-i,lagrangian-remarks:eq:inverted-lagrangian-position-ii}, being shear transformations, are volume-preserving in $(q, v)$-space \citep{modi2021delayed}. The required change in volume due to the mapping $(q, p)\mapsto (\tilde{q}, \tilde{p})$ is readily obtained as \begin{align} \begin{split} \label{lagrangian-remarks:eq:inverted-lagrangian-jacobian-determinant} &\abs{\mathrm{det}\paren{\frac{\partial (\tilde{q}, \tilde{p})}{\partial (q, p)}}} = \abs{\frac{\mathrm{det}(\mathbf{G}(\tilde{q}))}{\mathrm{det}(\mathbf{G}(q))} \frac{\mathrm{det}(\mathrm{Id}_m - \Omega(\epsilon, \breve{q}, \tilde{v}))}{\mathrm{det}(\mathrm{Id}_m + \Omega(\epsilon, \breve{q}, v))}}. \end{split} \end{align} Although this Jacobian determinant differs from that produced by \cref{lagrangian-remarks:alg:lagrangian-leapfrog} in \cref{app:algorithms}, we still have the following important property. \begin{lemma}\label{lagrangian-remarks:lem:inverted-lagrangian-properties} The inverted Lagrangian leapfrog integrator is self-adjoint and has at least first-order local error. \end{lemma} A proof is given in \cref{lagrangian-remarks:app:proofs-concerning-numerical-order}. \begin{corollary} The inverted Lagrangian leapfrog integrator has at least second-order local error. \end{corollary} \begin{proof} This follows as an immediate corollary of \cref{lagrangian-remarks:lem:inverted-lagrangian-properties} \end{proof} \begin{definition}\label{lagrangian-remarks:def:ilmc} Let $\Phi_\epsilon$ be the inverted Lagrangian leapfrog integrator with step-size $\epsilon\in\R$ (\cref{lagrangian-remarks:def:inverted-lagrangian-leapfrog}). Let $k\in\mathbb{N}$ be the number of integration steps. The {\it inverted Lagrangian Monte Carlo (ILMC)} is an instance involutive Monte Carlo (\cref{lagrangian-remarks:def:involutive-monte-carlo}) with involution $\mathbf{F} \circ \Phi_{\epsilon}^k$ where $\mathbf{F}$ is the momentum flip operator (\cref{lagrangian-remarks:def:momentum-flip}). \end{definition} Let us denote by $\hat{\Phi}_\epsilon$ the Lagrangian leapfrog integrator (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) and $\check{\Phi}_{\epsilon}$ the inverted Lagrangian leapfrog (\cref{lagrangian-remarks:def:inverted-lagrangian-leapfrog}). Let $\Phi_\epsilon$ be the exact time $\epsilon$ solution of \cref{lagrangian-remarks:eq:lagrangian-acceleration}. Because both methods are second-order accurate, it follows that \begin{align} \Vert \hat{\Phi}_\epsilon - \check{\Phi}_\epsilon \Vert &\leq \Vert \hat{\Phi}_\epsilon - \Phi_\epsilon \Vert + \Vert \check{\Phi}_\epsilon - \Phi_\epsilon \Vert \\ &= \mathcal{O}(\epsilon^3) \end{align} Intuitively, in the limit of small step-sizes, the difference in proposals generated by the Lagrangian leapfrog and the inverted Lagrangian leapfrog will be minimal, but ILMC (\cref{lagrangian-remarks:def:ilmc}) involves half the number of Jacobian determinant computations compared to LMC (\cref{lagrangian-remarks:def:lmc}) and should therefore be preferred. On the other hand, for large step-sizes, the situation is less clear. \subsection{Aversions to Inverting the Integration Sequence} \input{figures/position-difference} In the case when $\mathbf{G} = \mathrm{Id}_m$, the Lagrangian integrator devolve into the standard leapfrog integrator (\cref{lagrangian-remarks:def:standard-leapfrog}) that is ubiquitous in HMC. There are good reasons why implementations of HMC integrate in the order of an initial half-step in momentum, a full step in position, and then a second half-step of momentum. This is described visually by \citet{bou-rabee_sanz-serna_2018} for the Hamiltonian $H(q, p) = q^2 / 2 + p^2 / 2$, who make the argument that the leapfrog integrator produces high acceptance probabilities along the $q$-axis, which are desirable. By contrast, inverted leapfrog (\cref{lagrangian-remarks:def:inverted-leapfrog}) produces large acceptance probabilities along the $p$-axis, which are not valuable in HMC. Here we wish to expand on this example to consider what happens when HMC Markov chains based on the standard leapfrog and inverted leapfrog are initialized at stationarity. Based on the symmetric roles of $q$ and $p$ in the Hamiltonian, it is tempting to conclude that these Markov chains would exhibit similar performance profiles; surprisingly, this is not the case as shown in the following example. \begin{example}\label{lagrangian-remarks:ex:inverted-order-inferior} Consider a Hamiltonian of the form $H(q, p) = \omega^2 q^2 / 2 + p^2 / 2$. This Hamiltonian corresponds to the distributions $q\sim\mathrm{Normal}(0, 1/\omega^2)$ and $p\sim \mathrm{Normal}(0, 1)$. Let $\hat{\Phi}_\epsilon : \R^m\times\R^m\to \R^m\times\R^m$ and $\check{\Phi}_\epsilon : \R^m\times\R^m\to\R^m\times\R^m$ be the single step leapfrog (\cref{lagrangian-remarks:def:standard-leapfrog}) and inverted leapfrog (\cref{lagrangian-remarks:def:inverted-leapfrog}) methods with step-size $\epsilon$, respectively. Let $\mathrm{Proj}_q(q, p) = q$ be the projection onto the $q$-variables. Then, \begin{align} \mathbb{E} \left[(\mathrm{Proj}_q\circ\hat{\Phi}_\epsilon(q, p) - q)^2\right] &= \frac{\epsilon^4\omega^2}{4} + \epsilon^2 \\ \mathbb{E} \left[(\mathrm{Proj}_q\circ\check{\Phi}_\epsilon(q, p) - q)^2\right] &= \frac{\epsilon^4\omega^2}{4} + \epsilon^2 \paren{1 - \frac{\epsilon^2\omega^2}{4}}. \end{align} Both the leapfrog and inverted leapfrog methods are only numerically stable when $\epsilon^2 \omega^2 < 4$ \citep{leimkuhler_reich_2005}. Hence, $\mathbb{E} \left[(\mathrm{Proj}_q\circ\check{\Phi}_\epsilon(q, p) - q)^2\right] < \mathbb{E} \left[(\mathrm{Proj}_q\circ\hat{\Phi}_\epsilon(q, p) - q)^2\right]$, which we interpret to mean that, in a single step of the integrator, the expected squared distance between initial and terminal position is greater for the leapfrog integrator than for the inverted leapfrog. By deriving the propagator matrices (see \cref{lagrangian-remarks:app:propagator-matrices}) of the leapfrog and inverted leapfrog integrators, we may deduce exact formulas for the $k$-step quantities $\mathbb{E} \left[(\mathrm{Proj}_q\circ\hat{\Phi}^k_\epsilon(q, p) - q)^2\right]$ and $\mathbb{E} \left[(\mathrm{Proj}_q\circ\check{\Phi}^k_\epsilon(q, p) - q)^2\right]$. In \cref{lagrangian-remarks:fig:position-difference} we show the difference of these expected squared distances as a function of the number of steps and for several step-sizes. Notably, this difference is always non-negative, indicating that one expects the leapfrog to produce more distant proposals than the inverted leapfrog in the Gaussian case. \end{example} Because autocorrelation is related to the distance to subsequent samples, one expects the inverted leapfrog method to exhibit fewer effective samples. This will be true even if LMC Markov chain is initialized in the stationary distribution. This illustrates an important short-coming of inverting the integration sequence, which must be balanced against computational savings obtained by the reduction in Jacobian determinant computations in the LMC setting. \subsection{The Order of the Explicit Integrators} In \citet{lan2015}, the authors showed that the local error rate of the Lagrangian integrator is at least $\mathcal{O}(\epsilon^2)$. We now build on this foundation in order to deduce that the local error rate of the Lagrangian leapfrog is at least $\mathcal{O}(\epsilon^3)$. This means that the order of the LMC integrator matches the local and global error rates of the integrators used in HMC and RMHMC. Proofs of \cref{lagrangian-remarks:lem:second-order-local-error,lagrangian-remarks:lem:self-adjoint} may be found in \cref{lagrangian-remarks:app:proofs-concerning-numerical-order}. \begin{lemma}\label{lagrangian-remarks:lem:second-order-local-error} The explicit integrator of the Lagrangian dynamics has at least first-order local error. \end{lemma} \begin{lemma}\label{lagrangian-remarks:lem:self-adjoint} The explicit integrator of Lagrangian dynamics is self-adjoint. \end{lemma} \begin{proposition}\label{lagrangian-remarks:prop:third-order-local-error} The explicit integrator of the Lagrangian dynamics has at least third-order local error. \end{proposition} \begin{proof} From \cref{lagrangian-remarks:lem:second-order-local-error} we know that $r\geq 1$. Suppose $r=1$. From \cref{lagrangian-remarks:lem:self-adjoint} we know that the integrator is self-adjoint. From \cref{lagrangian-remarks:thm:self-adjoint-even-order} we know that the order of a self-adjoint method must be even; hence $r$ cannot be odd. But $r=1$ by assumption, a contradiction. Therefore, it must be that $r\geq 2$ so that the explicit integrator has, at least, third-order local error. \end{proof} Denote by $\hat{\Phi}_\epsilon$ the second-order integrator of Lagrangian dynamics. If $\hat{\Phi}_\epsilon(q_0, v_0) = (\hat{q}_\epsilon, \hat{v}_\epsilon)$, one wonders if $(\hat{q}_\epsilon, \hat{p}_\epsilon)$ is a second-order approximation of the {\it Hamiltonian dynamics}, where $\hat{p}_\epsilon = \mathbf{G}(\hat{q}_\epsilon) \hat{v}_\epsilon$. Indeed, this is true and follows as an immediate consequence of \cref{lagrangian-remarks:prop:composition-order} with diffeomorphism $(q, v)\mapsto (q, \mathbf{G}v)$. \subsection{Efficient Computation of the Jacobian Determinant and the Update to Velocity} The update to the velocity in \cref{lagrangian-remarks:eq:inverted-lagrangian-velocity,lagrangian-remarks:eq:lagrangian-velocity-i,lagrangian-remarks:eq:lagrangian-velocity-ii} and the associated change-in-volume in \cref{lagrangian-remarks:eq:inverted-lagrangian-jacobian-determinant,lagrangian-remarks:eq:inverted-lagrangian-jacobian-determinant} involve manipulations of a matrix of the form $\mathrm{Id} + \Omega(\epsilon, q, v)$: in the former case, we must solve a linear system involving this matrix while in the latter case we must compute the absolute value of its Jacobian determinant. An efficient procedure by which to achieve both of these objectives is to compute the PLU decomposition of $\mathrm{Id} + \Omega(\epsilon, q, v)=\mathbf{P}\mathbf{L}\mathbf{U}$ where $\mathbf{P}$ is a permutation matrix, $\mathbf{L}$ is a lower-triangular matrix with unit diagonal, and $\mathbf{U}$ is an upper-triangular matrix. The computational cost of this decomposition is $\frac{2}{3}m^3 + \mathcal{O}(m^2)$. Linear systems can be solved using the PLU decomposition by applying the permutation and solving the triangular systems via forward-backward substitution. Moreover, the required Jacobian determinant is simply $\prod_{i=1}^m \mathbf{U}_{ii}$, since the determinant of the permutation matrix has unit magnitude and the lower-triangular matrix $\mathbf{L}$ has unit Jacobian determinant since all of its diagonal elements are equal to one. \subsection{Built-In Robustness of the Lagrangian Integrator}\label{lagrangian-remarks:subsec:robustness} As shown in \citet{brofos2021numerical}, the volume-preservation property (i.e. $J=1$ in \cref{lagrangian-remarks:alg:generalized-leapfrog} in \cref{app:algorithms}) of the generalized leapfrog integrator is predicated on the symmetry of partial derivatives $\nabla_q^\top \nabla_p H(q, p) = \nabla_p \nabla_q H(q,p)$. In an {\it implementation} of the generalized leapfrog integrator we may suppose that we have functions $g_{k}(q)$ representing $\frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$. Substituting this function into the definition of the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}) yields the following map $(q, p)\mapsto (\tilde{q}, \tilde{p})$ \begin{align} \breve{p}^{(k)} &= p^{(k)} - \frac{\epsilon}{2} \delta_k(q, \breve{p}) \\ \tilde{q} &= q + \frac{\epsilon}{2} \paren{\Delta(q, \breve{p}) + \Delta(\tilde{q}, \breve{p})} \\ \tilde{p}^{(k)} &= \breve{p}^{(k)} - \frac{\epsilon}{2} \delta_k(\tilde{q}, \breve{p}), \end{align} where \begin{align} \delta_k(q, p) &= -\frac{1}{2} p^\top \mathbf{G}^{-1}(q) g_k(q) \mathbf{G}^{-1}(q) p + \frac{\partial U}{\partial q^{(k)}}(q) \\ \Delta(q, p) &= \mathbf{G}^{-1}(q)p \end{align} When $g_k(q) = \frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$, the resulting map is necessarily volume-preserving. However, we may then ask the question, ``What happens when $g_k(q)$ is {\it incorrectly implemented} so that, in fact, $g_k(q) \neq \frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$?'' The symmetry of partial derivatives has therefore been violated since \begin{align} \frac{\partial\Delta}{\partial q^{(k)}}(q, p) = \frac{\partial \mathbf{G}^{-1}}{\partial q^{(k)}}(q) p \neq -\mathbf{G}^{-1}(q) g_k(q) \mathbf{G}^{-1}(q) p = \frac{\partial \delta_k}{\partial p}(q, p). \end{align} In the case of the RMHMC Markov chain (\cref{lagrangian-remarks:def:rmhmc}), detailed balance is no longer satisfied and there is no expectation that the RMHMC will converge to the target distribution. The situation is different in the case of the LMC Markov chain (\cref{lagrangian-remarks:def:lmc}). The fundamental difference is that LMC {\it expects} the transformation $(q, v)\mapsto (\tilde{q},\tilde{v})$ to be non-volume-preserving, hence necessitating the Jacobian determinant correction in \cref{lagrangian-remarks:eq:acceptance-probability}. To see that the change-in-volume is still correctly computed even when $g_k(q) \neq \frac{\partial \mathbf{G}}{\partial q^{(k)}}(q)$, we observe that the Lagrangian leapfrog's (\cref{lagrangian-remarks:def:lagrangian-leapfrog}) update to velocity in \cref{lagrangian-remarks:eq:lagrangian-velocity-i} is a special case of the following map: \begin{align} \breve{v} = \paren{\mathrm{Id}_m + \mathbf{A}(q, v)}^{-1} \paren{v - \mathbf{b}(q)} \end{align} where $\mathbf{A} : \R^m\times\R^m\to\R^{m\times m}$ and $\mathbf{b} : \R^m\to\R^m$. Under the assumption that $\mathbf{A}(q, v)\tilde{v} = \mathbf{A}(q, \tilde{v}) v$ (which holds for the correctly implemented LMC with $\mathbf{A} = \Omega(\epsilon, q, v)$ by \cref{lagrangian-remarks:prop:omega-properties}), the Jacobian determinant of the map $(q, v)\mapsto (q, \breve{v})$ is \begin{align} \label{lagrangian-remarks:eq:general-determinant} \abs{\mathrm{det}\paren{\frac{\partial (q, \breve{v})}{\partial (q, v)}}} = \abs{\frac{\mathrm{det}(\mathrm{Id}_m + \mathbf{A}(q, \breve{v}))}{\mathrm{det}(\mathrm{Id}_m + \mathbf{A}(q, v))}}. \end{align} Hence, if we adopt the notation $g_{k,ij}(q)$ as the $(i,j)$-th element of $g_k(q)$, and substitute \begin{align} \tilde{\Gamma}^k_{ij}(q) = \frac{1}{2} \sum_{l=1}^m \mathbf{G}^{-1}_{kl}(q) \paren{g_{i,lj}(q) + g_{j,li}(q) - g_{l, ij}(q)} \end{align} for \cref{lagrangian-remarks:eq:christoffel} and define $\tilde{\Omega}_{ij}(\epsilon, q, v) = \frac{\epsilon}{2} \sum_{k=1}^m \tilde{\Gamma}^i_{kl}(q) v^{(k)}$ then we still have $\tilde{\Omega}(\epsilon, q, v) \breve{v} = \tilde{\Omega}(\epsilon, q, \breve{v})v$ using the fact that $\tilde{\Gamma}^k_{ij}(q) = \tilde{\Gamma}^k_{ji}(q)$. Hence, with $\mathbf{A}(q, v) = \tilde{\Omega}(\epsilon, q, v)$, \cref{lagrangian-remarks:eq:general-determinant} applies to compute the Jacobian determinant. \section{Experimentation}\label{lagrangian-remarks:sec:experimentation} We now turn our attention to the empirical evaluation of the numerical integrator of Lagrangian dynamics in terms of its numerical order, its inverted variant, and its robustness to misspecification of the derivatives of the metric. We begin in \cref{lagrangian-remarks:subsec:second-order} by numerically validating the second-order behavior of the numerical integrator. In the subsequent material, we evaluate the integrator with and without inversion in a banana-shaped distribution, in Bayesian logistic regression, in a multiscale Student-$t$ distribution, and in a stochastic volatility model. As baselines, we consider RMHMC and HMC. Code to reproduce these experiments may be found at \if00 { \url{https://github.com/JamesBrofos/Rethinking-Lagrangian-Monte-Carlo}. } \fi \if10 { \url{https://github.com/Anonymous/GitHubLink}. } \fi We consider three metrics by which to assess the convergence of the Markov chain produced by ILMC and the baselines. First, we consider the expected squared jump distance (ESJD) as described in \citet{esjd}; this measures the expected squared distance between the current state and the next state, where the expectation is computed over the acceptance probability. The larger the ESJD, the less serial autocorrelation in the Markov chain samples. We also consider the effective sample size (ESS) normalized by time elapsed, which gives an indication of the sampling efficiency of each method. We use the implementation of ESS as given in \citet{arviz_2019}. We also consider the method of \citet{brofos2021numerical} for measuring the ergodicity of the Markov chain given i.i.d. samples. Under this procedure, we project the i.i.d. samples and the Markov chain samples along one-hundred random directions and measure the average value of the Kolmogorov-Smirnov statistics of these one-dimensional distributions. By the Cram\'{e}r-Wold theorem, the closer these Kolmogorov-Smirnov statistics are concentrated toward zero, the higher the fidelity between the Markov chain samples and the i.i.d. samples. In implementing the generalized leapfrog integrator (\cref{lagrangian-remarks:def:generalized-leapfrog}), we resolve the fixed point equations \cref{lagrangian-remarks:eq:generalized-leapfrog-momentum-i,lagrangian-remarks:eq:generalized-leapfrog-position} using fixed point iteration to a convergence tolerance of $1\times 10^{-6}$, with convergence measured in $\Vert\cdot\Vert_\infty$. \subsection{Demonstration of Second-Order Error}\label{lagrangian-remarks:subsec:second-order} \input{figures/second-order} We consider the following non-separable Hamiltonian $H(q, p) = \frac{q^2 p^2}{2}$, which describes geodesic motion in $\R$ when equipped with the metric $G(q) = 1 / q^2$. After converting from momentum to velocity $v_t = \frac{p_t}{q_t^2}$, we obtain the second-order differential equation $a_t = \frac{v_t^2}{q_t}$. Given initial conditions $q_0$ and $p_0$ (in the Hamiltonian formalism), the exact solution to this differential equation is $q_t = q_0 \exp(q_0 p_0 t)$ and $v_t = q_0^2p_0 \exp(q_0 p_0 t)$. If, as claimed, the Lagrangian integrator is indeed second-order, then it should exhibit third-order local error according to \cref{lagrangian-remarks:def:integrator-order}. We evaluate this by examing the squared error between the output of the numerical integrator and the analytical solution for a decreasing sequence of step-sizes $\epsilon$; that is, denoting the output of a single step of the Lagrangian integrator by $(\hat{q}_\epsilon,\hat{v}_\epsilon)$, we measure $\Vert \hat{q}_\epsilon - q_\epsilon\Vert_2^2 + \Vert \hat{v}_\epsilon - v_\epsilon\Vert_2^2$. We observe in \cref{lagrangian-remarks:fig:second-order-error} that this error decreases linearly on a log-log scale and, critically, the slope of this linear relation is three. This demonstrates numerically the third-order local error of the Lagrangian integrator and gives support to the claim that the method is of second-order accuracy. \subsection{Banana-Shaped Posterior Distribution} \input{figures/banana/banana} The banana-shaped distribution was proposed in \citet{rmhmc} by Cornebise and Julien as an example of Bayesian inference in non-identifiable models. In this example, a non-identifiable likelihood function in Bayesian linear regression is regularized according to a normal prior, the effect of which is to produce a density with symmetric, elongated tails. The generative model of this distribution is as follows: \begin{align} (\theta_1,\theta_2) &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(0, \sigma^2_\theta) \\ y_i \vert \theta_1,\theta_2 &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(\theta_1 + \theta_2^2, \sigma^2_y) ~~~~~ \mathrm{for}~~ i = 1,\ldots, n. \end{align} This distribution also illustrates a short-coming of the generalized leapfrog method. For large step-sizes, the implicit update to the momentum variable will not have a solution; therefore, the generalized leapfrog integrator is compelled to adopt a significantly smaller step-size than can be used even by the standard leapfrog method. Indeed, an advantage of explicit numerical integrators is that one does not need to fret that constituent update steps in the integrator will not have solutions. We seek to draw 1,000,000 samples from this posterior. In our experiments we set $\sigma^2_\theta = \sigma^2_y = 2$, $n = 100$, and set parameter values $\theta_1 = 1/2$ and $\theta_2 = \sqrt{1 - 1/2}$ for generating synthetic data. For HMC we use a step-size of $0.1$ and ten integration steps, which was found to produce an acceptance probability between eighty and ninety percent. As for the Riemannian metric, we adopt the sum of the Fisher information of the log-likelihood and the negative Hessian of the log-prior. For RMHMC, we use a step-size of $0.04$ and twenty integration steps, which produces an acceptance probability of around ninety percent. For LMC and ILMC, we use twenty integration steps with a step-size of $0.1$, which yields an acceptance probability of around ninety percent. These parameter configurations were found to produce reasonable Markov chains based on hand-tuning. Results showing the effective sample size (ESS) per second are provided in \cref{lagrangian-remarks:fig:banana}; we see that RMHMC struggles in this distribution, being even worse than ordinary HMC due to the requirement to use a small step-size. By contrast, LMC and ILMC do significantly better, with ILMC having the best ESS per second due to its elimination of two Jacobian determinant computations. We also show the distribution of this average value over ten trials for each sampling method. We find that the geometric methods based on the Lagrangian formalism perform similarly under this ergodicity measure and outperform competing methods. \subsection{Bayesian Logistic Regression} \input{figures/logistic-regression/logistic-breast} \input{figures/logistic-regression/logistic-thyroid} We consider Bayesian logistic regression on a breast cancer and a thyroid cancer dataset. The breast cancer dataset has 277 observations and ten covariates while the thyroid cancer dataset has 215 observations and six covariates. The Bayesian generative model is assumed to have the following form: \begin{align} \beta &\sim\mathrm{Normal}(0,\alpha^{-1} \mathrm{Id}) \\ y_i \vert \mathbf{x}_i, \beta &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Bernoulli}(\sigma(\mathbf{x}_i^\top\beta))~~~~~ \mathrm{for}~~ i = 1,\ldots, n, \end{align} where $\sigma : \R\to(0,1)$ denotes the sigmoid function. As the Riemannian metric, we adopt the sum of the Fisher information of the log-likelihood and the negative Hessian of the log-prior. We show in \cref{lagrangian-remarks:fig:logistic-breast,lagrangian-remarks:fig:logistic-thyroid} the minimum ESS per second, where we have also considered varying the convergence threshold used to solve fixed point iterations in RMHMC; as discussed in detail by \citet{brofos2021numerical}, implementations of RMHMC require that the implicit updates to momentum and position be resolved using an iterative procedure such as fixed point iteration or Newton's method. The tolerance in these numerical methods directly controls the degree to which reversibility and volume preservation are violated by the implementation of the generalized leapfrog method: For small values of the threshold, these theoretical properties are closely respected by the numerical method, while for large thresholds, violations occur. Reversibility and volume preservation imply detailed balance in HMC, and violations imply that the detailed balance may not hold in an implementation of RMHMC with large thresholds. By contrast, LMC and ILMC are fully explicit and detailed balance is respected to machine precision for either method. We observe that both sampling methods based on Lagrangian mechanics exhibit higher ESS per second than their counterpart based on the Hamiltonian formalism except for the largest thresholds (with the greatest bias); we refer the interested reader to \citet{brofos2021numerical} for a detailed discussion on the effects of the convergence threshold on the bias of the RMHMC Markov chain. Moreover, ILMC outperforms LMC on this metric. When comparing the ESJD, we observe that, consistent with our understanding in the Gaussian case, the ILMC method has the smallest expected distance traveled. However, this is offset by a faster sampling iteration due to only requiring two Jacobian determinant calculations instead of four. \subsection{Multiscale Student's $t$-Distribution}\label{lagrangian-remarks:subsec:student-t} \input{figures/t/t-5} \input{figures/t/t-5000} Multiscale distributions can be challenging for HMC since trajectories integrated by the leapfrog method will exhibit significant oscillations along directions of the distributions possessing the smallest spatial scale. To investigate this phenomenon, we consider sampling from a multivariate Student-$t$ distribution with a multiscale covariance; in particular we consider a distribution with density function, \begin{align} \pi(x) \propto \left[1 + \frac{1}{\eta} x^\top\Sigma^{-1}x\right]^{-(\eta + m)/2}, \end{align} where $x\in\R^m$, $\eta > 2$ is the degrees-of-freedom, and $\Sigma$ is the scale matrix. We consider scale matrices of the form $\Sigma = \mathrm{diag}(1, \ldots, 1, \sigma^2) \in \R^{m\times m}$. In our experiments we set $m=20$ and $\eta \in \set{5\times 10^0, 5\times 10^3}$ and consider multiscale distributions for $\sigma^2\in \set{1\times 10^1, 1\times 10^2,1\times 10^3, 1\times 10^4}$. We choose these two values of the degrees-of-freedom to demonstrate two distinct sampling behaviors. For the Riemannian methods, we consider a step-size of $0.7$ and twenty integration steps. As the Riemannian metric, we use the positive definite term in the negative Hessian of the log-density of the distribution. For $\nu = 5\times 10^0$, we observe that the ESJD is largest for RMHMC; this occurs because RMHMC enjoys a far superior acceptance probability in this scenario at 95\% whereas LMC and ILMC have acceptance probabilities of 40\% and 62\%, respectively. This degraded performance of the Lagrangian methods is then reflected in the time-normalized ESS, which shows RMHMC dominating LMC, ILMC, and HMC. For the case of $\eta = 5\times 10^3$, circumstances are more favorable to the Lagrangian methods, with ILMC exhibiting the best performance in terms of time-normalized ESS, with the LMC method giving the second best results. In terms of ESJD, we observe that ILMC moves less far in sample space than LMC, but that this is offset by the faster sampling. As in the case of the banana-shaped distribution, we may sample from this target density analytically in order to assess the ergodicity properties of the samplers. We find that the ergodicity of the geometric methods is essentially constant with respect to the multiscale parameter, whereas the performance of Euclidean HMC noticeably degenerates. For both $\nu = 5\times 10^3$ and $\nu = 5\times 10^0$, one observes that the performance of the geometric methods is essentially constant over the multiple scales of the target distribution, demonstrating the beneficial effect of capturing the geometry of the target. \subsection{Stochastic Volatility Model} \input{figures/stochastic-volatility/stochastic-volatility} We consider Bayesian inference in a stochastic volatility model. We consider the following generative model: \begin{align} \label{lagrangian-remarks:eq:stochastic-volatility-x} x_t\vert x_{t-1}, \phi,\sigma^2 &\sim\mathrm{Normal}(\phi x_{t-1}, \sigma^2) \\ \label{lagrangian-remarks:eq:stochastic-volatility-y} y_t \vert \beta, x_t &\sim \mathrm{Normal}(0, \beta^2\exp(x_t)) \end{align} for $t = 2,\ldots, T$ in \cref{lagrangian-remarks:eq:stochastic-volatility-x} and $t=1,\ldots, T$ in \cref{lagrangian-remarks:eq:stochastic-volatility-y} and with priors $x_1\sim \mathrm{Normal}(0, \sigma^2 / (1- \phi^2))$, $(\phi+1)/2\sim\mathrm{Beta}(20, 3/2)$, $1/\sigma^2\sim \xi^2(10, 1/20)$, and the prior over $\beta$ being proportional to $1/\beta^2$. Given $(y_1,\ldots, y_T)$, we seek to sample the posterior of $(x_1,\ldots, x_T, \phi, \beta, \sigma^2)$. We follow \citet{rmhmc} and employ a Metropolis-within-Gibbs-like alternating procedure for sampling the posteriors of $(x_1,\ldots, x_T)$ and $(\phi,\beta,\sigma^2)$. In our experiments we set $T=1,000$ and use values of $\phi=0.98$, $\beta=0.65$, and $\sigma^2 = 0.15^2$. For HMC, we use a step-size of 0.01 and fifty integration steps when sampling $(\phi,\beta,\sigma^2)$; for the geometric methods, we use a step-size of 0.5 and six integration steps. As for the Riemannian metric, we adopt the sum of the Fisher information of the log-likelihood and the negative Hessian of the log-prior. We compare the average ESS per second among the three latent variables $(\phi, \beta, \sigma^2)$ with results reported in \cref{lagrangian-remarks:fig:stochastic-volatility}. We find that LMC and ILMC are the strongest performing methods, with LMC having better ESS per second due to its more efficient traversal of the sample space. Indeed, ILMC has degraded performance in this example, owing to its greater autocorrelation, but nevertheless outperforms HMC and RMHMC. \subsection{Fitzhugh-Nagumo Model} \input{figures/fitzhugh-nagumo/fitzhugh-nagumo} We now investigate the LMC and RMHMC in the Fitzhugh-Nagumo posterior distribution. The Fitzhugh-Nagumo posterior distribution has the following generative model, \begin{align} (a, b , c) &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(0, 1) \\ \hat{r}_{t_k} &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(r_{t_k}, \sigma^2) \\ \hat{v}_{t_k} &\overset{\mathrm{i.i.d.}}{\sim} \mathrm{Normal}(v_{t_k}, \sigma^2) ~~~\mathrm{for}~k=1,\ldots, n, \end{align} where $t_1,\ldots, t_n$ are evenly spaced time points in $[0, 10)$ and $r_t$ and $v_t$ obey the differential equations, \begin{align} \dot{r}_t &= -\frac{v_t - a + b r_t}{c} \\ \dot{v}_t &= cv_t - \frac{cv_t^3}{3} + cr_t. \end{align} In our experiments we give initial conditions $v_0 = 1$, $r_0 = -1$, $\sigma^2 = 1/4$, and $n=200$. The objective is to infer the posterior of $q=(a,b,c)$ given observations $\set{(\hat{v}_{t_k}, \hat{r}_{t_k})}_{k=1}^{200}$. Here we emphasize a different aspect of the computation: its robustness to misspecification. As described in \cref{lagrangian-remarks:subsec:robustness}, the proof that the generalized leapfrog integrator is a volume-preserving transformation when used to integrate Hamiltonian vector fields is the symmetry of partial derivatives. We therefore consider the repercussions of an error in the implementation of partial derivatives that invalidates this requirement. To give further context to this experiment, we quote from \citet{dahlquist2003numerical}: ``In all numerical work, one must expect that clerical errors, errors in hand calculation, and misunderstandings will occur. [...] Most of the errors depend on the so-called human factor. [...] We take up these sources of error in order to emphasize that both the person who carries out a calculation and the person who guides the work of others can plan so that such sources of error are not damaging.'' It seems to us, therefore, that the robustness of a Markov chain procedure to human misspecification is a most desirable circumstance. As described in \citet{rmhmc}, computing the gradient of the log-posterior, the Riemannian metric, and the Jacobian of the Riemannian metric requires us to compute sensitivity equations of the form $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial r_t}{\partial q_i}$, $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial v_t}{\partial q_i}$, $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial^2 r_t}{\partial q_i \partial q_j}$, and $\frac{\mathrm{d}}{\mathrm{d}t} \frac{\partial^2 v_t}{\partial q_i \partial q_j}$ for $i=1,2, 3$ and $j=1,2,3$. We employ a Riemannian metric of the form, \begin{align} \mathbf{G}_{ij}(q) = \frac{1}{\sigma^2}\sum_{k=1}^{n} \paren{\frac{\partial v_{t_k}}{\partial q_i}\frac{\partial v_{t_k}}{\partial q_j} + \frac{\partial r_{t_k}}{\partial q_i}\frac{\partial r_{t_k}}{\partial q_j}} + \mathbf{1}\set{i=j}. \end{align} If any of these sensitivity equations are misspecified, then we will destroy the symmetry of partial derivatives required by the leapfrog integrator to preserve volume. However, the integrator used in LMC and ILMC is non-volume-preserving by design, and the appropriate volume correction is readily computable during sampling. We expect, therefore, that the volume correction employed in LMC and ILMC will provide robustness against these incorrectly computed quantities. We note that, in this case, there is no obvious mechanism by which to compute the required Jacobian determinant when the generalized leapfrog integrator is no longer a symplectic transformation. In \cref{lagrangian-remarks:fig:fitzhugh-nagumo} we show the minimum ESS per second and Kolmogorov-Smirnov statistics for sampling from the Fitzhugh-Nagumo posterior. We observe that LMC outperforms ILMC in this example, but that both Lagrangian methods outperform HMC and RMHMC. In terms of ergodicity, all methods perform similarly. When we introduce changes to the sensitivity equations, we observe that RMHMC's ergodicity severely degrades. For HMC, for which higher-order sensitivities are not required (because of the Euclidean metric), ergodicity is identical to the previous case. However, for LMC and ILMC, in which the higher-order sensitivities are required to compute the Christoffel symbols, the fact that the sensitivities have been incorrectly specified has not noticeably degraded ergodicity. This is a virtue of the LMC and ILMC Markov chains that they are more robust to human errors of this variety. \section{Conclusion} This work has examined the numerical integrator for Lagrangian Monte Carlo (LMC). Motivated by the observation that LMC requires four Jacobian determinant evaluations, mechanisms by which this number may be reduced were examined. By inverting the sequence of integration so that position, rather than velocity, is updated twice, the number of Jacobian determinant evaluations in each step was reduced from four to two while still maintaining a fully explicit method. Empirical evaluations of this method were provided to show several situations in which the proposed integration strategy enjoys the best time-normalized performance among several alternatives. Moreover, it has been demonstrated in this work that the local error of the Lagrangian leapfrog (and its inverted counterpart) is third order, which improves the previously known order. Additionally, an important robustness property was characterized that LMC possesses and an illustration wherein human error will invalidate stationarity in RMHMC but not in LMC was given. Methods of Bayesian inference that incorporate geometric understanding exhibit a pleasing aesthetic, yet they are burdened by numerical considerations -- among which are fixed points and cubic complexity -- that have limited their adoption. We hope that this research sparks renewed interest in mechanisms of improving these geometric methods. \bigskip \begin{center} {\large\bf SUPPLEMENTARY MATERIAL} \end{center}
{'timestamp': '2022-03-01T02:52:25', 'yymm': '2202', 'arxiv_id': '2202.13888', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13888'}
arxiv
\section{Introduction} The view of computation as functions is at the foundation of computer science: the Church-Turing thesis expresses the coincidence of different notions of computable function; programming with higher-order functions is now taken for granted. In contrast the view of computation as interaction is more recent and less settled, and often obscured by adherence to one syntax or another, perhaps each with its own mechanism of interaction. Whereas the basic mechanism of interaction of functions is clear---ultimately by function composition---a functional approach can struggle with quite the right way to approach computation which isn't simply from input to output. The literature includes approaches via lenses, optics, combs, containers, dependent lenses, dependent optics, open games and learners~\cite{oles,pierce,optics,Chiribella2008,containers,opengames,openlearners}. The difficulty is compounded by enrichments to, say, probabilistic, quantum or real-number computation. Undeniably there are many ingenious successes, especially through modifications of functions and their types. But fundamentally the functional view of computation originates in another computing era, unlike that today where interaction, unwanted or designed, is often the rule rather than the exception. By adopting a model which addresses interaction from the outset we can hope to understand and explore better the space of possibilities in computation, functional or otherwise. Our model is that of distributed/concurrent games and strategies: games represent types or constraints while strategies represent programs or computational processes, with interaction via the composition of strategies~\cite{lics11}. Through it we can show how many functional paradigms arise automatically by specialising games. This gives one reading of the title. But reasoning about interaction is technically challenging. So there's another reading too: that of taming concurrent computation, making it practicable by providing functional abstractions where possible. {\sl After the basics on event structures, the tools of stable families, and concurrent strategies, the new contribution comes in two parts which can roughly be described as: how to describe strategies by functions; and how to describe functions by strategies. The first, rather technical part, Section~\ref{sec:part1}, introduces a powerful method for lifting a very broad class of functions to strategies, turning functional into causal dependency. It makes essential use of stable families and the Scott order intrinsic to a concurrent game. The second part, Section~\ref{sec:part2}, concerns how causal dependency determines functional dependency, and shows how many paradigms discovered in making functions interactive arise as subcategories of concurrent games. } \section{Event structures} An {\em event structure}~\cite{evstrs} comprises $(E, \leq, {\rm Con})$, consisting of a set $E$ of {\em events} which are partially ordered by $\leq$, the {\em causal dependency relation}, and a nonempty {\em consistency} relation ${\rm Con}$ consisting of finite subsets of $E$. The relation $e'\leq e$ expresses that event $e$ causally depends on the previous occurrence of event $e'$; the consistency relation, those events which may occur together. We insist that the partial order is {\em finitary}, {\it i.e.} \begin{itemize} \item $[e]\coloneqq \set{e'}{e'\leq e}\hbox{ is finite for all } e\in E$\,, \end{itemize} and that consistency satisfies \begin{itemize} \item $\setof{e}\in{\rm Con} \hbox{ for all } e\in E$\,, \item $Y\subseteq X\in{\rm Con} \hbox{ implies }Y\in {\rm Con},\ \hbox{ and}$ \item $ X\in{\rm Con} \ \&\ e\leq e'\in X \hbox{ implies } X\cup\setof{e}\in{\rm Con}$\,. \end{itemize} There is an accompanying notion of state or history. A {\em configuration} is a, possibly infinite, subset $x\subseteq E$ which is: \begin{itemize} \item {\em consistent,} $X\subseteq x \ \&\ X \hbox{ is finite} \hbox{ implies } X\in{\rm Con}$\,; and \item {\em down-closed, } $ e'\leq e\in x \hbox{ implies } e' \in x$\,. \end{itemize} Two events $e, e'$ are called {\em concurrent} if the set $\setof{e,e'}$ is in ${\rm Con}$ and neither event is causally dependent on the other; then we write $e\mathbin{{\it co}} e'$. In games the relation of {\em immediate} dependency $e\rightarrowtriangle e'$, meaning $e$ and $e'$ are distinct with $e\leq e'$ and no event in between, plays a very important role. We write $[X]$ for the down-closure of a subset of events $X$. Write $\iconf E$ for the configurations of $E$ and $\conf E$ for its {\em finite configurations}. (Sometimes we shall need to distinguish the precise event structure to which a relation is associated and write, for instance, $\leq_E$, $\rightarrowtriangle_E$ or $\mathbin{{\it co}}_E$.) Let $E$ and $E'$ be event structures. A {\em map} of event structures $f:E\to E'$ is a partial function on events $f:E\rightharpoonup E'$ such that for all $x\in\iconf E$ its direct image $f x\in\iconf{E'}$ and $$ \hbox{if } e, e' \in x \hbox{ and } f(e) =f(e') \hbox{ (with both defined)}, \hbox{ then } e=e'\,. $$ Maps of event structures compose as partial functions. Notice that for a {\em total} map $f$, {\it i.e.}~when the function $f$ is total, the condition on maps says it is {\em locally injective}, in the sense that w.r.t.~any configuration $x$ of the domain the restriction of $f$ to a function from $x$ is injective; the restriction of total $f$ to a function from $x$ to $f x$ is thus bijective. Although a map $f:E\to E'$ of event structures does not generally preserve causal dependency, it does reflect causal dependency locally: whenever $e, e'\in x$, a configuration of $E$, and $f(e)$ and $f(e')$ are both defined with $f(e')\leq f(e)$, then $e'\leq e$. Consequently, $f$ preserves the concurrency relation: if $e\mathbin{{\it co}} e'$ in $E$ then $f(e)\mathbin{{\it co}} f(e')$, when defined. A total map of event structures is {\em rigid} when it preserves causal dependency. Rigid maps induce discrete fibrations: \begin{proposition} A total map $f:E\to E'$ of event structures is rigid iff for all $x\in\fconf E$ and $y\in\fconf{E'}$, $$ y\subseteq f x \implies \exists z\in\fconf{E}.\ z\subseteq x \hbox{ and } f z = y\ . $$ The configuration $z$ is necessarily unique by local injectivit . \end{proposition} \section{Stable familie } In a ``prime'' event structure, defined above, an event $e$ has a unique causal history, the prime configuration $[e]$. Constructions directly on such event structures can be unwieldy, as often an event is more immediately associated with several mutually inconsistent causal histories. In this case the broader model of stable families is apt, especially so, as any stable family yields an event structure~\cite{icalp82,evstrs}. A subset $X$ of a family of sets ${\mathcal F}$ is {\em compatible} if there is an element of ${\mathcal F}$ which includes all elements of $X$; we say $X$ is {\em finitely compatible} if every finite subset of $X$ is compatible. \\ % A {\em stable family} is a non-empty family of sets ${\mathcal F}$ which is\\ $\bullet$ {\em Complete:} $\forall Z\subseteq{\mathcal F}. \ \hbox{if } Z\hbox{ is finitely compatible, } \bigcup Z \in {\mathcal F}$\,;\\ $\bullet$ {\em Stable:} $ \forall Z\subseteq{\mathcal F}.\ Z\not= \emptyset \ \& \ Z\hbox{ is compatible } \implies \bigcap Z\in {\mathcal F}$;\\ $\bullet$ {\em Finitary:} $ \forall x \in{\mathcal F}, e\in x\exists x_0\in{\mathcal F}.\ x_0 \hbox{ is finite }\ \&\ e\in x_0\subseteq x$; \\%and $\bullet$ {\em Coincidence-free:} For all $x \in {\mathcal F}$, $ e, e' \in x$ with $e \not= e'$, $$ \exists x_0 \in {\mathcal F}. \ x_0 \subseteq x \ \& \ (e\in x_0 \iff e' \notin x_0)\, .$$ We call elements of ${\mathcal F}$ its {\em configurations}, $\bigcup{\mathcal F}$ its {\em events} and write ${\mathcal F}^o$ for its {\em finite configurations}. A {\em map} $f:{\mathcal F}\to \G$ between stable families ${\mathcal F}$ and $\G$ is a partial function $f$ from the events of ${\mathcal F}$ to those of $\G$ such that for all $x\in{\mathcal F}$ its direct image $f x\in\G$ and if $e, e' \in x$ and $f(e) =f(e')$ then $e=e'$. The choice of map ensures an inclusion functor from the category of event structures to that of stable families. The inclusion functor has a right adjoint $\Pr$ giving a coreflection (an adjunction with unit an isomorphism). The construction $\Pr({\mathcal F})$ essentially replaces the original events of a stable family ${\mathcal F}$ by the minimal, prime configurations at which they occu . Let $x$ be a configuration of a stable family ${\mathcal F}$. Define the {\em prime} configuration of $e$ in $x$ by $$[ e ]_x \coloneqq \hbox{$\bigcap$} \set{y\in {\mathcal F}}{ e\in y \ \& \ y\subseteq x}\ . $$ By coincidence-freeness, the function $\max:\iconf{\Pr({{\mathcal F}})}\to {\mathcal F}$ which takes a prime configuration $[e]_x$ to $e$ is well-defined; it is the counit of the adjunction~\cite{icalp82,evstrs}. \begin{proposition}\label{prop:Pr} Let ${\mathcal F}$ be a stable family. Then, $\Pr({\mathcal F}) \coloneqq (P, {\rm Con}, \leq)$ is an event structure where $$ \eqalign{ &P= \set{[ e ]_x }{e\in x\ \&\ x\in {\mathcal F}}\ ,\cr & Z \in {\rm Con} \hbox{ iff } Z \subseteq P \ \&\ \hbox{$\bigcup$} Z \in{\mathcal F}\ \hbox{ and},\cr & p\leq p' \hbox{ iff } p, p'\in P\ \&\ p\subseteq p'\,.} $$ There is an order isomorphism $\theta: (\iconf{\Pr({\mathcal F})},\subseteq) \cong ({\mathcal F}, \subseteq)$ where $\theta(y)\coloneqq\max\, y = \bigcup y$ for $y\in \iconf{\Pr({{\mathcal F}})} ; its mutual inverse is $\varphi$ where $\varphi(x) = \set{[e]_x}{e\in x}$ for $x\in{\mathcal F}$. \end{proposition} The partial orders represented by configurations under inclusion are the same whether for event structures or stable families. They are G\'erard Berry's {\em dI-domains}~\cite{berry,icalp82,evstrs}. \subsection{Hiding---the defined part of a map} Let $(E,\leq, {\rm Con})$ be an event structure. Let $V\subseteq E$ be a subset of `visible' events. Define the {\em projection} on $V$, by $ E{\mathbin\downarrow} V\coloneqq (V, \leq_V, {\rm Con}_V) $, where $v \leq_V v' \hbox{ iff } v\leq v' \ \&\ v,v'\in V$ and $X\in{\rm Con}_V \hbox{ iff } X\in{\rm Con}\ \&\ X\subseteq V$. The operation {\em hides} all events outside $V$. It is associated with a {\em partial-total factorization system}. Consider a partial map of event structures $f:E\rightharpoonup E'$. Let $$V\coloneqq \set{e\in E}{ f(e) \hbox{ is defined}}\,.$$ Then $f$ clearly factors into the composition $$ \xymatrix{ E\ar@^{->}[r]^{f_0}& E{\mathbin\downarrow} V \ar[r]^{f_1}& E'\\} $$ of $f_0$, a partial map of event structures taking $e\in E$ to itself if $e\in V$ and undefined otherwise, and $f_1$, a total map of event structures acting like $f$ on $V$. Note that any $x\in \iconf{E{\mathbin\downarrow} V}$ is the image under $f_0$ of a {\em minimum} configuration, {\it viz.}~$[x]_E\in\iconf E$. We call $f_0$ a {\em projection} and $f_1$ the {\em defined part} of the map $f$. \subsection{Pullbacks} The coreflection from event structures to stable families is a considerable aid in constructing limits in the former from limits in the latter. The {\em pullback} of total maps of event structures is essential in composing strategies. We can define it via the pullback of stable families, obtained as a stable family of {\em secured bijections}. Let $\sigma:S\to B$ and $\tau:T\to B$ be total maps of event structures. There is a composite bijection $$ \theta: x\cong \sigma x = \tau y \cong y\,, $$ between $x\in\iconf S$ and $y\in \iconf T$ such that $\sigma x = \tau y$; because $\sigma$ and $\tau$ are total they induce bijections between configurations and their image. The bijection is {\em secured} when the transitive relation generated on $\theta$ by $(s, t) \leq (s', t')$ if $s\leq_S s'$ or $t\leq_T t'$ is a finitary partial order. \begin{theorem} Let $\sigma:S\to B$, $\tau:T\to B$ be total maps of event structures. The family $\mathcal R$ of secured bijections between $x\in\conf S$ and $y\in \conf T$ such that $\sigma x = \tau y$ is a stable family. The functions $\pi_1: \Pr({\mathcal R})\to S$, $\pi_2:\Pr({\mathcal R})\to T$, taking a secured bijection with top to, respectively, the left and right components of its top, are maps of event structures. % $ \Pr({\mathcal R})$ with $\pi_1$, $\pi_2$ is the pullback of $\sigma$, $\tau$ in the category of event structures. \end{theorem} \begin{notation}{\rm W.r.t.~$\sigma:S\to B$ and $\tau:T\to B$, define $x\wedge y$ to be the configuration of their pullback which corresponds via this isomorphism to a secured bijection between $x\in\iconf S$ and $y\in \iconf T$, necessarily with $\sigma x = \tau y$; any configuration of the pullback takes the form $x\wedge y$ for unique $x$ and $y$. } \end{notation} \section{Concurrent games and strategies} The driving idea is to replace the traditional role of game trees by that of event structures. Both games and strategies will be represented by {\em event structures with polarity}, which comprise $(A,{\it pol}_A)$ where $A$ is an event structure and a polarity function ${\it pol}_A:A\to \{+,-,0\}$ ascribing a polarity + (Player) or $-$ (Opponent) or 0 (neutral) to its events. The events correspond to (occurrences of) moves. It will be technically useful to allow events of neutral polarity; they arise, for example, in a play between a strategy and a counterstrategy. Maps are those of event structures which preserve polarity. A {\em game }is represented by an event structure with polarities restricted to + or $-$, with no neutral events. \begin{definition}\label{def:scottorder} {\rm In an event structure with polarity, with configurations $x$ and $y$, write $x \subseteq^-y$ to mean inclusion in which all the intervening events are Opponent moves. Write $x \subseteq^+ y$ for inclusion in which the intervening events are neutral or Player moves. For a subset of events $X$ we write $X^+$ and $X^-$ for its restriction to Player and Opponent moves, respectively. The {\em Scott order} will play a central role: between $x,y\in\iconf A$, where $A$ is a game, it is characterised by \\ \hbox{\ }\qquad\qquad\quad$ y\sqsubseteq_A x \iff y^-\supseteq x^-\ \&\ y^+\subseteq x^+\,. $ } \end{definition} There are two fundamentally important operations on games. One is that of forming the {\em dual game}. On a game $A$ this amounts to reversing the polarities of events to produce the dual $A^\perp$. The other operation, a {\em simple parallel composition} $A{\mathbin{\parallel}} B$, is achieved on games $A$ and $B$ by simply juxtaposing them, ensuring a finite subset of events is consistent if its overlaps with the two games are individually consistent; any configuration $x$ of $A{\mathbin{\parallel}} B$ decomposes into $x_A{\mathbin{\parallel}} x_B$ where $x_A$ and $x_B$ are configurations of $A$ and $B$ respectively. A {\em strategy} {\em in} a game $A$ is a total map $\sigma: S \to A$ of event structures with polarity~such that \noindent {(i)} if $\sigma x \subseteq^- y$, where $x\in\iconf S$ and $y\in\iconf A$, there is a unique $x'\in\iconf S$ with $x\subseteq x'$ and $\sigma x' = y$; \noindent {(ii)} if $s\rightarrowtriangle_S s'$ \ \&\ (${\it pol}(s) = +$ or ${\it pol}(s') = -$ )\,, \ \ $ \sigma(s)\rightarrowtriangle_A \sigma(s')$. \noindent The conditions prevent Player from constraining Opponent’s behaviour beyond the constraints of the game. Condition (i) is {\em receptivity}, ensuring that the strategy is open to all moves of Opponent permitted by the game. Condition (ii), called {\em innocence} in~\cite{FP}, ensures that the only additional immediate causal dependencies a strategy can enforce beyond those of the game are those in which a Player move awaits moves of Opponent. A map $f:\sigma \Rightarrow \sigma'$ of strategies $\sigma:S\to A$ and $\sigma' :S' \to A$ is a map $f:S\to S'$ such that $\sigma=\sigma'f$; this determines when strategies are isomorphic. Following~\cite{conway, joyal}, a {\em strategy from} a game $A$ {\em to} a game $B$ is a strategy in the game $A^\perp {\mathbin{\parallel}} B$. The conditions of receptivity and innocence precisely ensure that the copycat strategy behaves as identity w.r.t.~composition, presented below~\cite{lics11}. \subsection{Copycat} Let $A$ be a game. The copycat strategy $\ c\!c\,_A:{\rm C\!\!C}_A\to A^\perp{\mathbin{\parallel}} A$ is an instance of a strategy from $A$ to $A$. The event structure ${\rm C\!\!C}_A$ is based on the idea that Player moves in one component of the game $A^\perp{\mathbin{\parallel}} A$ always copy corresponding moves of Opponent in the other component. For $c \in A^\perp{\mathbin{\parallel}} A$ we use $\bar c$ to mean the corresponding copy of $c$, of opposite polarity, in the alternative component. The event structure ${\rm C\!\!C}_A$ comprises $A^\perp{\mathbin{\parallel}} A$ with extra causal dependencies $\bar c\leq c$ for all events $c$ with ${\it pol}_{A^\perp{\mathbin{\parallel}} A}(c) = +$; with the original causal dependency they generate a partial order; a finite subset is consistent in ${\rm C\!\!C}_A$ iff its down-closure w.r.t. $\leq$ is consistent in $A^\perp{\mathbin{\parallel}} A$. The map $\ c\!c\,_A$ acts as the identity function. In characterising the configurations of ${\rm C\!\!C}_A$ we recall the Scott order of Def ~\ref{def:scottorder}. % \begin{lemma}\label{lem:CCbel} Let $A$ be a game. Let $x\in\iconf{A^\perp}$ and $y\in\iconf A$, \\ \hbox{\ } \qquad \qquad \qquad\qquad $x{\mathbin{\parallel}} y \in\iconf{{\rm C\!\!C}_A} \ \hbox{ iff }\ y \sqsubseteq_A x\,.$ \\ \end{lemma} % \subsection{Composition} Two strategies $\sigma:S\to A^\perp{\mathbin{\parallel}} B$ and $\tau:T\to B^\perp {\mathbin{\parallel}} C$ compose via pullback and hiding, summarised below. $$\small\xymatrix@R=12pt@C=10pt{ &\ar[dl]_{\pi_1 }T\sncirc S \ar@^{-->}[rr] \ar@{..>}[dd]|{\tau\sncirc\sigma} \pb{270}\ar[dr]^{\pi_2 }& & T{{\odot}} S \ar@{-->}[dd]^{\tau{{\odot}} \sigma}\\ S{\mathbin{\parallel}} C\ar[dr]_{\sigma{\mathbin{\parallel}} C}&&\ar[dl]^{A{\mathbin{\parallel}} \tau}A{\mathbin{\parallel}} T\\ &A{\mathbin{\parallel}} B{\mathbin{\parallel}} C\ar@^{->}[rr]& &A{\mathbin{\parallel}} C}$$ Ignoring polarities, by forming the pullback of $\sigma{\mathbin{\parallel}} C$ and $A{\mathbin{\parallel}} \tau$ we obtain the synchronisation of complementary moves of $S$ and $T$ over the common game $B$; subject to the causal constraints of $S$ and $T$, the effect is to instantiate the Opponent moves of $T$ in $B^\perp$ by the corresponding Player moves of $S$ in $B$, and {\it vice versa}. Reinstating polarities we obtain the {\em interaction} of $\sigma$ and $\tau$ $$ \tau\sncirc \sigma: T\sncirc S \to A^\perp {\mathbin{\parallel}} B^0 {\mathbin{\parallel}} C\,, $$ where we assign neutral polarities to all moves in or over $B$. Neutral moves over the common part $B^0$ remain unhidden. The map $A^\perp {\mathbin{\parallel}} B^0{\mathbin{\parallel}} C\rightharpoonup A^\perp{\mathbin{\parallel}} C$ is undefined on $B^0$ and otherwise mimics the identity. Pre-composing this map with $\tau\sncirc \sigma$ we obtain a partial map $T\sncirc S\rightharpoonup A^\perp{\mathbin{\parallel}} C$; it is undefined on precisely the neutral events of $T\sncirc S$. The defined parts of its partial-total factorization yields $$\tau{{\odot}} \sigma: T{{\odot}} S\to A^\perp{\mathbin{\parallel}} C\,;$$ this is the {\em composition} of $\sigma $ and $\tau$. \begin{notation}{\rm For $x\in\iconf S$ and $y\in\iconf T$, let $\sigma x = x_A{\mathbin{\parallel}} x_B$ and $\tau y = y_B{\mathbin{\parallel}} y_C$ where $x_A\in \iconf A$, $x_B, y_B\in\iconf B$, $y_C\in\iconf C$. Define $ y\sncirc x = (x{\mathbin{\parallel}} y_C) \wedge (x_A{\mathbin{\parallel}} y) $. This is a partial operation only defined if the $\wedge$-expression is. It glues configurations $x$ and $y$ together at their common overlap over $B$, if $x_B=y_B$ and a finitary partial order of causal dependency results. Any configuration of $T\sncirc S$ has the form $ y\sncirc x $, for unique $x\in\iconf S, y\in\iconf T$. } \end{notation} \subsection{A bicategory of strategies} We obtain a bicategory ${\mathbf{Strat}}$ for which the objects are games, the arrows $\sigma: A\profto B$ are strategies $\sigma:S\to A^\perp{\mathbin{\parallel}} B$; with 2-cells $f:\sigma \Rightarrow \sigma'$ maps of strategies. The vertical composition of 2-cells is the usual composition of maps. Horizontal composition is the composition of strategies ${{\odot}}$ (which extends to a functor via the universality of pullback and partial-total factorisation). We can restrict the 2-cells to be rigid maps and still obtain a bicategory. The bicategory of strategies is compact-closed, though with the addition of winning conditions---Section~\ref{sec:winningcond}---this weakens to $*$-autonomous. A strategy $\sigma:S\to A$ is {\em deterministic} if $S$ is deterministic, {\it viz.} $$ \forall X\subseteq_{\rm fin} S.\ [X]^-\in {\rm Con}_S \implies X\in{\rm Con}_S\,, $$ where $[X]^- \coloneqq \set{s'\in S}{\exists s\in X.\ {\it pol}_S(s')=- \ \&\ s'\leq s}$. So, a strategy is deterministic if consistent behaviour of Opponent is answered by consistent behaviour of Player. Copycat $\ c\!c\,_A$ is deterministic iff the game $A$ is {\em race-free}, {\it i.e.}~if $x\subseteq^- y$ and $x\subseteq^+ z$ in $\iconf A$ then $y\cup z\in \iconf A$. The bicategory of strategies restricts to a bicategory of deterministic strategies between race-free games. There are several ways to reformulate strategies. Deterministic strategies coincide with the {\em receptive} ingenuous strategies of Melli\`es and Mimram based on asynchronous transition systems~\cite{Asgames,DBLP:journals/fac/Winskel12}. Via the Scott order, we can see strategies as a refinement of profunctors: a strategy in a game $A$ induces a discrete fibration, so presheaf, on $(\conf A, \sqsubseteq_A)$, a construction which extends to strategies between games~\cite{fossacs13}. \subsection{Winning conditions}\label{sec:winningcond} {\em Winning conditions} of a game $A$ specify a subset of its configurations $W$, an outcome in which is a win for Player. Informally, a strategy (for Player) is {\em winning} if it always prescribes moves for Player to end up in a winning configuration, no matter what the activity or inactivity of Opponent. Formally, a game with winning conditions $(A, W_A)$ comprises a concurrent game $A$ with winning conditions $W_A\subseteq \iconf A$. A strategy $\sigma:S\to A$ is {\em winning} if $\sigma x$ is in $W_A$ for all +-maximal configurations $x$ of $S$; in general, a configuration is +-maximal if no additional Player, or neutral, moves can occur from it. That $\sigma$ is winning can be shown equivalent to: all plays of $\sigma$ against any counterstrategy of Opponent result in a win for Player~\cite{lics12,ecsym-notes}. As the dual of a game with winning conditions $(A, W_A)$ we again reverse the roles of Player and Opponent, and take its winning conditions to be the set-complement of $W_A$, {\it i.e.}~$(A,W_A)^\perp = (A^\perp, \iconf A \setminus W_A)$. In a parallel composition of games with winning conditions, we deem a configuration winning if its component in either game is winning: $(A, W_A) {\mathbin{\parallel}} (B, W_B) \coloneqq (A{\mathbin{\parallel}} B, W)$ where $W= \set{x\in\iconf{A{\mathbin{\parallel}} B}}{x_A\in W_A \hbox{ or } x_B \in W_B}$. With these extensions, we take a winning strategy from a game $(A,W_A)$ to a game $(B,W_B)$, to be a winning strategy in the game $A^\perp{\mathbin{\parallel}} B$. When games are race-free, copycat will be a winning strategy. The composition of winning strategies is winning~\cite{lics12,ecsym-notes}. In the proof the following lemma is critical: \begin{lemma}\label{lem:+max} For strategies $\sigma:S\to A^\perp {\mathbin{\parallel}} B$, $\tau:T\to B^\perp{\mathbin{\parallel}} C$, $y\sncirc x\in \iconf{T\sncirc S}$ is +-maximal iff $x$ and $y$ are +-maximal. \end{lemma} One can extend winning conditions to payoff functions~\cite{payoff} or to allow draws, where neither player wins~\cite{dexter}. \subsection{Imperfect information} In a game of {\em imperfect information} some moves are masked, or inaccessible, and strategies with dependencies on unseen moves are ruled out. One can extend games with imperfect information in a way that respects the operations of concurrent games and strategies~\cite{dexter}. Each move of a game is assigned a level in a global order of access levels; moves of the game or its strategies can only causally depend on moves at equal or lower levels. In more detail, a fixed preorder of {\em access levels} $(\Lambda, \preceq)$ is pre-supposed. A {\em $\Lambda$-game}, comprises a game $A$ with a {\em level function} $l:A\to \Lambda$ such that if $a\leq_A a' $ then $ l(a)\preceq l(a') $ for all moves $a, a'$ in $A$. A {\em $\Lambda$-strategy} in the $\Lambda$-game is a strategy $\sigma:S\to A$ for which if $ s\leq_S s' $ then $l\sigma(s) \preceq l\sigma(s') $ for all $s, s'$ in $S$. The access levels of moves in a game are left undisturbed in forming the dual and parallel composition of $\Lambda$-games. As before a $\Lambda$-strategy from a $\Lambda$-game $A$ to a $\Lambda$-game $B$ is a $\Lambda$-strategy in the game $A^\perp{\mathbin{\parallel}} B$. It can be shown that $\Lambda$-strategies compose~\cite{dexter}. \subsection{A language for strategies} We recall briefly the language for strategies introduced in~\cite{stratasproc}. Games $A, B, C, \cdots$ play the role of types. Operations on games include forming the dual $A^\perp$, simple parallel composition $A{\mathbin{\parallel}} B$, a sum $\Sigma_{i\in I} A_i$ as well as recursively-defined games. Terms, denoting strategies, have typing judgement \begin{center}$ x_1:A_1, \cdots, x_m:A_m \vdash\ t \ \dashv y_1:B_1, \cdots, y_n:B_n\ , $ \end{center} where all the variables are distinct, interpreted as a strategy from $\vec A= A_1 {\mathbin{\parallel}} \cdots {\mathbin{\parallel}} A_m$ to $\vec B= B_1 {\mathbin{\parallel}} \cdots {\mathbin{\parallel}} B_n$. We can think of the term $t$ as a box with input and output wires for the variables $\vec x$ and $\vec y$. The term $t$ denotes a strategy $\sigma: S\to \vec A^\perp {\mathbin{\parallel}} \vec B$. It does so by describing witnesses, configurations of $S$, to a relation between configurations $\vec x$ of $\vec A$ and $\vec y$ of $\vec B$. For example, the term \\ \hbox{\ }\qquad\qquad\qquad\qquad $x:A \vdash y\sqsubseteq_A x \dashv y:A$ \\ denotes the copycat strategy on a game $A$; it describes configurations of copycat, ${\rm C\!\!C}_A$, as witnesses, {\it viz.}~ those configurations $x{\mathbin{\parallel}} y$ of ${\rm C\!\!C}_A$ for which $y\sqsubseteq_A x$ in the Scott order. There are other operations, such as sum $\mathop{[\!]}$ and pullback $\wedge$ on strategies of the same type. \noindent Duality is caught by the rules $$ \pfrule{\Gamma, x:A \vdash t \dashv \Delta}{ \Gamma \vdash t \dashv x:{A}^\perp, \Delta} \qquad \pfrule{\Gamma \vdash t \dashv x:A, \Delta}{ \Gamma, x: {A}^\perp \vdash t \dashv \Delta} $$ and composition of strategies by $$ \pfrule{{\Gamma \vdash t \dashv \Delta \qquad \Delta \vdash u \dashv {\rm H}} }{\Gamma \vdash \stcomp\Delta t u \dashv {\rm H}} $$ which, in the picture of strategies as boxes, joins the output wires of one strategy to input wires of the other. Simple parallel composition of strategies arises when $\Delta$ is empty. \section{From functions to strategies}\label{sec:part1} The language for strategies in~\cite{stratasproc} included a judgement $$ x:A \vdash g (y) \sqsubseteq_{C} f (x) \dashv y:B $$ for building strategies out of expressions $f(x)$ and $g(y)$ denoting ``affine functions.'' It breaks down into a composition $$ x:A \vdash \stcomp{z:C }{ g (y)\sqsubseteq_C z}{ z\sqsubseteq_{C} f (x) } \dashv y:B\,. $$ Here we present a considerably broader class of affine-stable functions $f$ and ``co-affine-stable'' functions $g$ with which to define strategies in this manner. It hinges on the Scott order to convert functional dependency to causal dependency. \subsection{Affine-stable maps and their strategies}\label{sec:affstab} \begin{definition}\label{def:affine-stable}{\rm An {\em affine-stable map} between games from $A$ to $B$, is a function $f: \iconf A \to \iconf B$ which is\\ $\bullet$ {\em polarity-respecting:} for $x, y\in\iconf A$, $$ x\subseteq^- y\Rightarrow f(x)\subseteq^- f(y) \ \hbox{ and } \ x\subseteq^+ y\Rightarrow f(x)\subseteq^+ f(y)\,; $$ $\bullet$ {\em +-continuous:} for $x\in\iconf A$, $$ b\in f(x) \ \&\ {\it pol}_B(b) = + \Rightarrow \exists x_0\in\conf A.\ x_0\subseteq x\ \&\ b\in f(x_0)\,; $$ $\bullet$ {\em $-$-image finite:} for all finite configurations $ x\in\conf A$ the set $ f(x)^-$ is finite; \\ $\bullet$ {\em affine:} for all compatible families $\set{x_i}{i\in I}$ in $ \iconf A$, $$ \hbox{$\bigcup$}_{i\in I} f (x_i) \subseteq^+ f( \hbox{$\bigcup$}_{i\in I} x_i)\, $$ ---when $I$ is empty this amounts to $\emptyset \subseteq^+ f(\emptyset)$; and \\ $\bullet$ {\em stable:} for all compatible families $\set{x_i}{i\in I}\neq \emptyset$ in $ \iconf A$, $$ f( \hbox{$\bigcap$}_{i\in I} x_i) \subseteq^- \hbox{$\bigcap$}_{i\in I} f ( x_i)\,. $$ }\end{definition} When all the moves of games $A$ and $B$ are those of Player, the definition reduces to that of stable function. If all moves are those of Opponent, it becomes that of demand maps---see Section~\ref{sec:stabspans}~\cite{Visions}. Affine-stable maps include maps of event structures with polarity, including partial maps between games, and the affine maps of~\cite{stratasproc}. They are the most general maps out of which we can construct a strategy as follows: \begin{theorem}\label{thm:affstmaptostrats} Let $f: \iconf A \to \iconf B$ be an affine-stable map between games $A$ and $B$. Then $$ {\mathcal F} \coloneqq \set{ x{\mathbin{\parallel}} y\in \iconf{A^\perp{\mathbin{\parallel}} B}}{y\sqsubseteq_B f(x)} $$ is a stable family. The map $\max:\Pr({\mathcal F})\to A^\perp{\mathbin{\parallel}} B$ is a strategy $f_!:A\profto B$. The strategy $f_!$ is deterministic if $A$ and $B$ are race-free and $f$ reflects $-$-compatibility, {\it i.e.}~$x\subseteq^- x_1$ and $x\subseteq^- x_2$ in\, $\iconf A$ and $f x_1 \cup f x_2\in \iconf B$ implies $x_1\cup x_2\in \iconf A$. \end{theorem} For $f$ an affine-stable map from $A$ to $B$ we can write $f_!$ as $$ x:A \vdash y \sqsubseteq_{B} f(x) \dashv y:B\,. $$ Through suitable $f$ we can create strategies from structural maps, injections and projections as strategies, for conditional and case statements and, generally, much of the causal wiring that is often explained informally in diagrammatic reasoning. If $\sigma$ is a strategy in $A$ then $f_!{{\odot}} \sigma$ is its ``pushforward'' to a strategy in $B$. Some basic examples: \begin{example}\label{ex:projection}{\rm ({\it Projectors}) Let $f:A{\mathbin{\parallel}} B \to B$ be the function undefined on game $A$ but acting as identity on game $B$. Let $\sigma$ be a strategy in the game $A{\mathbin{\parallel}} B$. The strategy $f_!{{\odot}} \sigma$ is its projection to a strategy in $B$. }{\hspace*{\fill}\hbox{$\Box$}}\end{example} \begin{example}\label{ex:duplication}{\rm ({\it Duplicators}) Let $A$ be a game. Consider the function $d_A: x\mapsto x{\mathbin{\parallel}} x$ from $\iconf A$ to $\iconf{A{\mathbin{\parallel}} A}$. It is easily checked to be affine-stable. Hence there is a {\em duplicator} strategy $\delta_A={d_A}_!: A\profto A{\mathbin{\parallel}} A$. (The strategy $\delta_A$ is not natural in $A$ as ${\mathbin{\parallel}}$ is not a product, except in subcategories.) }{\hspace*{\fill}\hbox{$\Box$}}\end{example} \begin{example}\label{ex:detector}{\rm {\it (Detectors)} Let $A$ be a game. Let $X\in{\rm Con}_A$ with $X\subseteq A^+$. Let $\oplus$ be a single ``detector'' event, of +ve polarity. Let $$ d_X:\iconf A \to \iconf\oplus $$ be the function such that $$ d_X(x) = \begin{cases} \oplus & \hbox{ if } X\subseteq x\,,\\ \emptyset & \hbox{ otherwise. } \end{cases} $$ The function $d_X$ is affine-stable. There is a {\em detector} strategy $$ {d_X}_!: A \profto \oplus\,. $$ The strategy simply adjoins extra causal dependencies $a\rightarrowtriangle \oplus$ from $a\in X$. It detects the presence of $X$. In a similar way, one can extend detectors to detect the occurrence of one of a family $\langle X_i\rangle_{i\in I}$ of $X_i\in{\rm Con}_A$ provided $ X_i\cup X_j \in {\rm Con}_A \implies i=j $ for $i,j\in I$. }{\hspace*{\fill}\hbox{$\Box$}}\end{example} \begin{example}\label{ex:inhibitor}{\rm ({\it Blockers}) Let $A$ be a game and $Y\subseteq A^-$. Let $$ h_Y : \iconf A \to \iconf\ominus $$ be the function which acts so $$ h_Y(x) = \begin{cases}\ominus &\hbox{ if } x\cap Y\neq \emptyset\,,\\ \emptyset & \hbox{ otherwise.} \end{cases} $$ $h_Y$ is a map of event structures so affine-stable. The {\em blocker} strategy ${h_Y}_!$ adjoins causal dependencies $\ominus \rightarrowtriangle a$ from $\ominus$ to each $a\in Y$. The absence of move $\ominus$ blocks all moves $Y$. }{\hspace*{\fill}\hbox{$\Box$}}\end{example} \begin{theorem}\label{thm:functor} The operation $(\_)_!$ is a (pseudo) functor from the category of affine-stable maps to concurrent strategies ${\mathbf{Strat}}$. \end{theorem} \subsection{co-Affine-stability} We examine the dual, or co-notion, to affine-stability. An affine-stable map $f$ from $A^\perp$ to $B^\perp$ yields a strategy $f_!: A^\perp\profto B^\perp$, so by duality a strategy $f^*:B\profto A$. We obtain the dual to Theorems~\ref{thm:affstmaptostrats},\ref{thm:functor} as a corollary: \begin{corollary} Let $g:\iconf A\to \iconf B$ be such that $g:\iconf{A^\perp}\to \iconf{B^\perp}$ is affine-stable, then $$ {\mathcal G} \coloneqq \set{y{\mathbin{\parallel}} x\in \iconf{B^\perp{\mathbin{\parallel}} A}}{g(x)\sqsubseteq_B y} $$ is a stable family. The map $\max:\Pr({\mathcal G})\to B^\perp{\mathbin{\parallel}} A$ is a strategy $g^*:B\profto A$. The strategy $g^*$ is deterministic if $A$ is race-free and $g$ reflects $+$-compatibility. The operation $(\_)^*$ is a contravariant (pseudo) functor from the category of affine-stable maps to ${\mathbf{Strat}}$. \end{corollary} For $g$ an affine-stable map from $A^\perp$ to $B^\perp$ we can write $g^*$ as $$ y:B \vdash g (y) \sqsubseteq_{B} x \dashv x:A\,. $$ For a strategy $\sigma$ in game $B$ the operation $g^*{{\odot}} \sigma$ yields the strategy in $A$ got as the pullback of $\sigma$ along $g$. In particular, if $A$ prefixed game $B$ by some initial move, $g^*{{\odot}} \sigma$ would be a prefix operation on strategies. \subsection{An adjunction}\label{sec:adjn} An affine-stable map $f$ from $A$ to $B$ is not generally an affine-stable map from $A^\perp$ to $B^\perp$. The next definition, of an {\em additive-stable} map $f$ from $A$ to $B$, bluntens affine-stability to ensure $f$ is also a additive-stable map from $A^\perp$ to $B^\perp$; and hence is associated with both a strategy $ f_!:A\profto B $ and a converse strategy $ f^*:B\profto A $. Together they form an adjunction. \begin{definition}{\rm A {\em additive-stable map} between event structures with polarity, from $A$ to $B$, is a function $f: \iconf A \to \iconf B$ which is\\ $\bullet$ {\em polarity-respecting:} for $x, y\in\iconf A$, $$ x\subseteq^- y \Rightarrow f(x)\subseteq^- f(y) \ \hbox{ and } \ x\subseteq^+ y\Rightarrow f(x)\subseteq^+ f(y)\,; $$ $\bullet$ {\em image finite:} if $ x\in\conf A$ then $ f(x)\in\conf B$; \\ $\bullet$ {\em additive:} for all compatible families $\set{x_i}{i\in I}$ in $ \iconf A$, $$ \hbox{$\bigcup$}_{i\in I} f (x_i)= f(\hbox{$\bigcup$}_{i\in I} x_i)\,; $$ $\bullet$ {\em stable:} for all compatible families $\set{x_i}{i\in I}\neq\emptyset$ in $ \iconf A$, $$ f(\hbox{$\bigcap$}_{i\in I} x_i) = \hbox{$\bigcap$}_{i\in I} f ( x_i)\,. $$ }\end{definition} The usual maps of games are additive-stable, including those which are partial, as are Girard’s linear maps. Additive-stability is indifferent to a switch of polarities: \begin{proposition} An additive-stable function $f$ from $A$ to $B$ is an additive-stable function $f$ from $A^\perp$ to $B^\perp$ and {\it vice versa}. \end{proposition} Given an additive-stable function $f$ from $A$ to $B$ we obtain a strategy $f_!:A\profto B$ and, via $f$ from $A^\perp$ to $B^\perp$, $f^*:B\profto A$. \begin{theorem}\label{thm:adjn} Let $f$ be an additive-stable function from $A$ to $B$ between event structures with polarity. The strategies $f_!$ and $f^*$ form an adjunction $f_!\dashv f^*$ in the bicategory ${\mathbf{Strat}}$. \end{theorem} ${\mathbf{Strat}}$ forms a {\em pseudo double category}~\cite{2DCat,hugo-thesis}. In Section~\ref{sec:GoIadjns} we apply Theorem~\ref{thm:adjn} to relate deterministic strategies in general, to those of Geometry of Interaction. The adjunction in ${\mathbf{Strat}}$ of Theorem~\ref{thm:adjn} yields a traditional adjunction: \begin{corollary} Let $f$ be an additive-stable function from game $A$ to game $B$. Let ${\mathbf{Strat}}_A$ be the category of strategies in the game $A$, and ${\mathbf{Strat}}_B$ that in $B$. Then there are functors $f_!{{\odot}} (\_):{\mathbf{Strat}}_A\to {\mathbf{Strat}}_B$ and $f^*{{\odot}} (\_):{\mathbf{Strat}}_B\to {\mathbf{Strat}}_A$ with $f_!{{\odot}} (\_)$ left adjoint to $f^*{{\odot}} (\_)$. \end{corollary} \section{From strategies to functions}\label{sec:part2} We recover familiar notions on games from those based on event structures. A game is {\em tree-like} when any two events are either inconsistent or causally dependen . When race-free, at any finite configuration, the next moves, if there are any, are either purely those of Player, or purely those of Opponent; so positions either belong to Player or Opponent. Then, at each Player position a deterministic strategy either chooses a unique move or to stay put. In contrast to many presentations of games, in a concurrent strategy Player isn't forced to make a move, though that can be encouraged through suitable winning conditions. A counterstrategy, as a strategy in the dual game, picks moves for Opponent at their configurations. The interaction $\tau\sncirc\sigma$ of a deterministic strategy $\sigma$ with a deterministic counterstrategy $\tau$ determines a finite or infinite branch in the tree of configurations, which in the presence of winning conditions will be a win for one of the players. On tree-like games we recover familiar notions. More surprising is that by exploiting the richer structure of concurrent games we can recover other familiar paradigms, not traditionally tied to games, or if so only somewhat informally. We start by rediscovering Berry's stable domain theory, of which Jean-Yves Girard's qualitative domains and coherence spaces are special cases. The other examples, from dataflow, logic and functional programming, concern ways of handling interaction within a functional approach. We shall restrict to race-free games, so guaranteeing that deterministic strategies have an identity w.r.t.~composition, given by copycat. \subsection{Stable functions} Consider games in which all moves are Player moves. Consider a strategy $\sigma$ from from one such purely Player game $A$ to another $B$. This is a map $\sigma: S\to A^\perp{\mathbin{\parallel}} B$ which is receptive and innocent. Notice that in $A^\perp{\mathbin{\parallel}} B$ all the Opponent moves are in $A^\perp$ and all the Player moves are in $B$. By receptivity any configuration of $A$ can be input. The only new immediate causal connections, beyond those in $A^\perp$ and $B$, that can be introduced in a strategy are those from Opponent moves of $A^\perp$ to a Player move in $B$. Beyond the causal dependencies of the games, a strategy $\sigma$ can only make a Player move in $B$ causally depend on a finite subset of moves in $A^\perp$. When $\sigma$ is deterministic, all conflicts are inherited from conflicts between Opponent moves. Then the strategy $\sigma$ gives rise to a stable function from the configurations of $A$ to the configurations of $B$. Conversely, such a stable function $f$ yields a deterministic strategy $f_!:A\profto B$, by Theorem~\ref{thm:affstmaptostrats}. \begin{theorem} The category of dI-domains and stable functions, enriched by the stable order, is equivalent to the bicategory of deterministic strategies between purely Player games with rigid 2-cells. \end{theorem} The category of dI-domains and stable functions is well-known to be cartesian-closed; its function space and product are realised by constructions $[A\to B]$ and $A{\mathbin{\parallel}} B$ on event structures. When the games are further restricted to have trivial causal dependency we recover Girard's {\em qualitative domains} and, with conflict determined in a binary fashion, his {\em coherence spaces}. Girard's models for polymorphism there generalise to dI-domains, with dependent types $\Pi_{x:A} B(x)$ and $\Sigma_{x:A} B(x)$ on event structures~\cite{evstrs,dIPoly, CGW}---see Appendices~\ref{sec:Stfnspace}, \ref{app:deptypes}. \subsection{Stable spans} \label{sec:stabspans} When between games in which all the moves are Player moves, a general, nondeterministic, strategy corresponds to a {\em stable span}, a form of many-valued stable function which has been discovered, and rediscovered, in giving semantics to higher-order processes and nondeterministic dataflow~\cite{mikkel,Visions,SEW}; the trace of strategies, derived from their compact closure, specialises to the feedback operation of dataflow. Recall a {\em stable span} comprises $$ \spano A{\it dem} {E}{\it out }{B\,,} $$ with event structure $E$ relating input given by an event structure $A$ and output by an event structure $B$. The map ${\it out }: E\to B$ is a {\em rigid} map. The map ${\it dem}:E\to A$, associated to input, is of a different character. It is a {\em demand} map, {\it i.e.}, a function from $\iconf E$ to $\iconf A$ which preserves unions and finite configurations; ${\it dem}(x)$ is the minimum input for $x$ to occur and is the union of the demands of its events. The occurrence of an event $e$ in $E$ demands minimum input ${\it dem}([e])$ and is observed as the output event ${\it out }(e)$. Spans from $A$ to $B$ are related by the usual 2-cell , here (necessarily) rigid maps $r$ making the diagram below commute: $$\small\xymatrix@R=12pt@C=18pt{ &\ar[ld]_{{\it dem}'}E'\ar@{..>}[d]^r\ar[rd]^{{\it out }'}&\\ A&\ar[l]^{\it dem} E\ar[r]_{\it out }&B } $$ Stable spans compose via the usual pullback construction of span , as both demand and output maps extend to functions between configurations. A stable span $E$ corresponds to a (special) profunctor $$\tilde E(x,y) =\set{w\in\conf E}{{\it dem}(w) \subseteq x \ \&\ {\it out }\,w= y}\,,$$ between the partial-order categories $\conf A$ and $\conf B$ ---a correspondence that respects composition. Recalling the view of profunctors as Kleisli maps w.r.t.~the presheaf construction~\cite{Kleisli}, we borrow from Moggi~\cite{Moggi} and describe the composition of stable spans $ F:A\profto B$, $G:B\profto C$ as $$ G{{\odot}} F (x) = \hbox{ {\rm let }} y \Leftarrow F(x) \hbox{ {\rm in} } G(y) \, $$ ---which, via the correspondence with profunctors, stands for the coend \int^{y\in\conf B} \tilde F(x,y) \times\tilde G(y,\_)$. In using let-notation we can take account of the shape of the configuration $y$ in the definition of $G$, in effect an informal pattern matching. Stable spans are monoidal closed~\cite{mikkel,lics02}: w.r.t.~an event structure $A$, the functor $(\_{\mathbin{\parallel}} A)$ has a right adjoint, the function space $[A\multimap\_]$. The construction $[A\multimap B]$ is recalled in Appendix~\ref{app:stspans} along with a more general dependent product $\Pi^s_{x:A}B(x)$ for stable spans: the type of stable spans which on input $x:A$ yield output $y:B(x)$ nondeterministically. Let $A$ and $B$ be purely Player games. A strategy $\sigma:S\to A^\perp{\mathbin{\parallel}} B$ gives rise to a stable span $$ \xymatrix{ A&\ar[l]_{\it dem}{E}\ar[r]^{\it out }&{B\,,} } $$ where $E= S^+$, and ${\it out }$ gives the image of its events in $B$ and ${\it dem}$ those events in $A$ on which they casually depend. Conversely given a stable span, as above, we obtain a strategy as the composition ${\it out }_! {{\odot}} {\it dem}^ $, by the results of Section~\ref{sec:part1}; as regarding $E$ and $A$ as purely Player games, both ${\it out }$ and ${\it dem}:\iconf{E^\perp}\to \iconf{A^\perp}$ are affine-stable. In the strategy ${\it out }_! {{\odot}} {\it dem}^*:S\to A^\perp{\mathbin{\parallel}} B$ so obtained, $S$ comprises the disjoint union of $A$ and $E$ with the additional causal dependencies of $e\in E$ on $a\in A^\perp$ prescribed by ${\it dem}$. \begin{theorem} The bicategory of stable spans is equivalent to the bicategory of strategies between purely Player games with rigid 2-cells. \end{theorem} We show that in a similar way, we obtain geometry of interaction, dialectica categories, containers, lenses, open games and learners, optics and dependent optics by moving to slightly more complicated subcategories of games, sometimes with winning conditions and imperfect information. \subsection{Geometry of Interaction} \label{sec:GoI} Let's now consider slightly more complex games. A {\em GoI game} comprises a parallel composition $A:=A_1{\mathbin{\parallel}} A_2$ of a purely Player game $A_1$ with a purely Opponent game $A_2$. Consider a strategy $\sigma$ from a GoI game $A:= A_1{\mathbin{\parallel}} A_2$ to a GoI game $B:= B_1{\mathbin{\parallel}} B_2$. Rearranging the parallel compositions, $$ A^\perp{\mathbin{\parallel}} B = A_1^\perp {\mathbin{\parallel}} A_2^\perp {\mathbin{\parallel}} B_1{\mathbin{\parallel}} B_2 \cong (A_1 {\mathbin{\parallel}} B_2^\perp)^\perp {\mathbin{\parallel}} (A_2^\perp{\mathbin{\parallel}} B_1)\,. $$ So $\sigma$, as a strategy in $A^\perp{\mathbin{\parallel}} B$, corresponds to a strategy from the purely Player game $A_1 {\mathbin{\parallel}} B_2^\perp$ to the purely Player game $A_2^\perp{\mathbin{\parallel}} B_1$. We are back to the simple situation considered in the previous section, of strategies between purely Player games. Strategies between GoI games, from $A$ to $B$ correspond to stable spans from ${A_1 {\mathbin{\parallel}} B_2^\perp}$ to ${A_2^\perp{\mathbin{\parallel}} B_1}$, and to stable functions when deterministic. Note that a configuration of a parallel composition of games splits into a pair of configurations: $$ { \iconf{A_1 {\mathbin{\parallel}} B_2^\perp} \cong \iconf{A_1}\times\,\iconf{B_2}, \ \iconf{A_2^\perp{\mathbin{\parallel}} B_1} \cong \iconf{A_2}\times\,\iconf{B_1}. }$$ Thus deterministic strategies from $A$ to $B$ correspond to stable functions $$ S=\langle f, g\rangle : \iconf{A_1}\times\iconf{B_2} \to \iconf{A_2}\times \iconf{B_1}\,, $$ associated with a pair of stable functions $f: \iconf{A_1}\times\iconf{B_2} \to \iconf{A_2}$ and $g: \iconf{A_1}\times\, \iconf{B_2} \to \iconf{B_1}$, summarised diagrammatically by: $$ \xymatrix{ A_1\ar@/^1.1pc/[d]\ar@/_0.9pc/[r]_S&B_1\ar@{}[l]|f\\ A_2&B_2\ar@/^1.1pc/[u]\ar@/_0.9pc/[l] \ar@{}[l]|g } $$ Such maps are obtained by Abramsky and Jagadeesan's GoI construction, here starting from {\em stable} domain theory~\cite{nfgoi}. The composition of deterministic strategies between GoI games, $\sigma$ from $A$ to $B$ and $\tau$ from $B$ to $C$ coincides with the composition of GoI given by ``tracing out'' $B_1$ and $B_2$. Precisely, supposing $\sigma$ corresponds to the stable function $$ S: \iconf{A_1}\times\,\iconf{B_2} \to \iconf{A_2}\times\,\iconf{B_1}\, $$ and $\tau$ to the stable function $$ T: \iconf{B_1}\times\,\iconf{C_2} \to \iconf{B_2}\times\,\iconf{C_1}\,, $$ we see a loop in the functional dependency at $B$: $$ \xymatrix{ A_1\ar@/^1.1pc/[d]\ar@/_0.9pc/[r]_S&{B_1}\ar@/^1.1pc/[d]\ar@/_0.9pc/[r]_T&C_1& \\ A_2&B_2\ar@/^1.1pc/[u]\ar@/_0.9pc/[l]&C_2\ar@/^1.1pc/[u]\ar@/_0.9pc/[l]& } $$ Accordingly, the composition $\tau{{\odot}} \sigma$ corresponds to the stable function taking $(x_1,z_2)\in \iconf{A_1}\times\,\iconf{C_2}$ to $(x_2, z_1) \in \iconf{A_2}\times\,\iconf{C_1}$ in the least solution to the equations $$ (x_2, y_1) = S(x_1, y_2) \ \hbox{ and }\ (y_2, z_1) = T(y_1, z_2)\, $$ ---given, as in Kahn networks, by taking a least fixed point. \begin{theorem} The bicategory of deterministic strategies on GoI games with rigid 2-cells is equivalent to the Geometry of Interaction category $\G({\bf dI})$ of~\cite{AbramskyHaghverdiScott} built on the category $\bf dI$ of dI-domains and stable functions. \end{theorem} Geometry of Interaction started as an investigation of the nature of proofs of linear logic, understood as networks~\cite{GirardGoI1}. It has subsequently been tied to optimal reduction in the $\lambda$-calculus~\cite{GoI-optred}, and inspired implementations via token machines on networks~\cite{mackie,ghica}; when the two components of a GoI game match events of exit and entry of a token at a link. It is straightforward to extend GoI games with winning conditions. A winning condition on a GoI game $A=A_1{\mathbin{\parallel}} A_2 $ picks out a subset of the configurations $\iconf A$, so amounts to specifying a property $W_A(x_1,x_2)$ of pairs $(x_1,x_2)$ in $\iconf{A_1}\times \iconf{A_2}$. That a deterministic strategy from GoI game $A$ to GoI game $B= B_1{\mathbin{\parallel}} B_2$ is winning means $$ W_A(x, g(x,y)) \implies W_B(f(x,y), y)\,, $$ for all $x\in \iconf{A_1}, y\in \iconf{B_2}$, when expressed in terms of the pair of stable functions the strategy determines. In particular, a deterministic winning strategy in the individual GoI game $B$, with winning conditions $W_B$, corresponds to a stable function $f: \iconf{B_2} \to \iconf{B_1}$ such that $\forall y\in\iconf{B_2}.\ W_B(f(y), y)$. With stable spans, unlike with dI-domains with stable functions, the operation of parallel composition ${\mathbin{\parallel}}$ is no longer a product; stable spans are monoidal-closed and not a cartesian-closed. While general, not just deterministic, strategies $\sigma:A\profto B$ between GoI games are expressible as stable spans $ A_1{\mathbin{\parallel}} B_2^\perp \profto A_2^\perp {\mathbin{\parallel}} B_1 $, their expression doesn't project to an equivalent pair of separate components as with lenses. \subsubsection{The GoI adjunctions}\label{sec:GoIadjns} For any game $A$ there is a map of event structures with polarity $$ f_A: A \to A^+ {\mathbin{\parallel}} A^-\,, $$ where $A^+$ is the projection of $A$ to its $+$ve events and $A^-$ is the projection to its $-$ve events: the map $f_A$ acts as the identity function on events; it sends a configurations $x\in\iconf A$ to $f_A x = x^+{\mathbin{\parallel}} x^-$. It determines an adjunction $ f_! \dashv f^*$ from $A $ to $A^+ {\mathbin{\parallel}} A^-$. Because the game $A$ is race-free, both ${f_A}_!$ and ${f_A}^*$ are deterministic strategies. This provides a lax functor from deterministic strategies in general, to those between GoI games. Let $\sigma:A\profto B$ be a deterministic strategy between games $A$ and $B$. Defining ${\it goi}(\sigma) = {f_B}_! {{\odot}} \,\sigma\, {{\odot}} {f_A}^*$ we obtain a deterministic strategy $${\it goi}(\sigma): A^+{\mathbin{\parallel}} A^- \profto B^+{\mathbin{\parallel}} B^-\,.$$ Then, the strategy ${\it goi}(\sigma)$ corresponds to a stable function from $A^+{\mathbin{\parallel}} B^-$ to $A^- {\mathbin{\parallel}} B^+$, so to a GoI map. The operation ${\it goi}$ only forms a lax functor however: for $\sigma:A\profto B$ and $\tau:B\profto C$, there is, in general, a nontrivial 2-cell $ {\it goi}(\tau{{\odot}} \sigma) \Rightarrow {\it goi}(\tau){{\odot}} {\it goi}(\sigma)$. This puts pay to ${\it goi}$ being right adjoint to the ``inclusion'' functor in a pseudo adjunction from the category of GoI games to deterministic strategies. But, there is a {\em lax} pseudo adjunction, of potential use in abstract interpretation. \subsection{Dialectica games} Dialectica categories were devised in the late 1980's by Valeria de Paiva in her Cambridge PhD work with Martin Hyland~\cite{valeria}. The motivation then was to provide a model of linear logic underlying Kurt G\"odel's {\em dialectica interpretation} of first-order logic~\cite{dialecticaInt}. They have come to prominence again recently because of a renewed interest in their maps in a variety of contexts, in formalisations of reverse differentiation and back propagation, open games and learners, and as an early occurrence of maps as lenses. The dialectica interpretation underpins most proof-mining techniques~\cite{kreisel,kohlenbach}. We obtain a particular dialectica category, based on Berry's stable functions, as a full subcategory of deterministic strategies on dialectica games. Dialectica games are obtained as GoI games of imperfect information, intuitively by not allowing Player to see the moves of Opponent. A {\em dialectica game} is a GoI game $A= A_1{\mathbin{\parallel}} A_2$ with winning conditions, and with imperfect information given as follows. The imperfect information is determined by particularly simple order of access levels: ${1} \prec {2}$. All Player moves, those in $A_1$, are assigned to ${1}$ and all Opponent moves, those in $A_2$, are assigned to ${2}$. It is helpful to think of the access levels ${1}$ and ${2}$ as representing two rooms separated by a one-way mirror allowing anyone in room ${2}$ to see through to room ${1}$. In a dialectica game, Player is in room ${1}$ and Opponent in room ${2}$. Whereas Opponent can see the moves of Player, and in a counterstrategy make their moves dependent on those of Player, the moves of Player are made blindly, in that they cannot depend on Opponent's moves. Although we are mainly interested in strategies {\em between} dialectica games it is worth pausing to think about strategies {\em in} a single dialectica game $A= A_1{\mathbin{\parallel}} A_2$ with winning conditions $W_A$. Because Player moves cannot causally depend on Opponent moves, a deterministic strategy in $A$ corresponds to a configuration $x\in\iconf{A_{1}}$; that it is winning means $\forall y\in \iconf{A_{2}}.\ W_A(x,y)$. So to have a winning strategy for the dialectica game means $$ \exists x\in \iconf{A_{1}}\forall y\in \iconf{A_{2}}.\ W_A(x,y)\,. $$ Consider now a deterministic winning strategy $\sigma$ from a dialectica game $A=A_1{\mathbin{\parallel}} A_2$ with winning conditions $W_A$ to another $B=B_1{\mathbin{\parallel}} B_2$ with winning conditions $W_B$. Ignoring access levels, $\sigma$ is also a deterministic strategy between GoI games, so corresponds to a pair of stable functions $$f: \iconf{A_1}\times\iconf{B_2} \to \iconf{B_1}\hbox{ and } g: \iconf{A_1}\times\iconf{B_2} \to \iconf{A_2}\,.$$ But moves in $B_2$ have access level ${2}$, moves of $B_1$ access level ${1}$; a causal dependency in the strategy $\sigma$ of a move in $B_1$ on a move in $B_2$ would violate the access order ${1} \prec {2}$. That no move in $B_1$ can causally depend on a move in $B_2$ is reflected in the functional independence of $f$ on its second argument. As a deterministic strategy between dialectica categories, $\sigma$ corresponds to a pair of stable functions $$f: \iconf{A_1} \to \iconf{B_1} \hbox{ and } g: \iconf{A_1}\times \iconf{B_2} \to \iconf{A_2}\,,$$ which we can picture as: $$ \xymatrix@R=10pt{ A_1\ar@{-}@/^1.9pc/[d]^g\ar[r]^f&B_1\\ A_2&B_2\ar@/_0.3pc/[l] } $$ That $\sigma$ is winning means, for all $x\in \iconf{A_1}, y\in \iconf{B_2}$, $$ W_A(x, g(x,y)) \implies W_B(f(x), y)\,. $$ Pairs of functions $f,g$ satisfying this winning condition are precisely the maps of de Paiva's construction of a dialectica category from Berry's stable functions. Such pairs of functions are the {\em lenses} of functional programming where they were invented to make composable local changes on data-structures~\cite{oles,pierce}. We recover their at-first puzzling composition from the composition of strategies. Let $\sigma$ be a deterministic strategy from dialectica game $A$ to dialectica game $B$; and $\tau$ a deterministic strategy from $B$ to another dialectica game $C$. Assume $\sigma$ corresponds to a pair of stable functions $f$ and $g$, as above, and analogously that $\tau$ correponds to stable functions $f'$ and $g'$. Then, the composition of strategies $\tau{{\odot}}\sigma$ corresponds to the composition of lenses: with first component $f'\circ f$ and second component taking $x\in\iconf{A_1}$ and $y\in \iconf{C_2}$ to $g(x, g'(f(x), y))$. \begin{theorem} The bicategory of deterministic strategies on dialectica games with rigid 2-cells is equivalent to the dialectica category of~\cite{valeria} built on dI-domains and stable functions. \end{theorem} \subsubsection*{Girard's variant} In the first half of de Paiva's thesis she concentrates on the construction of dialectica categories. In the second half, she follows up on a suggestion of Girard to explore a variant. This too is easily understood in the context of concurrent games: imitate the work of this section, with GoI games extended with imperfect information, but now with access levels modified to the {\em discrete} order on ${1}, {2}$. Then the causal dependencies of strategies are further reduced and deterministic strategies from $A= A_1{\mathbin{\parallel}} A_2$ to $B= B_1{\mathbin{\parallel}} B_2$ correspond to pairs of stable functions $ f: \iconf{A_1} \to \iconf{B_1}$, $g: \iconf{B_2} \to \iconf{A_2}$. \subsubsection*{Combs} Discussions of causality in science, and quantum information in particular, are often concerned with what causal dependencies are feasible; then structures similar to orders of access levels are used to capture {\em one-way signalling}, as in dialectica games, and {\em non-signalling}, as in Girard's variant. In this vein, through another variation of games with imperfect information, we obtain the generalisation of lenses to {\em combs}, used in quantum architecture and information~\cite{Chiribella2008,aleks}. Combs arise as strategies between {\em comb games} which, at least formally, are an obvious generalisation of dialectica games; their name comes from their graphical representation as structures that look like (hair) combs, with each tooth representing a transformation from input to output. An {\em $n$-comb game}, for a natural number $n$, is an $n$-fold parallel composition $A_1{\mathbin{\parallel}} A_2 {\mathbin{\parallel}} \cdots{\mathbin{\parallel}} A_n$ of purely Player or purely Opponent games $A_i$ of alternating polarity; it is a game of imperfect information associated with access levels $1\prec 2\prec \cdots \prec n$ with moves of component $A_i$ having access level $i$. Dialectica games are 2-comb games with winning conditions. \subsubsection*{Open games and learners} There are intriguing connections with {\em open games and learners ~\cite{opengames,openlearners}. They have recently been presented as {\em parameterised} lenses or optics, in the case of open games with some concept of equilibrium or winning condition~\cite{capucci2021foundations}. As an example, we obtain a form of open game between dialectica games $A$ and $B$ as a strategy $ A{\mathbin{\parallel}} P \profto B $, where $P$ is a dialectica game of which the configurations specify {\em strategy profiles}. A variation based on optimal strategies between dialectica games with payoff, following~\cite{payoff}, introduces Nash equilibria and takes us into game-theory territory, and to a testing ground for open games and the notions being developed there. \subsection{Optics} Now we show that general, possibly nondeterministic, strategies between dialectica games are precisely {\em optics}~\cite{optics,optics2} based on stable spans~\cite{SEW,mikkel,Visions}. Recall that a dialectica game comprises $A_1{\mathbin{\parallel}} A_2$ where $A_1$ is a purely Player game, all events of which have access level ${1}$ and $A_2$ is a purely Opponent game with all events of access level ${2}$, w.r.t.~access order $\Lambda$ specifying $1\prec 2$. We ignore winning conditions. Let $A$ and $B$ be dialectica games. Let $Q$ be a purely Player $\Lambda$-game. Recall that nondeterministic strategies between purely Player games correspond to stable spans. Consider strategies $$F: A_1 \profto B_1{\mathbin{\parallel}} Q \hbox{ and } G: Q {\mathbin{\parallel}} B_2^\perp \profto A_2^\perp\,.$$ Then the strategies $F$ and $G$ are between purely Player games, so correspond to stable spans-- Appendix~\ref{app:stspans}. As any causal dependencies of $F$ or $G$ respect $\Lambda$, they are $\Lambda$-strategies. Hence the composition $$\xymatrix{ A_1{\mathbin{\parallel}} B_2^\perp \ar[r]|-{\! +\!}^{F{\mathbin{\parallel}} B_2^\perp}& B_1{\mathbin{\parallel}} Q{\mathbin{\parallel}} B_2^\perp \ar[r]|-{\! +\!}^{B_1{\mathbin{\parallel}} G}& B_1{\mathbin{\parallel}} A_2^\perp } $$ is also a $\Lambda$-strategy and, being between purely Player games, corresponds to a stable span. The composition, rearranges to a strategy $$ \sigma: A_1{\mathbin{\parallel}} A_2 \profto B_1{\mathbin{\parallel}} B_2\,, $$ which is a $\Lambda$-strategy, so to a strategy between the original dialectica games $A$ and $B$. We call this strategy ${\rm optic}(F,G)$ and call $(F,G)$ its {\em presentation} from $A$ to $B$ with {\em residual} $Q$. The terminology is apt, as we'll show strategies obtained in this way coincide with {\em optics} as usually defined. Presentations can be represented diagrammatically: $$ \small\xymatrix@R=2pt@C=10pt{ A_1 \ar[rrr]^F&\ar@/^0.5pc/[dr]&&B_1\\ &&Q\ar@{-}@/^0.5pc/[dl]\\ A_2&&&B_2\,,\ar[lll]^G } $$ illustrating how $F$ and $G$ are ``coupled'' via the residual $Q$. As usually defined, an optic is an equivalence class of presentations. Let $(F,G)$ and $(F', G')$ be presentations from $A$ to $B$ with residuals $Q$ and $Q'$ respectively. The equivalence relation $\sim$ on presentations is that generated by taking $(F,G)\sim(F', G')$ if, for some $f: Q\profto Q'$, the following triangles commute $$ \xymatrix@R=12pt@C=18pt{ A_1\ar[r]|+^{F'}\ar[dr]|\times_{F}& B_1{\mathbin{\parallel}} Q' \!\!\!& Q'{\mathbin{\parallel}} B_2\ar[r]|+^{G'} & B_1\\ &B_1{\mathbin{\parallel}} Q \ar[u]|+_{B_1{\mathbin{\parallel}} f} & Q{\mathbin{\parallel}} B_2\,.\ar[u]|+^{f{\mathbin{\parallel}} B_2}\ar[ru]|\times_{G} \\ } \eqno(\sim\hbox{def}) $$ Presentations of optics compose. Let $A$, $B$ and $C$ be dialectica games. Given a presentation $(F,G)$ from $A$ to $B$ with residual $Q$ and another $(F',G')$ from $B$ to $C$ with residual $P$ we obtain a presentation from $A$ to $C$ with residual $P{\mathbin{\parallel}} Q$ guided by the diagram $$ \small\xymatrix@R=1pt@C=10pt{ A_1 \ar[rrr]^F&\ar@/^0.5pc/[dr]&&B_1 \ar[rrr]^{F'}&\ar@/^0.5pc/[dr] &&C_1 \\ &&Q\ar@{-}@/^0.5pc/[dl]&&&P\ar@{-}@/^0.5pc/[dl] \\ A_2&&&B_2 \ar[lll]^G &&&C_2\,, \ar[lll]^{G'} } $$ precisely, as $((F'{\mathbin{\parallel}} Q){{\odot}} F, \, G{{\odot}} (Q{\mathbin{\parallel}} G'){{\odot}} (s_{PQ}{\mathbin{\parallel}} C_2))$, where $s_{PQ}$ expresses the symmetry $P{\mathbin{\parallel}} Q\cong Q{\mathbin{\parallel}} P . Composition preserves $\sim$ and has the evident identity presentation, with residual the empty game. It follows that ${\rm optic}$ is functorial and that if $(F,G)\sim(F', G')$ then $${\rm optic}(F,G)\cong{\rm optic}(F', G')\,.$$ To show any strategy between container games is an optic, we exploit the monoidal-closure of stable span ---see Appendix~\ref{app:stspans}. A presentation $(F,G)$ is $\sim$-equivalent to a {\em canonical presentation} $(F', G')$ with residual $Q' = [B_2^\perp \multimap A_2^\perp]$ and $G'$ as {\em application} ${\rm apply}$: in ($\sim$def), take $f = {\rm curry\,} $ and $F' = (B_1{\mathbin{\parallel}} f) {{\odot}} F . Now, strategies $\sigma: A\profto B$, between dialectica games $A$ and $B$, correspond to canonical presentations. To see this, ignoring the access levels for the moment, a general strategy $$\sigma: A_1{\mathbin{\parallel}} A_2 \profto B_1{\mathbin{\parallel}} B_2$$ corresponds to a strategy between purely Player games $$\sigma_1: A_1{\mathbin{\parallel}} B_2^\perp \profto B_1{\mathbin{\parallel}} A_2^\perp\,,$$ so to a stable span. From the monoidal-closure of stable spans we can curry $\sigma_1$, to obtain a corresponding strategy $$\sigma_2: A_1\profto [B_2^\perp \multimap (B_1{\mathbin{\parallel}} A_2^\perp)]\,$$ with the property $$ \sigma_1 \cong {\rm apply}_{B_1{\mathbin{\parallel}} A_2^\perp}{{\odot}} (\sigma_2{\mathbin{\parallel}} B_2^\perp)\,. $$ Recalling the access levels, no event of $B_1$ can causally depend on an event of $B_2$, ensuring that $\sigma_2$ corresponds to $$\sigma^+: A_1\profto B_1{\mathbin{\parallel}} [B_2^\perp \multimap A_2^\perp]\,$$ where $$ \sigma_1 \cong {\rm apply}_{B_1{\mathbin{\parallel}} A_2^\perp}{{\odot}} (\sigma_2{\mathbin{\parallel}} B_2^\perp)\cong (B_1{\mathbin{\parallel}} {\rm apply}_{A_2^\perp}) {{\odot}} (\sigma^+{\mathbin{\parallel}} B_2^\perp)\,. $$ It follows that $(\sigma^+, {\rm apply}_{A_2^\perp})$ is a canonical presentation for which $$\sigma\cong {\rm optic}(\sigma^+, {\rm apply}_{A_2^\perp})\,,$$ giving a correspondence between strategies $\sigma:A\profto B$ between dialectica games and canonical presentations $(\sigma^+, {\rm apply}_{A_2^\perp})$. Via canonical presentations we obtain a bicategory of optics. Its objects are dialectica games. Its maps are stable spans A_1 \profto B_1{\mathbin{\parallel}} [B_2^\perp \multimap A_2^\perp \,,$ with the associated 2-cells, from dialectica game $A$ to dialectica game $B$. \begin{theorem} The bicategories of strategies on dialectica games with rigid 2-cells and that of optics built on stable spans are equivalent. \end{theorem} \subsection{Containers}\label{sec:containers} A {\em container game} is a game of imperfect information $A$ w.r.t.~access levels ${1} \prec {2}$; each Player move of $A$ is sent to ${1}$ and each Opponent move to ${2}$. So in $A$ the only causal dependencies between moves of different polarity are $\oplus \leq \ominus$. The configurations of a container game $A$ have a dependent-type structure. Opponent moves can causally depend on Player moves, but not conversely. Let $A_1$ denote the subgame comprising the initial substructure of purely Player moves of $A$. A configuration $x\in\iconf{A_1}$ determines a subgame $A_2(x)$ comprising the substructure of $A$ based on all those Opponent moves for which all the Player moves on which they depend appear in $x$. A configuration of $A$ breaks down uniquely into a union $x\cup y$, so a pair $(x,y)$, where $x\in \iconf{A_1}$ and $y\in \iconf{A_2(x)}$. We can see the configurations of a container game $A$ as forming a dependent sum $\Sigma_{x:{A_1}} \, {{A_2(x)}}$. In this way a container game represents a container type, familiar from functional programming~\cite{containers}; configurations $x$ of $A_1$ are its ``shapes'' and $y\in A_2(x)$ their ``positions.'' \footnote We won't treat symmetry in concurrent games at all here, but it is important in many applications. With the addition of symmetr , configurations form a nontrivial category, not merely a partial order based on inclusion~\cite{lics14}. } We can of course extend a container game $A$ with winning conditions which we identify with a property $W_A$ of the dependent sum $\Sigma_{x:{A_1}} \, {{A_2(x)}}$. A deterministic winning strategy in the container game corresponds to a configuration $x\in \iconf{A_1}$ such that $\forall y \in \iconf{{A_2(x)}}.\ W_A(x,y)$. Strategies between container games respect $\preceq$ on access levels. A deterministic strategy $\sigma$ from a container game $A$ to a container game $B$ corresponds to a map of container types, also called a {\em dependent lens}, having type $$ \Sigma_{f:[{A_1}\to {B_1}]} \Pi_{x:{A_1}}\ [ {B_2(f (x)) } \to {A_2(x)}]\,; \eqno(*) $$ so $\sigma$ corresponds to a pair of stable functions $$f:[{A_1} \to {B_1}] \ \hbox{ and } \ g:\Pi_{x:{A_1}} \, [{B_2(f(x))} \to {A_2(x)}]\,,$$ where we are using the function space, dependent sum and product of stable function ---see Appendix~\ref{app:deptypes}. With winning conditions $W_A$ and $W_B , the strategy from $A$ to $B$ would be winning iff, for all $x\in\iconf{A_1}$, $y\in \iconf{B_2(f(x))}$, $$ W_A(x, g_x(y)) \implies W_B(f(x), y)\,. $$ The correspondence respects composition. Container types built on dI-domains and stable functions arise as a full subcategory of deterministic concurrent games. \begin{theorem} The bicategory of deterministic strategies on container games with rigid 2-cells is equivalent to a full subcategory of containers of dI-domains and stable functions~\cite{containers}. \end{theorem} \subsection{Dependent optics} What about general, nondeterministic, strategies between container games? A way to motivate their characterisation is to observe the isomorphism of the type of a dependent lens $(*)$ above with $$ \Pi_{x:{A_1}}\Sigma_{y:{B_1}} \ [{B_2(y)} \to A_2(x) ]\,. $$ It is this nonstandard way to present the type of lenses that generalises to the monoidal-closed bicategory of stable spans, once we move to the dependent product $\Pi^s$ of stable span -- Appendix~\ref{app:deptypes}. Ignoring winning conditions, a general strategy between container games corresponds to a new form of optic. A {\em dependent optic} between container games, from $A$ to $B$, is a stable span of type $$ {\bf dOp}[A, B] = \Pi^s_{x:{A_1}}\Sigma_{y:{B_1}} \ [{B_2(y)} \multimap {A_2(x)}]\,, $$ so a rigid map into ${\bf dOp}[A,B]$. A 2-cell $f:F\Rightarrow F'$ between dependent optics $F, F':{\bf dOp}[A, B]$ is a 2-cell of stable spans. Composition of dependent optics is the stable spa $$ {\circ}: {\bf dOp}[B, C]\, {\mathbin{\parallel}} \, {\bf dOp}[A, B] \profto {\bf dOp}[A,C] $$ described by $$\eqalign{ G {\circ} F \coloneqq \lambda x:{A_1}. \ \hbox{ {\rm let }} & (y, F') \Leftarrow F(x) \hbox{ {\rm in} } \cr \hbox{ {\rm let }} & (z, G') \Leftarrow G(y) \hbox{ {\rm in} } (z, F'{{\odot}} G')\,, } $$ where $F'{{\odot}} G': [{C_2(z)} \multimap {A_2(x)}]$ is the composition of stable spans $G':[{C_2(z)} \multimap {B_2(y)}]$ and $F':[{B_2(y)} \multimap {A_2(x)}]$. The identity optic of container game $A$ acts on $x:A_1$ to return the identity at the $x$-component of $\Sigma_{x:A_1}[A_2(x) \multimap A_2(x)]$. The equivalence of strategies between container games with dependent optics, hinges on recasting ${\bf dOp}[A,B]$ as a strategy $\hbox{{\it do}}[A,B]: A\profto B$ between container games $A$ and $B$. Any strategy between container games is of course a strategy where we forget the access levels. We can express that a strategy $\sigma: A \profto B$ respects the access levels, so is truly a strategy between container games, precisely through the presence of a rigid 2-cell $$ \xymatrix@R=14pt@C=18pt{ A\ar@/^1pc/[rr]|-{\! +\!}^\sigma \ar@/_1pc/[rr]|-{\! +\!}_{\hbox{{\it do}}[A,B]}&\Downarro r\!\!\!\!\!&B\,. \\ }$$ The 2-cell $r$ is unique, making the strategy $\hbox{{\it do}}[A,B]$ terminal amongst strategies $\sigma$ between container games, from $A$ to $B$. By restricting $r$ to Player moves we obtain the dependent optic $\sigma^+: {\bf dOp}[A,B]$ which corresponds to $\sigma$. \begin{theorem} \label{thm:depop} The bicategory of strategies between container games, with rigid 2-cells, is equivalent to the bicategory of dependent optics. \end{theorem} \section{Enrichment }\label{sec:enrichment} Games and strategies support enrichments, to: probabilistic strategies, also with continuous distributions~\cite{probstrats,mfps2018}; quantum strategies~\cite{popl19}; and strategies on the reals~\cite{aurore}. The enrichments specialise to the cases above; {\it e.g.}, probabilistic strategies specialise to optics based on Markov kernels when between dialectica games. The enrichments were developed individually and are not always the final story. For instance, the assignment of quantum operators to configurations of strategies in~\cite{popl19} is not functorial w.r.t.~inclusion on configurations, a defect when it comes to understanding how the operator of a configuration is built up. The authors' remedy also achieves all the enrichments just named, now uniformly by the same construction. The construction is w.r.t.~a symmetric monoidal category $(\mathcal M, \otimes, {\rm I})$. For example, $\mathcal M$ can be the monoid $([0,1], \cdot, 1)$ comprising the unit interval under multiplication (for probabilistic strategies); measurable spaces with Markov kernels (for probabilistic strategies with continuous distributions); CPM, finite-dimensional Hilbert spaces with completely positive maps (for quantum strategies); or Euclidean spaces with smooth maps, to support (reverse) differentiation. We first extend $\mathcal M$ to allow interaction beyond that from argument to result. The {\em parameterised category} $\Para{\mathcal M}$ has the same objects, now with maps $(P, f, Q):X\to Y$ consisting of $f:X\tensor P \to Q\tensor Y$ in $\mathcal M$; the parameters $P$ and $Q$ allow input and output with the environment. Composition accumulates parameters: $(R,g,S)\circ (P, f, Q) \coloneqq (P\tensor R,\ (Q\tensor g)\circ (f\tensor R), \ Q\tensor S) $. Then, \noindent {\bf (1) } moves $a$ of a game $A$ are assigned objects ${\mathcal H}(a)$ in $\mathcal M$, extended to $X\in{\rm Con}_A$ by ${\mathcal H}(X) \coloneqq \Tensor_{a\in X} {\mathcal H}(a)$. (When neutral moves appear, as in interaction, they are assigned the tensor unit $\rm I$.) \noindent {\bf (2) } an $\mathcal M$-enriched strategy $\sigma:S\to A$ is accompanied by a functor ${\mathcal Q}:(\conf S, \subseteq) \to \Para{\mathcal M}$. To an interval $x\subseteq x'$ in $\conf S$ this assigns a parameterised map ${\mathcal Q}(x\subseteq x')$ with input parameters ${\mathcal H}(\sigma{(x'\setminus x)}^-)$ and output parameters ${\mathcal H}(\sigma{(x'\setminus x)}^+)$. The assignment in {\bf (2)} describes how the internal state is transformed in moving from $x$ to $x'$ under interaction via events $x'\setminus x$. In the probabilistic and quantum cases, observation is contextual, reflected in the presence of a {\em drop condition}, a form of inclusion-exclusion principle~\cite{probstrats,popl19}; it requires $\mathcal M$ be enriched over, at least, cancellative commutative monoids. Then, the assignment in {\bf (2)} is {\em oblivious}, {\it i.e.}~${\mathcal Q}(x\subseteq^- x')$ is always an isomorphism in $\mathcal M$, expressing that the input from $x'\setminus x$ is adjoined to the internal state. Events, their positions, dependencies and polarities, orchestrate the functional dependency and dynamic linkage in composing enriched strategies. Enrichments achieved in this way transfer automatically to subcategories, and the functional cases we have considered, without needing extra demands on the category $\mathcal M$. \section{Conclusion} In conclusion, functional paradigms can help tame the wild world of interactive computation. On the other hand, discovering the simplifying paradigms has often required considerable ingenuity. The challenges are even more acute with enrichments, say to probabilistic, quantum or real number computation. The traditional categories of mathematics do not often support all the features required by computation. They often don't have function spaces or support recursion. It is as if each case has had to be dealt with separately. A model of interaction is more technically challenging and requires a new, more local, way of thinking. But, as has been demonstrated her , it can provide a broad general context for interaction which can be specialised to functional paradigms, also in providing enrichments to probabilistic, quantum and real number computation, without requiring clever extensions to the traditional categories of mathematics. There is work to do, specifically in connecting concurrent games and strategies with the theory of effects~\cite{Moggi,powerplotkin}, but a lot can be said for a single, intrinsically higher-order framework which readily adapts to enrichments. \begin{acks} I'm grateful for discussions with Bob Atkey, Matteo Capucci, Fredrik Nordvall Forsberg, Bruno Gavranovic, Neil Ghani, Dan Ghica, Samuel Ben Hamou, Jules Hedges, Martin Hyland, Clemens Kupke, J\'er\'emy Ledent, Valeria de Paiva, Hugo Paquet and James Wood; I learnt of optics and combs from Jules and J\'er\'emy. Samuel Ben Hamou, ENS Paris Saclay, tackled the verification of the early part of the dialectica-games section for his student internship. Section~\ref{sec:enrichment} is directly inspired by joint work with Pierre Clairambault and Marc de Visme. \end{acks}
{'timestamp': '2022-03-01T02:53:50', 'yymm': '2202', 'arxiv_id': '2202.13910', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13910'}
arxiv
\section{Introduction} Modularity endows neural models with an inductive bias towards systematic generalisation, by activating and updating their knowledge sparsely \citep{hupkes2020compositionality}. For instance, modules may compete to attend different parts of a structured input \citep{goyal2019recurrent,goyal2020object} or disentangle pre-determined skills, reusable and autonomous facets of knowledge, across multiple tasks to be later recombined in original ways for new tasks \citep{alet2018modular,ponti2021inductive,ansell-etal-2021-mad-g,kingetsu2021neural}. These two levels of modularity mirror two distinct levels of memory \citep{hill2020grounded,yogatama2021adaptive}---short-term for input-level knowledge and long-term for task-level knowledge---and ultimately reflect the integrated yet modular nature of the cognitive system in humans \citep{clune2013evolutionary}. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{figures/Tasks-Skills2} \caption{A diagram of our latent-skill model: 1) a row of the task--skill binary matrix is selected according to the active task; 2) the (sparse or low-rank) parameters corresponding to active skills from a layer-specific inventory are combined; 3) the resulting parameterisation is plugged into a neural network.} \label{fig:diag} \end{figure} In multitask learning, previous work focused on settings where the skills relevant for each task are known \textit{a priori} \citep{pfeiffer-etal-2020-mad,ponti2020parameter,ansell2021composable}, or settings where parameters or representations are an entangled mixture of shared and task-specific knowledge \citep{misra2016cross,ruder2019latent,mahabadi2021parameter}. The former method requires expert knowledge (possibly sub-optimal and limited to a few domains), whereas the latter leaves multitask models vulnerable to distribution shifts and hence hinders them from quickly adapting to new tasks. To remedy these shortcomings, in this work we address a setting where the skills needed for each task are modular but unknown and possibly finer-grained than those posited by experts. Thus, we propose a method to jointly learn, in an end-to-end fashion: 1) a task--skill allocation matrix, which indicates which subset of skills (from a fixed inventory) are active for which task; and 2) a corresponding set of parameter-efficient adaptations of the model, a subset of which are superimposed to a base model according to the active skills. The proposed model is equivalent to performing a soft partition, represented by a binary matrix, of the set of skill-specific parameters \citep{orbanz2012lecture}. Thus, an Indian Buffet Process \citep{griffiths2005infinite,teh2007stick} can be posited as a prior over this matrix, to regularise it towards striking a balance in allocating different subsets of skills to each task. As an alternative inductive bias, we also explore using a higher learning rate for the task--skill matrix compared to the skill-specific parameters, as it promotes better allocations over general-purpose parameterisations. We evaluate our model on both reinforcement and supervised learning. For the first set of experiments, we focus on BabyAI \citep{chevalier-boisvert2018babyai}, a platform consisting of a sequence of levels where agents must follow linguistic instructions in a simulated environment. Each level is procedurally generated to reflect an increasingly complex combination of skills (e.g., picking up objects or unlocking doors). We find that our modular network achieves higher sample efficiency---by requiring a significantly smaller number of episodes to reach a near-perfect success rate in all levels---compared to all baselines including fully shared and level-specific models based on a state-of-the-art architecture \citep{hui2020babyai}, as well as a model that has access to the ground-truth skills. In addition, in the wake of the recent surge of interest in massively multitask few-shot NLP models \citep[\textit{inter alia}]{min2021metaicl,wei2021finetuned,aribandi2021ext5,sanh2022multitask,mahabadi2021parameter}, we also evaluate our latent-skill model on CrossFit \citep{ye-etal-2021-crossfit}. This benchmark recasts 160 NLP tasks (including QA, conditional text generation, classification, and other types such as regression) as text-to-text generation problems. We obtain superior performance in few-shot adaptation to held-out tasks compared to a series of competitive baselines that include HyperFormer, a state-of-the-art method for task-conditional parameter generation \citep{mahabadi2021parameter}. Thus, we demonstrate the ability of our model to successfully reuse and adjust the skills, which were previously acquired during multitask pre-training, on new tasks. Moreover, we show that our method can be used in tandem with several parameter-efficient methods \citep{he2021towards} in order to make the increase in time and space complexity due to skill-specific parameters negligible. In particular, we explore sparse adaptation with Lottery-Ticket Sparse Fine-Tuning \citep[LT-SFT;][]{ansell2021composable} and low-rank adaptation with Low-Rank Adapters \citep[LoRA;][]{hu2021lora}. Finally, in addition to sample efficiency and systematic generalisation, we illustrate how our method also favours interpretability, as it discovers explicitly which pairs of tasks require common modules of knowledge. The code for our model is available at: \\ \url{github.com/McGill-NLP/polytropon}. \section{A Latent-Skill Multitask Model} The goal of multitask learning in modelling a set of tasks ${\cal T} = ({\cal T}_1, \dots, {\cal T}_{|{\cal T}|})$ is two-fold: 1) increasing sample efficiency on each seen task by borrowing statistical strength from the others; and 2) attaining systematic generalisation, the ability to adapt robustly to new tasks, possibly based on a few target-domain examples. In particular, in supervised learning, each task ${\cal T}_i$ is associated with a dataset ${\cal D}_i \triangleq \{(\mathbf{x}_{1}, y_{1}), \dots, (\mathbf{x}_{n}, y_{n})\}$ and a loss function $\mathcal{L}(\hat{y}, y)$, where each $\mathbf{x}$ is an input and each $y$ is a label. In reinforcement learning, each task is characterised by an initial state distribution $q(\mathbf{x}_1)$, a transition distribution $q(\mathbf{x}_{t+1} \mid \mathbf{x}_t, a_t)$, and a loss function $\mathcal{L}(\mathbf{x}_1, a_1, \dots, \mathbf{x}_h, a_h) \rightarrow \mathbb{R}$,\footnote{This is the negative of the reward: $\mathcal{L}(\cdot) = - \mathcal{R}(\cdot)$.} where $\mathbf{x}$ is a state, $a$ is an action, and $h$ is the temporal horizon of each episode. Thus, each task defines a Markov Decision Process (MDP). Previous work sought to counter the limitations of fully sharing the parameters of a model across all tasks \citep{pmlr-v97-stickland19a}, which may exhaust model capacity and lead to interference among the task-specific gradients \citep{wang2021gradient}. Instead, parameters can be softly shared across tasks by composing task-specific adapters ~\citep{pfeiffer2020adapterfusion} or generating parameters via task-conditioned hyper-networks \citep{ponti2020parameter,mahabadi2021parameter,ansell-etal-2021-mad-g}. The first method leads to an explosion in parameter count, which grow linearly with the size of the number of tasks. Moreover, due to entangling knowledge across tasks, the second method suffers during few-shot adaptation to new tasks as it may overfit the training task distribution. In this work, we posit instead that there exists a (possibly small) fixed inventory of skills ${\cal S} = ({\cal S}_1, \dots, {\cal S}_{|{\cal S}|})$, where $|{\cal S}| \ll |{\cal T}|$. Each skill is an independent facet of knowledge that is reused across a subset of tasks. These assumptions guarantee both scalability and modularity. In particular, we seek to create a model that jointly learns which skills are active for which task, aggregates the corresponding skill parameters according to some deterministic function, and maximises the multitask log-likelihood \begin{equation} \label{eq:model} \sum_{\mathcal{T}_i}\sum_{(\mathbf{x}, y) \in \mathcal{T}_i} \log p(y \mid \mathbf{x}, Z, \Phi, {\cal T}_i) \, p(Z \mid \alpha) \, p(\Phi) \end{equation} with respect to two distinct sets of parameters: i) a matrix $Z$ of soft partitions of skills across tasks, regularised by a prior with hyper-parameter $\alpha$; ii) a matrix $\Phi$ of skill-specific parameters for a given neural architecture, which are composed according to the active skills. The full graphical model is shown in \cref{fig:grf}. In what follows, we illustrate each component separately. \input{figures/graph} \subsection{Soft Partitions} What is the best strategy to determine which skills are active for which task? The cognitively inspired notion of modularity at the level of structured inputs assumes that modules compete with each other for activation and updating~\citep{bengio2017consciousness,goyal2019recurrent}. This intuition is translated in practice into a softmax across modules and top-\textit{k} selection. Instead, we argue, modularity at the task level should reflect the fact that tasks fall into a hierarchy where more complex ones subsume simpler ones (e.g., dialogue requires both intention classification and text generation). Hence, variable-size subsets of skills should be allowed. As a consequence, we assume that the matrix $Z \in \{0, 1\}^{|{\cal T}| \times |{\cal S}|}$ representing task--skill allocations is a soft partition: each cell $z_{ij}$ is a binary scalar indicating if module ${\boldsymbol \varphi}_j$ is active for a certain task ${\cal T}_i$. However, being discrete, such a binary matrix is not differentiable and therefore cannot be learned end-to-end via gradient descent. Instead, we implement it as a collection of continuously relaxed Bernoulli distributions through a Gumbel-sigmoid \citep{maddison2016concrete,jang2016categorical}, which ensures stochasticity while allowing for differentiable sampling: \begin{align} \label{eq:allocation} \hat{z}_{i,j} &= \sigma \left[ \log \frac{\sigma({z}_{i,j}) \, u}{(1 - \sigma({z}_{i,j})) \, (1 - u)}^{1/\tau}\right] \nonumber \\ u &\sim \mathrm{Uniform}(0, 1). \end{align} In principle, either a coarse-grained soft partition can be learned globally for the entire neural network, or different fine-grained soft partitions can be assigned to each layer. We opt for the second alternative as it affords the model more flexibility and, foreshadowing, yields superior performance. Therefore, $Z$ and $\Phi$ are henceforth assumed to be layer-specific, although we will omit layer indexes in the notation for simplicity's sake. \subsection{Skill-specific Parameters} Given the matrix row $\hat{Z}_{i,\star}$ for task ${\cal T}_i$ from \cref{eq:allocation} and a matrix of skill-specific parameters $\Phi \in \mathbb{R}^{|{\cal S}| \times d}$, where $d$ is the dimension of the layer parameters, the aggregate of the parameters of active skills is superimposed to a base parameterisation ${\boldsymbol \vartheta}_0 \in \mathbb{R}^d$ shared across tasks. For instance, ${\boldsymbol \vartheta}_0$ may be either the initialisation from a pre-trained model or learned from scratch: \begin{align} \label{eq:skillparams} p(y | \mathbf{x}, Z, \Phi, {\cal T}_i) \triangleq p(y | x, {\boldsymbol \vartheta}_i) \nonumber \\ {\boldsymbol \vartheta}_i = {\boldsymbol \vartheta}_0 + \sum_{{\cal S}_j} \Phi_{j,\star} \frac{\hat{z}_{i, j}}{\sum_{{\cal S}_j} \hat{z}_{i,j}}. \end{align} Note that we normalise the rows of the task--skill allocation matrix $\hat{Z}$ prior to composition because the variable number of active skills per task would otherwise affect the norm of the combined parameters ${\boldsymbol \vartheta}_i$, thus making training unstable. \subsection{Inductive Biases} A possible failure mode during training is a collapse into a highly entropic or non-sparse allocation matrix $\hat{Z}$, where all skills are active and skill-specific parameters remain general-purpose rather than specialising. Thus, we also provide an inductive bias to encourage the model to learn a low-entropy, highly-sparse allocation matrix. \paragraph{IBP Prior} A possible inductive bias consists of adding an Indian Buffet Process~\citep[IBP;][]{teh2007stick} prior to $Z$, as IBP is the natural prior for binary matrices representing soft partitions. In particular, this assumes that the $i$-th task is associated with skills used by previous tasks with probability $\mathrm{Bernoulli}(m_{{\cal S}_j} / i)$ (i.e., in proportion to their `popularity') and $\mathrm{Poisson}(\alpha / i)$ new skills, where $m_{{\cal S}_j} = \sum_{{\cal T}_i} z_{i, j}$ is the count of tasks for which skill ${\cal S}_j$ is active. The log-probability of a task--skill allocation matrix under an IBP prior with hyper-parameter $\alpha$ is: \begin{equation} \label{eq:ibp} \begin{aligned} \log p(Z \mid \alpha) &= |{\cal S}| \log \alpha - \sum_{h=1}^{2^{|{\cal T}|}-1} \log Z_h! \\ &- \alpha \sum_{{\cal T}_i} H_{{\cal T}_i} + \sum_{{\cal S}_j} \bigl[ \log (|{\cal T}| - m_{{\cal S}_j})! \\ &+ \log (m_{{\cal S}_j} - 1)! - \log (|{\cal T}|)! \bigr] \end{aligned} \end{equation} where $H_n$ is the $n$-th harmonic number and $Z_h$ is the number of skills possessing the history $h$ (the binary vector of their corresponding column in the matrix $Z$). While training a neural network, the prior probability in \cref{eq:ibp} can be taken into account in the form of a regulariser subtracted to the main loss function. \paragraph{Two-speed Learning Rate} As a simpler inductive bias alternative to the IBP prior, we also experiment with setting the learning rate for $Z$ higher than for $\Phi$. Intuitively, by accelerating learning of the soft partition matrix, to minimise the loss it becomes more convenient to discover better task--skill allocations over settling for general-purpose parameters that are agnostic with respect to the subset of active skills. \subsection{Parameter Efficiency} \label{ssec:parameff} In order to keep the skills modular, each of them must correspond to a separate layer parameterisation. Nevertheless, this may lead to a significant increase in both time and space complexity. Thus, we explore parameter-efficient implementations of $\Phi$ that only add a negligible amount of parameters to the base model. In particular, we contemplate both sparse and low-rank approximations. \paragraph{Sparse Approximations} Lottery Ticket Sparse Fine-Tuning \citep[LT-SFT;][]{ansell2021composable} learns a highly sparse vector of differences with respect to a base model ${\boldsymbol \vartheta}_0$. In our setting, this amounts to identifying a binary matrix $M \in \{0, 1\}^{|{\cal S}| \times d}$ indexing non-zero entries in $\Phi$.\footnote{We leverage PyTorch \texttt{sparse\_coo\_tensor} for implementation.} We infer $M$ by selecting the top-$k$ entries in $\Phi$ based on their change in magnitude after a few early episodes: \begin{equation} \mu_{i, j} \gets \begin{cases} 1 & \mathrm{if} \; \phi_{i, j} \in \mathop{\mathrm{argmax}}_{\phi_1, \dots, \phi_k} |\Phi^\prime - \Phi| \\ 0 & \mathrm{otherwise} \end{cases} \end{equation} The advantage of LT-SFT over other methods is that it is architecture-agnostic. However, it suffers from high space complexity during the early phase of training. \paragraph{Low-rank Approximations} Other parameter-efficient methods are designed for Transformer architectures specifically. For instance, Low-Rank Adapters \citep{hu2021lora} factorise each weight of the linear projections inside self-attention layers as a multiplication between two low-rank matrices. Hence, a linear projection $f_{\boldsymbol \varphi}\ : \mathbb{R}^i \rightarrow \mathbb{R}^o$ is implemented as: \begin{equation} \label{eq:lora} \mathbf{x}^\prime = [W_{0} + (\mathbf{z}^\top A B)] \mathbf{x} + \mathbf{b}_0 \end{equation} where $A \in \mathbb{R}^{|{\cal S}| \times o \times r}$, $B \in \mathbb{R}^{|{\cal S}| \times r \times i}$, and $r$ is the rank. Hence, $\Phi \triangleq \textrm{flatten}(AB)$. \subsection{Baselines} We measure the performance of our \textbf{\sc {Skilled}}\xspace approach, where we learn the skill--task allocation matrix $Z$ end-to-end, against the following baselines: \begin{itemize}[leftmargin=12pt] \itemsep0pt \item \textbf{\sc {Private}}\xspace: there is a separate model parameterisation for each task. During few-shot adaptation, given that ${\cal T}_{train} \cap {\cal T}_{eval} = \emptyset$, this model cannot benefit from any transfer of information between training and evaluation tasks. This is equivalent to the special case where the task--skill allocation matrix is an identity matrix $Z = I$ of size ${|{\cal T}| \times |{\cal T}|}$ and $|{\cal S}| = |{\cal T}|$. \item \textbf{\sc {Shared}}\xspace: a shared skill is learnt on the training tasks and then fine-tuned for each evaluation task separately. This is equivalent to the special case where the task--skill allocation matrix is a matrix of ones $Z = \mathbf{1}$ of size $|{\cal T}| \times 1$ and $|{\cal S}| = 1$. \item \textbf{\sc {Expert}}\xspace, where the task--skill allocation is contingent on expert knowledge about task relationships. Crucially, $Z$ is fixed \textit{a priori} rather than being learned. \end{itemize} \noindent In addition, we compare our \textbf{\sc {Skilled}}\xspace method to a state-of-the-art baseline for multitask learning where parameters are softly shared, \textbf{\sc {Hyper\-Former}}\xspace \citep{mahabadi2021parameter}. This method takes inspiration from \citet{ponti2020parameter} and generates adapters for the pre-trained model parameters with hyper-networks conditioned on task embeddings. In particular, parameters for task ${\cal T}_i$ are obtained as: \begin{equation} \mathbf{x}^\prime = [W_0 + f_A({\cal T}_i) \, f_B({\cal T}_i)] \mathbf{x} + \mathbf{b}_0 \end{equation} where each $f_W({\cal T}_i) \triangleq W_2[\mathrm{ReLU}(W_1\mathrm{e}({\cal T}_i))]$ is a hyper-network, $\mathrm{e}({\cal T}_i)$ is the embedding of task ${\cal T}_i$, $W_1 \in \mathbb{R}^{h \times e}$ and $W_2 \in \mathbb{R}^{d \times h}$ for hidden size $h$ and task embedding size $e$. Note that, in our case, we generate LoRA rather than Adapter layers, contrary the original formulation of \citet{mahabadi2021parameter}, in order to make the baseline comparable to the implementation of \textbf{\sc {Skilled}}\xspace in \cref{eq:lora}. \section{Reinforcement Learning Experiments} \subsection{Dataset} As a proof-of-concept experiment, we perform multitask reinforcement learning on the BabyAI platform \citep{chevalier-boisvert2018babyai}. This benchmark consists in a series of increasingly complex levels, where an agent must execute a linguistic command by navigating a two-dimensional grid world and manipulating objects. Crucially, levels are procedurally generated to reflect different subsets of skills (e.g., \textsc{PickUp}, \textsc{Unlock}, \dots). This enables us to test our model in a controlled setting where performance based on learned skills can be compared with `ground truth' skills. In particular, we focus on a similar subset of 8 levels as \citet{hui2020babyai}: \textsc{GoToObj}, \textsc{GoToRedBallGrey}, \textsc{GoToRedBall}, \textsc{GoToLocal}, \textsc{PutNextLocal}, \textsc{PickupLoc}, \textsc{GoToObjMaze}, \textsc{GoTo}. During each episode within a level, the visual input is a 7 by 7 grid of tiles, a partial observation of the environment based on the agent's field of view at the current time step. Each tile consists of 3 integers corresponding to the properties of a grid cell: object type, colour, and (optionally for doors) if they are open, closed, or locked. The linguistic instructions in English may require to complete multiple goals (via coordination) or express a sequence of sub-goals (via temporal markers). \subsection{Experimental Setup} \paragraph{Model Architecture} The neural architecture adheres to the best model reported in \citet{hui2020babyai}, \textsc{bow\_endpool\_res}. It encodes the linguistic input through a Gated Recurrent Unit \citep[GRU;][]{cho2014properties} and the visual input through a convolutional network (CNN). These two streams from different modalities are then merged into a single representation through FiLM \citep{perez2018film}. This component performs a feature-wise affine transformation of the CNN output conditioned on the GRU output. Afterwards, a Long Short-Term Memory network \citep[LSTM;][]{hochreiter1997long}, a recurrent module keeping track of the agent state trajectory, receives the multimodal representation and returns the current hidden state. This in turn is fed into two distinct MLPs, an actor and a critic \citep{sutton1984temporal}. The actor yields a distribution over actions, whereas the critic a reward baseline for the current state. In our experiments, each row of the matrix $\Phi$ corresponds to a possible parameterisation for all these components. To determine \textit{a priori} a skill--task allocation for the \textbf{\sc {Expert}}\xspace baseline, we harness the information about the skills employed to procedurally generate each level by \citet[p.\ 6]{chevalier-boisvert2018babyai}, which are indicated in \cref{tab:babyai_task_allocation}. For the \textbf{\sc {Skilled}}\xspace model, we set $|{\cal S}| = 9$ similarly to \textbf{\sc {Expert}}\xspace. This allows us to compare learned skills and `ground-truth' skills from an inventory of identical size. As a parameter-efficient implementation of $\Phi$, we employ LT-SFT \citep{ansell2021composable} with a sparsity of $90\%$. For all model variants, ${\boldsymbol \vartheta}_0$ and $\Phi$ are both initialised from a Kaiming uniform and learnable. During training, we sample levels uniformly. \paragraph{Hyper-parameters} We follow closely the best hyper-parameter setup of \citet{hui2020babyai}. Tiles in the visual input are encoded into embeddings of size 128 via a look-up table. The CNN has 2 layers, filter size 3, stride 1, and padding 1; whereas the FiLM module has 2 layers. A residual layer is added between the CNN output and each of the FiLM layers. The output of FiLM is max-pooled with a layer of size 7 and stride 2. Both the LSTM and the GRU have a hidden size of 128. A learning rate of 1e-4 is adopted for Adam \citep{kingma2014adam}. We optimise the model with Proximal Policy Optimisation \citep[PPO;][]{schulman2017proximal} and Back-Propagation Through Time \citep[BPTT;][]{werbos1990backpropagation}. Additionally, we use an Advantage Actor--Critic \citep[A2C;][]{wu2017scalable} with Generalised Advantage Estimation \citep[GAE;][]{schulman2015high}. The reward is calculated as $(1 - 0.9 \, n / n_{\max})$ if the agent completes a task---where $n$ is the number of steps required and $n_{\max}$ is a threshold set according to the level difficulty, $0$ otherwise. Returns are discounted by $\gamma$ = 0.99. \subsection{Results} We now measure whether our latent-skill model facilitates sample efficiency, which following \citet{chevalier-boisvert2018babyai} is defined as the number of episodes required for an agent to reach a success rate greater than $0.99$. Success in turn is defined as executing an instruction in a number of steps $n < n_{\max}$, where the threshold again depends on the level complexity. We plot our results in \cref{fig:sampleffbabyai}. Firstly, models sharing information across tasks (either fully or mediated by skills) enjoy higher sample efficiency than assigning disjoint parameters for each task (\textbf{\sc {Private}}\xspace), as they can borrow statistical strength from each other. Crucially, among information-sharing models, \textbf{\sc {Skilled}}\xspace (where knowledge is modular) surpasses \textbf{\sc {Shared}}\xspace (where knowledge is entangled among tasks). Thus, considering a task as a collection of fine-grained skills that can be separated and reused is the most effective way of sharing information. Finally, results surprisingly show that learning a task--skill allocation matrix end-to-end (\textbf{\sc {Skilled}}\xspace) is more beneficial than leveraging the ground-truth task--skill decomposition used to create the BabyAI levels (\textbf{\sc {Expert}}\xspace). This highlights the fact that different tasks might mutually benefit in ways that go beyond what is posited \textit{a priori} by experts, and that our proposed approach can successfully uncover and exploit such task synergies. Moreover, we run several ablations to study the impact of the inductive biases and the parameter-efficient implementation. We report the number of episodes required to reach a success rate $> 0.99$ in \cref{tab:rlsampleff}, comparing the \textbf{\sc {Skilled}}\xspace model in the standard setup (with two-speed learning rates and sparse skill-specific parameters) with other variants (with an IBP prior or fully dense skill-specific parameters). We find that adding an IBP prior with $\alpha=5$ does not affect the performance significantly. Hence, for the remainder of the experiments, we will adopt two-speed learning rates as an inductive bias. On the other hand, employing fully dense skill-specific parameters increases sample efficiency, albeit to a limited degree. Thus, we verify that parameter sparsification is an effective trade-off between performance and space complexity. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{figures/babyai-success_rate} \caption{Smoothed sample efficiency (success rate vs.\ number of episodes) for different multitask models across 8 levels of BabyAI.} \label{fig:sampleffbabyai} \end{figure} \begin{table*}[t] \footnotesize \begin{tabularx}{\textwidth}{>{\sc \scriptsize}l >{\scriptsize}l|P|PPPPP} \toprule Task & Metric & \citet{ye-etal-2021-crossfit} & Shared & Private & Expert & HyperFormer & Skilled \\ \midrule ag-news & C--F1 & 84.6 $\pm$ \hspace{4pt}1.4 & 59.6 $\pm$ 21.1 & 74.7 $\pm$ 10.2 & 47.0 $\pm$ \hspace{4pt}9.9 & 64.6 $\pm$ 13.4 & 81.2 $\pm$ \hspace{4pt}8.0 \\ ai2-arc & Acc & 22.8 $\pm$ \hspace{4pt}1.9 & 23.7 $\pm$ \hspace{4pt}2.4 & 20.3 $\pm$ \hspace{4pt}0.8 & 28.3 $\pm$ \hspace{4pt}3.7 & 23.8 $\pm$ \hspace{4pt}6.7 & 22.3 $\pm$ \hspace{4pt}3.4 \\ amazon-polarity & C--F1 & 92.2 $\pm$ \hspace{4pt}0.6 & 92.4 $\pm$ \hspace{4pt}2.8 & 94.4 $\pm$ \hspace{4pt}0.4 & 57.4 $\pm$ \hspace{4pt}3.1 & 93.8 $\pm$ \hspace{4pt}1.5 & 93.7 $\pm$ \hspace{4pt}0.9 \\ bsn-npi-licensor & Acc & 99.9 $\pm$ \hspace{4pt}0.2 & 99.9 $\pm$ \hspace{4pt}0.0 & 99.9 $\pm$ \hspace{4pt}0.0 & 99.9 $\pm$ \hspace{4pt}0.0 & 99.9 $\pm$ \hspace{4pt}0.0 & 99.9 $\pm$ \hspace{4pt}0.2 \\ bsn-npi-scope & Acc & 85.7 $\pm$ 13.0 & 99.8 $\pm$ \hspace{4pt}0.3 & 99.6 $\pm$ \hspace{4pt}0.9 & 99.9 $\pm$ \hspace{4pt}0.2 & 99.9 $\pm$ \hspace{4pt}0.0 & 99.9 $\pm$ \hspace{4pt}0.2 \\ break-QDMR & EM & 4.8 $\pm$ \hspace{4pt}0.4 & 4.1 $\pm$ \hspace{4pt}0.5 & 1.9 $\pm$ \hspace{4pt}1.7 & 4.1 $\pm$ \hspace{4pt}0.9 & 3.8 $\pm$ \hspace{4pt}1.2 & 4.9 $\pm$ \hspace{4pt}0.6 \\ circa & C--F1 & 42.3 $\pm$ \hspace{4pt}7.8 & 44.3 $\pm$ \hspace{4pt}7.5 & 22.2 $\pm$ \hspace{4pt}6.3 & 13.0 $\pm$ \hspace{4pt}7.0 & 25.0 $\pm$ \hspace{4pt}6.3 & 45.9 $\pm$ \hspace{4pt}5.7 \\ crawl-domain & EM & 20.7 $\pm$ \hspace{4pt}2.0 & 40.9 $\pm$ \hspace{4pt}2.2 & 36.2 $\pm$ \hspace{4pt}6.3 & 37.1 $\pm$ \hspace{4pt}5.3 & 34.9 $\pm$ \hspace{4pt}3.8 & 39.0 $\pm$ \hspace{4pt}4.2 \\ ethos-disability & C--F1 & 75.3 $\pm$ \hspace{4pt}2.2 & 66.9 $\pm$ 11.8 & 64.7 $\pm$ 12.1 & 59.2 $\pm$ 15.8 & 79.4 $\pm$ \hspace{4pt}3.9 & 72.2 $\pm$ \hspace{4pt}5.2 \\ ethos-sexual & C--F1 & 59.7 $\pm$ \hspace{4pt}5.7 & 62.4 $\pm$ \hspace{4pt}8.4 & 71.2 $\pm$ \hspace{4pt}9.8 & 40.3 $\pm$ 11.4 & 76.8 $\pm$ 10.0 & 86.1 $\pm$ \hspace{4pt}2.6 \\ freebase-qa & EM & 1.3 $\pm$ \hspace{4pt}0.1 & 0.7 $\pm$ \hspace{4pt}0.2 & 0.2 $\pm$ \hspace{4pt}0.1 & 1.3 $\pm$ \hspace{4pt}0.5 & 1.6 $\pm$ \hspace{4pt}0.8 & 0.7 $\pm$ \hspace{4pt}0.3 \\ glue-cola & M-Corr & 3.5 $\pm$ \hspace{4pt}6.7 & 12.9 $\pm$ \hspace{4pt}5.5 & 9.1 $\pm$ \hspace{4pt}6.3 & 7.6 $\pm$ \hspace{4pt}5.6 & 6.8 $\pm$ \hspace{4pt}4.2 & 7.1 $\pm$ \hspace{4pt}5.3 \\ glue-qnli & Acc & 74.7 $\pm$ \hspace{4pt}2.9 & 75.5 $\pm$ \hspace{4pt}3.6 & 57.1 $\pm$ \hspace{4pt}7.7 & 56.6 $\pm$ 19.7 & 73.9 $\pm$ \hspace{4pt}3.2 & 78.1 $\pm$ \hspace{4pt}1.6 \\ hatexplain & C--F1 & 44.9 $\pm$ \hspace{4pt}2.5 & 33.1 $\pm$ \hspace{4pt}8.2 & 26.5 $\pm$ \hspace{4pt}7.8 & 11.9 $\pm$ \hspace{4pt}4.0 & 23.2 $\pm$ \hspace{4pt}6.2 & 32.6 $\pm$ 13.6 \\ quoref & QA-F1 & 41.2 $\pm$ \hspace{4pt}1.6 & 46.0 $\pm$ \hspace{4pt}4.4 & 36.3 $\pm$ \hspace{4pt}4.6 & 48.4 $\pm$ \hspace{4pt}4.3 & 41.7 $\pm$ \hspace{4pt}6.5 & 47.3 $\pm$ \hspace{4pt}3.5 \\ race-high & Acc & 30.5 $\pm$ \hspace{4pt}1.5 & 34.0 $\pm$ \hspace{4pt}2.7 & 28.5 $\pm$ \hspace{4pt}1.4 & 38.5 $\pm$ \hspace{4pt}2.0 & 30.8 $\pm$ \hspace{4pt}1.9 & 34.8 $\pm$ \hspace{4pt}2.0 \\ superglue-rte & Acc & 60.4 $\pm$ \hspace{4pt}3.6 & 60.6 $\pm$ \hspace{4pt}2.9 & 49.7 $\pm$ \hspace{4pt}5.1 & 51.7 $\pm$ \hspace{4pt}4.8 & 60.9 $\pm$ \hspace{4pt}3.8 & 60.4 $\pm$ \hspace{4pt}5.9 \\ tweet-eval-irony & C--F1 & 55.2 $\pm$ \hspace{4pt}3.6 & 52.1 $\pm$ \hspace{4pt}8.0 & 50.1 $\pm$ 14.2 & 25.6 $\pm$ \hspace{4pt}8.9 & 38.4 $\pm$ \hspace{4pt}6.0 & 57.2 $\pm$ \hspace{4pt}2.4 \\ wiki-split & Rouge-L & 79.3 $\pm$ \hspace{4pt}0.5 & 80.1 $\pm$ \hspace{4pt}0.6 & 80.3 $\pm$ \hspace{4pt}0.6 & 79.2 $\pm$ \hspace{4pt}0.8 & 79.2 $\pm$ \hspace{4pt}0.7 & 80.6 $\pm$ \hspace{4pt}0.3 \\ yelp-polarity & C--F1 & 71.8 $\pm$ 21.1 & 88.3 $\pm$ 14.9 & 65.0 $\pm$ 20.5 & 53.9 $\pm$ 12.7 & 95.0 $\pm$ \hspace{4pt}0.9 & 94.5 $\pm$ \hspace{4pt}1.1 \\ \hline all & Avg & 52.5 $\pm$ 30.8 & 53.9 $\pm$ 30.5 & 49.4 $\pm$ 31.7 & 43.0 $\pm$ 29.0 & 52.7 $\pm$ 33.2 & \textbf{56.9} $\pm$ \textbf{32.3} \\ \bottomrule \end{tabularx} \caption{Few-shot adaptation results of \textbf{\sc {Skilled}}\xspace and four baselines, as well as the original model from \citet{ye-etal-2021-crossfit}. Results are reported both in aggregate and separately for each task in ${\cal T}_{eval}$. For the full name of the metrics, refer to \cref{ssec:sldata}.} \label{tab:ft} \vspace{-4mm} \end{table*} \section{Supervised Learning Experiments} \subsection{Dataset} \label{ssec:sldata} In order to measure the benefits of a modular design for systematic generalisation to new tasks, we run a second set of experiments on CrossFit \citep{ye-etal-2021-crossfit}, a benchmark including 160 diverse natural language processing tasks sourced from Huggingface Datasets \citep{lhoest2021datasets}. The tasks in CrossFit are all converted into a unified text-to-text format inspired by \citet{raffel2020exploring}. Moreover, they are partitioned into three disjoint subsets. First, a model is pre-trained in a multitask fashion on training tasks ${\cal T}_{train}$. Afterwards, it is adapted to each evaluation task from ${\cal T}_{eval}$ in a few-shot learning setting. Hyper-parameter are tuned on the held-out set ${\cal T}_{dev}$. We adopt the partition 1 (called \textsc{Random}) from \citet{ye-etal-2021-crossfit}, where $|{\cal T}_{train}| = 120$, $|{\cal T}_{dev}| = |{\cal T}_{eval}| = 20$, and tasks are split randomly. This is the most comprehensive partition and most suited for general-purpose models, as it includes all types of tasks. Every task is associated with 5 different few-shot data splits for train ${\cal D}_{train}$ and development ${\cal D}_{dev}$ and 1 larger data split for evaluation ${\cal D}_{eval}$. During multitask pre-training, we concatenate all train and development splits of datasets from ${\cal T}_{train}$, whereas during few-shot adaptation we use the splits of datasets in ${\cal T}_{eval}$ separately in 5 distinct runs. We measure the performance of a model with 7 evaluation metrics according to the type of task: C[lassification]-F1, Acc[uracy], QA-F1, E[xact] M[atch], Rouge-L, M[atthew]-Corr[elation], and P[earson]-Corr[elation]. \begin{figure*}[t] \centering \includegraphics[width=\textwidth]{figures/mtl_bar_hf.pdf} \par\vspace{2mm} \includegraphics[width=\textwidth]{figures/mtl_bar_sk.pdf} \caption{Delta in performance in terms of task-specific metrics between \textbf{\sc {Skilled}}\xspace (top) and \textbf{\sc {Hyper\-Former}}\xspace (bottom) on the one hand and \textbf{\sc {Shared}}\xspace on the other, across 120 seen CrossFit tasks after multitask pre-training.} \label{fig:mlt_bar} \vspace{-2mm} \end{figure*} \subsection{Experimental Setup} \paragraph{Model Architecture} As pre-trained weights ${\boldsymbol \vartheta}_0$ for conditional text generation, we choose BART Large \citep{lewis-etal-2020-bart}, a 24-layer Transformer-based encoder--decoder. We use LoRA \citep{hu2021lora} to implement skill-specific parameters efficiently, as it was explicitly designed for the Transformer architecture and has lower space complexity that LT-SFT during the early phases of training (cf.\ \cref{ssec:parameff}). While ${\boldsymbol \vartheta}_0$ remains frozen for all model variants, $A$ matrices in $\Phi$ (and $f_A(\cdot)$ in \textbf{\sc {Hyper\-Former}}\xspace) are initialised to zero matrices following \citet{hu2021lora}. As a source of expert knowledge for the \textbf{\sc {Expert}}\xspace baseline, we associate each task to a unique skill corresponding to one of the 4 task types of \citet[p.\ 20]{ye-etal-2021-crossfit}'s taxonomy: question answering, conditional text generation, classification, or other (e.g., regression). The skill inventory size for \textbf{\sc {Skilled}}\xspace was chosen among $\{2, 4, 8, 16, 32\}$ based on validation. We set the embedding size \textit{e} and hidden size \textit{h} of \textbf{\sc {Hyper\-Former}}\xspace to an identical value to ensure a fair comparison. \paragraph{Hyper-parameters} During both multitask pre-training and few-shot adaptation, we use the Adam optimiser \citep{kingma2014adam} and select a learning rate for $\Phi$ among $\{1e-2, 1e-3, 1e-4\}$ based on performance on the development set of ${\cal T}_{train}$ and ${\cal T}_{dev}$, respectively. As a more aggressive learning rate for $Z$ in \textbf{\sc {Skilled}}\xspace instead we search in the range $[1e-1, 1e-2]$. We run multitask pre-training for 30 epochs with an effective batch size of 32, with a warm-up of 6\% of the total steps. Instead, during few-shot adaptation, the effective batch size is 8 for 1000 training steps, with a warm-up rate of 10\% and a weight decay of 1e-2. For a comparison of parameter counts, LoRA adds $4l(2hr + |{\cal T}|) \cdot |{\cal S}|$ parameters to the pre-trained model, where $l$ is the number of layers in the encoder and decoder, $h$ is the hidden size, and $4$ is the number of linear projections in self-attention (query, key, value, output). We use $r=16$, $l=24$ and $h=1024$ for BART Large, so we add $\sim 3 \cdot 10^6$ parameters per skill. Given that the pre-trained model has $\sim 4 \cdot 10^8$ parameters, this implies an increase of $\sim 0.78\%$ per skill. \textbf{\sc {Hyper\-Former}}\xspace adds $4l(2he + 2e) \cdot e$ parameters, an increase of $\sim 0.78\%$ per task embedding dimension. \subsection{Results} \paragraph{Few-shot Adaptation to New Tasks} In the few-shot adaptation setting, our goal is to evaluate the capability of the model to quickly generalise to new tasks unseen during training. This is the most realistic setting as tasks encountered by models deployed `in the wild' will be characterised by different distributions or involve different input / output spaces. Performance in terms of task-specific metrics is reported in \cref{tab:ft} for the 20 evaluation tasks individually and on average. Crucially, results show that \textbf{\sc {Skilled}}\xspace outperforms alternative formulations of the task--skill allocation matrix, such as \textbf{\sc {Shared}}\xspace, \textbf{\sc {Private}}\xspace and \textbf{\sc {Expert}}\xspace. Importantly, we note that \textbf{\sc {Skilled}}\xspace also surpasses \textbf{\sc {Hyper\-Former}}\xspace by a sizeable margin despite the two models having comparable parameter counts. This points to the fact that explicitly modularising knowledge learnt during multitask training is important for systematic adaptation to unseen tasks, whereas entangled knowledge is more brittle to distribution shifts in cross-task transfer. Finally, we corroborate the soundness of our experimental setup by reproducing the results of~\citet{ye-etal-2021-crossfit}.\footnote{Note that in \citet{ye-etal-2021-crossfit} the pre-trained model is BART Small and all parameters are fine-tuned. Hence, these results are not directly comparable.} \paragraph{Multitask Evaluation on Seen Tasks} Moreover, to ensure that modularity does not adversely affect in-domain performance, we evaluate models on the test sets of seen tasks after multitask training. The results are shown in \cref{tab:multitask}. \textbf{\sc {Skilled}}\xspace achieves average improvements of up to \textasciitilde3\% in the global metrics with respect to \textbf{\sc {Shared}}\xspace by flexibly allocating skills to each task. In Figure~\ref{fig:mlt_bar}, we report the delta in performance in terms of task-specific metrics between \textbf{\sc {Skilled}}\xspace and \textbf{\sc {Shared}}\xspace for the 120 training tasks, in most of which \textbf{\sc {Skilled}}\xspace yields positive gains. In this context, we can see that \textbf{\sc {Skilled}}\xspace achieves comparable performance to \textbf{\sc {Hyper\-Former}}\xspace, therefore confirming that explicit modularisation can be as effective as conditional parameter generation when evaluated on seen tasks, but also engenders vast improvements on held-out tasks. \paragraph{In-Depth Analysis of Learned Skills} Finally, we run an in-depth analysis of the task--skill allocation matrices $Z$ learned by \textbf{\sc {Skilled}}\xspace. Specifically, we measure: \begin{enumerate}[leftmargin=12pt] \itemsep0pt \item \textit{Discreteness}. How close is the continuous relaxation to a binary matrix? To this end, we report the average normalised entropy across all probabilities in the cells of the matrix: \begin{equation} \mathrm{Discrete}(Z) = \frac{1}{|{\cal T}| \cdot |{\cal S}|} \sum_{{\cal T}_i} \sum_{{\cal S}_j} \frac{\mathcal{H}(z_{ij})}{\log 2} \end{equation} \item \textit{Sparsity}. How many skills are active per task on average? We count the rate of non-zero cells in the values rounded to the closest integer: \begin{equation} \mathrm{Sparsity}(Z) = \frac{1}{|{\cal T}| \cdot |{\cal S}|} \sum_{{\cal T}_i} \sum_{{\cal S}_j} \lfloor {z}_{ij} \rceil \end{equation} \item \textit{Usage}. Is the allocation of skills across tasks balanced or are some preferred over others? We provide the normalised entropy of a categorical distribution parameterised by $\sum_j Z_{\star, j}$, the sum of the columns of $Z$: \begin{equation} \mathrm{Usage}(Z) = \frac{\mathcal{H} \left[ \sum_{{\cal T}_i} z_{i, \star} \right]}{ \log |{\cal S}|} \end{equation} \end{enumerate} Note that the entropy values are normalised into the range $[0, 1]$ to make them invariant to the number of skills: this quantity is known as `efficiency'. We plot these metrics---as well as the performance on in-domain train tasks in terms of exact match---as a function of the skill inventory size in \cref{fig:skillsearch}. We find that, whilst a continuous relaxation, the learned matrices are highly discretised and all their values are extremely close to either 0 or 1. Moreover, the level of sparsity decreases as the number of skills increases. This means that smaller subsets of skills are required in proportion due to the diversity of available skills. Finally, usage is consistently near the maximum value, which implies that there is uniformity in how frequently each skill is active across tasks. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{figures/skill_analysis_2} \caption{Statistics of the task--skill matrices for different choices of skill inventory size, including: discreteness, sparsity, usage, and the average exact match on the development set of 120 CrossFit tasks.} \label{fig:skillsearch} \end{figure} \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{figures/Z_s4} \caption{Posterior over $Z$ in \textbf{\sc {Skilled}}\xspace for $|\mathcal{S}| = 4$.} \label{fig:Z_s4} \end{figure} \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{figures/dendro_2} \caption{Task partitions for $|\mathcal{S}| = 4$, which corresponds to $2^{|\mathcal{S}|} = 16$ possible subsets of skills.} \label{fig:dendro} \end{figure} Overall, these results demonstrate that a quasi-binary, highly-sparse, and non-trivial allocation matrix can be successfully learned in an end-to-end fashion even with simple inductive biases such as a two-speed learning rate. For instance, we visualise the posterior of $Z$ for $|{\cal S}| = 4$ in \cref{fig:Z_s4}. Crucially, the learned allocation also facilitates the interpretability of black-box multitask models. In fact, the structure of $Z$ corresponds to an explicit hierarchy of tasks, where simpler ones are subsumed by more complex ones, and similar tasks can be grouped into the same category if they share the same subset of skills. We plot this hierarchy as a dendrogram in \cref{fig:dendro}. For instance, most \textsc{GLUE} tasks \citep{wang-etal-2018-glue} are grouped together as they are all focused on natural language understanding: for instance, they require skill 1 (\textsc{cola}), 2 (\textsc{mrpc, rte, sst2, wnli}), or both 1 and 2 (\textsc{mnli, qqp}). \section{Related Work} \paragraph{Modular Networks} The idea of modularising neural network computation by decomposing it into a subset of specialised sub-systems has long been sought as a way to achieve better generalisation to unseen inputs~\citep{jacobs1991adaptive,andreas2016nmn,kirsch2018modular}, tasks~\citep{jacobs1991task,alet2018modular,ruder2019latent} and recently to improve continual learning~\citep{ostapenko2021continual} and robustness to changes in the environment~\cite{goyal2019recurrent}. Modular networks fall in the category of conditional computation methods, where modules are chosen dynamically given the input~\citep{gulcehre2016dynamic}. In routing networks~\citep{rosenbaum2019routing}, the system makes hard decisions about which modules to use and learns the structure in which modules are composed~\citep{andreas2016nmn, alet2018modular}.~\citet{andreas2016nmn} learn the structure using an external parser while~\citet{alet2018modular} recur to a stochastic process in which structures are sampled with simulated annealing. In mixture of experts (MoE) approaches, the system selects a potentially sparse, soft subset of modules depending on the input to be processed~\citep{jacobs1991adaptive,shazeer2017outrageously}. MoEs can be interpreted from the point of view of independent mechanisms~\citep{parascandolo2018learning} that~\citet{goyal2019recurrent} further extend to handle sequential problems. In the context of NLP,~\citet{fedus2021switch} successfully used a MoE architecture to scale large language model pre-training to trillions of parameters. In contrast to previous approaches, our model conditions the computation on the task rather than on task inputs. There have been related attempts to enforce parameter reuse and modularity for multitask learning~\citep{rajendran2017adaapt,ponti2020parameter,kingetsu2021neural,kudugunta2021beyond}.~\citet{rajendran2017adaapt} learn separate modules for each task and then learn how to reuse those modules for a new task.~\citet{kudugunta2021beyond} uses a set of modules for each task in a multi-lingual translation setting. Our approach does not assume a set of modules for each task but instead decomposes a task into a set of skills themselves reusable across tasks. \paragraph{Multitask NLP} Multitask learning for NLP has been an effective strategy for improving model performance in low-resource tasks and for quickly adapting to new, unseen tasks~\cite{ruder2019latent,liu2019multi,min2021metaicl,wei2021finetuned,aribandi2021ext5,sanh2022multitask,mahabadi2021parameter,rusu2019meta}, languages \citep{ponti2019modeling}, and modalities \citep{bugliarello2022iglue}.~\citet{liu2019multi} adopt a multitask training strategy with a shared model and achieve impressive performance on GLUE. However, the method still requires task-specific fine-tuning. Rather than re-training all the model parameters,~\citet{houlsby2019parameter} proposes to train task-specific adapters.~\citet{pfeiffer2020adapterfusion} share information across task-specific adapters while alleviating negative task interference. Instead of using adapters, in our experiments we parameterise our skills with LT-SFT \citep{ansell2021composable} or LoRA~\citep{hu2021lora}, which achieve comparable or superior performance. Recently,~\citet{mahabadi2021parameter} ensure cross-task information sharing by using a hyper-network to generate task-specific adapters. Differently, our task-specific parameters are composed of a set of skills from a shared inventory, which makes our approach modular and more scalable. \paragraph{Few-shot Task Adaptation} Several multitask approaches specifically target adaptation to new tasks, such as meta-learning approaches~\citep{alet2018modular, rusu2019meta,ponti-etal-2021-minimax, garcia2021meta,ostapenko2021continual}. In our paper, we efficiently achieve few-shot task adaptation by inferring the task--skill allocation matrix for new tasks and fine-tuning skill parameters, which were previously learned via multitask learning. In fact, \citet{ye-etal-2021-crossfit} found that this pre-training routine is superior to meta-learning in CrossFit. A similar attempt to recompose modular knowledge learnt on previous tasks has been recently explored by~\citet{ostapenko2021continual}. \section{Conclusions} In this work, we argued that a modular design is crucial to ensure that neural networks can learn from a few examples and generalise robustly across tasks by recombining autonomous facets of knowledge. To this end, we proposed a model where a subset of latent, discrete skills from a fixed inventory is allocated to each task in an end-to-end fashion. The task-specific instantiation of a neural network is then obtained by combining efficient parameterisations of the active skills, such as sparse or low-rank adapters. We evaluate the sample efficiency of our model on multitask instruction following through reinforcement learning and its few-shot adaptability on multitask text-to-text generation through supervised learning. In both experiments, we surpass competitive baselines where parameters are fully shared, task-specific, combined according to expert knowledge, or generated conditionally on the task. Finally, we show that our model facilitates interpretability by learning an explicit hierarchy of tasks based on the skills they require.
{'timestamp': '2022-03-02T02:29:35', 'yymm': '2202', 'arxiv_id': '2202.13914', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13914'}
arxiv
\section{Introduction and Related Work}\label{sec:intro} Many important tasks involve making and breaking contact. As humans, we make contact with the environment to move ourselves through it (locomotion), as well as to move objects relative to ourselves (manipulation). Earlier work on robot locomotion and manipulation focused primarily on predefined contact sequences from reduced-order models (for locomotion) \cite{wieber2016modeling} or grasping heuristics (for manipulation) \cite{mason2018toward}. More recently, there has been a trend toward discovering contact sequences automatically using trajectory optimization. Contact-implicit trajectory optimization has been used to generate a wide variety of behaviors for manipulation and locomotion \cite{tassa2012synthesis,posa2014direct,manchester2020variational,aydinoglu2021real,patel2019contact,onol2020tuning,cleac2021fast}. Furthermore, this approach can not only synthesize but also stabilize contact-rich trajectories, either through Model Predictive Control (MPC) or with local feedback generated by optimization algorithms like iLQR \cite{li2004iterative}. The major promise of contact-implicit trajectory optimization---reliable automated generation of contact-rich behaviors---has yet to be realized, however. This is largely due to two conflicting challenges: numerical reliability and physical realism. Complementarity-based rigid contact models \cite{anitescu1997formulating} are physically accurate but lead to non-smooth system dynamics, which present a challenge for gradient-based optimization. While there has been significant recent progress in developing numerically stable optimization algorithms for such rigid contact, existing techniques are typically limited to simple (often linear) dynamics \cite{aydinoglu2021real} or relatively simple contact configurations \cite{sleiman2019contact,carius2018trajectory}. On the other hand, compliant contact models such as that used in the MuJoCo simulator \cite{todorov2014convex} are amenable to gradient-based trajectory optimization techniques like iLQR, and have resulted in many impressive simulation demonstrations involving incredibly complex contact configurations and high degree-of-freedom systems \cite{tassa2012synthesis,patel2019contact,onol2020tuning,chatzinikolaidis2021trajectory}. But these contact models include non-physical force-at-a-distance and ``gliding'' artifacts, often resulting in trajectories that are difficult to reproduce on hardware. \begin{figure} \begin{subfigure}{0.49\linewidth} \centering \includegraphics[width=\linewidth]{figures/lift_simulation.png} \caption{} \label{fig:lift_simulation} \end{subfigure} \begin{subfigure}{0.49\linewidth} \centering \includegraphics[width=\linewidth]{figures/lift_hardware.png} \caption{} \label{fig:lift_hardware} \end{subfigure} \begin{subfigure}{\linewidth} \centering \includegraphics[width=0.7\linewidth]{figures/quadruped_gait.png} \caption{} \label{fig:quad_gait} \end{subfigure} \centering \caption{We show that iLQR over hydoelastic contact \cite{elandt2019pressure} enables reliable synthesis of contact-rich behaviors including whole-arm manipulation (\subref{fig:lift_simulation}) and quadruped gait generation (\subref{fig:quad_gait}). Optimal trajectories for whole-arm manipulation could be directly applied on hardware, with little sim-to-real gap (\subref{fig:lift_hardware}).}. \label{fig:front_page} \end{figure} In this paper, we consider contact-implicit trajectory optimization over the recently proposed pressure-field-based hydroelastic contact model \cite{elandt2019pressure,masterjohn2021discrete}. Hydroelastic contact allows some interpenetration between nominally rigid objects, and computes contact forces based on a surface integral rather than a single point of maximum penetration. In addition to being physically realistic---this contact model can accurately model interactions between complex geometries like the arm and ball shown in Figure~\ref{fig:hydroelastic}---dynamics gradients can be computed with automatic differentiation. We show that iLQR over hydroelastic contact can generate a variety of complex contact-rich behaviors, including whole-arm manipulation for a Kinova Gen3 robot and gait discovery for a Mini Cheetah quadruped. While our simple Python implementation of iLQR was far too slow for real-time MPC, open-loop playback of optimal trajectories on a Kinova Gen3 robot arm resulted in behavior that closely matched the simulation. These preliminary results support the physical realism of the hydroelastic contact model \cite{elandt2019pressure}, and suggest that iLQR over hydroelastic contact is a promising basis for contact-implicit trajectory optimization. The remainder of this paper is organized as follows: a problem formulation is presented in Section~\ref{sec:problem}, a basic overview of hydroelastic contact and iLQR are presented in Section~\ref{sec:background}, we describe simulation and hardware experiments in Sections \ref{sec:simulation} and \ref{sec:hardware}, discuss advantages and limitations in Section~\ref{sec:discussion}, and conclude with Section~\ref{sec:conclusion}. \section{Problem Formulation}\label{sec:problem} In this paper, we consider rigid-body systems in the standard ``manipulator'' form: \begin{equation}\label{eq:multibody_dynamics} \bm{M}(\bm{q})\dot{\v} + \bm{C}(\bm{q},\v)\v + \bm{g}(\bm{q}) = \S^T\bm{\tau} + \sum_{c}\bm{J}_c(\bm{q})^T\bm{f}_c \end{equation} where $\bm{q}$ are generalized positions (e.g. joint angles and free body poses) and $\v$ are generalized velocities (e.g. joint velocities and free body linear/angular velocities). $\bm{M}$ is the positive definite mass matrix, $\bm{C}$ and $\bm{g}$ collect Coriolis/centripetal and gravitational terms, $\bm{\tau}$ are applied joint torques, $\bm{f}_c$ represents the contact wrench associated with contact $c$, and $\bm{J}_c$ is the corresponding Jacobian. The dynamics (\ref{eq:multibody_dynamics}) describe both legged locomotion (where $\bm{q}$ consists of joint angles and a body pose) as well as manipulation (where $\bm{q}$ also includes poses of objects in the environment). We assume that $\bm{q}$ and $\v$ can be measured perfectly at any time. Furthermore, we assume that (\ref{eq:multibody_dynamics}) is discretized as \begin{equation}\label{eq:discrete_dynamics} \bm{x}_{k+1} = f(\bm{x}_k,\u_k), \end{equation} where $\bm{x}_k^T = [\bm{q}_k^T~\v_k^T] \in \mathbb{R}^n$ is the system state at the $k^{th}$ time step and $\u_k = \bm{\tau}_k \in \mathbb{R}^m$ are control inputs. Implicit in this formulation is the fact that contact forces $\bm{f}_c$ are computed at each time step as some function of the state $\bm{x}$ and input $\u$. Importantly, we assume that $f$ is differentiable even when making and breaking contact, i.e., $f_{\bm{x}} = \frac{\partial f(\bm{x},\u)}{\partial \bm{x}}$ and $f_{\u} = \frac{\partial f(\bm{x},\u)}{\partial \u}$ are well-defined for any $\bm{x}$ and $\u$. All of these assumptions are met by the open-source Drake simulator \cite{drake}, which discretizes (\ref{eq:multibody_dynamics}) using the semi-implicit integration scheme described in \cite{castro2020transition}, computes contact wrenches using the hydroelastic contact model \cite{elandt2019pressure,masterjohn2021discrete}, and makes dynamics gradients $f_{\bm{x}}$ and $f_{\u}$ available via automatic differentiation. With this in mind, we aim to solve contact-implicit trajectory optimization problems of the following standard form: \begin{subequations}\label{eq:trajectory_optimization} \begin{align} \min~ & \sum_{k=0}^{N-1}\left\{ \tilde{\bm{x}}_k^T\bm{Q}\tilde{\bm{x}}_k + \u_k^T\bm{R}\u_k\right\} + \tilde{\bm{x}}_N^T\bm{Q}_f\tilde{\bm{x}}_N, \\ \mathrm{s.t.~} & \bm{x}_0 \text{ fixed}, \\ & \bm{x}_{k+1} = f(\bm{x}_k,\u_k), \end{align} \end{subequations} where $\tilde{\bm{x}}_k = \bm{x}_k - \bm{x}^{nom}$ represents an error with respect to a nominal state $\bm{x}^{nom}$, $\bm{Q}$, $\bm{R}$, and $\bm{Q}_f$ are symmetric positive semi-definite weighting matrices, and the contact-implicit nature of the problem comes from the fact that the discretized dynamics (\ref{eq:discrete_dynamics}) account for contact interactions. \section{Background}\label{sec:background} \subsection{Hydroelastic Contact}\label{sec:hydroelastic} In this section we provide a brief overview of hydroelastic contact, also known as Pressure Field Contact (PFC). This approach was first proposed in \cite{elandt2019pressure}, with further refinements in \cite{masterjohn2021discrete}. Further details can be found in these original works, as well as in the Drake documentation \cite{drake}. \begin{figure} \centering \includegraphics[width=0.6\linewidth]{figures/contact_surface_composite.png} \caption{Visualization of hydroelastic contact surfaces between a Kinova Gen3 manipulator arm and a ball in Drake \cite{drake}.} \label{fig:hydroelastic} \end{figure} The basic idea is as follows. Discretization of the multibody dynamics (\ref{eq:multibody_dynamics}) leads to a contact-modeling problem: two bodies may be separate at time $k$, but interpenetrating at time $k+1$. The hydroelastic model resolves this problem by allowing some overlap between nominally rigid objects. Contact forces are a function of the resulting overlap, with larger overlap resulting in larger forces. These overlaps are resolved into contact forces by the pressure field theory described in \cite{elandt2019pressure}. Essentially, each object is associated with an internal pressure field, typically with higher pressures toward the interior of an object. When two objects overlap, the two pressure fields define an equilibrium surface. A contact wrench (force and torque) is defined by integrating over this surface. In practice, this equilibrium surface is defined by user-specified meshes. A visualization of such contact surfaces is shown in Figure~\ref{fig:hydroelastic}. In addition to standard parameters like friction coefficients, hydroelastic contact requires the specification of \textit{hydroelastic modulus} and \textit{dissipation} parameters for each object. The hydroelastic modulus, measured in $Pa(N / m^2)$, defines how the pressure field increases with distance to the center of the object, with lower values corresponding to more compliant behavior. Dissipation, measured in $s/m$, controls how energy is lost during the contact interaction. We refer the interested reader to the Drake documentation \cite{drake} for further details. Two key features of hydroelastic contact make it appealing for contact-implicit trajectory optimization. The first is physical realism: contact rich interactions like that shown in Figure~\ref{fig:hydroelastic} are essential for tasks like whole-arm manipulation, but are notoriously difficult to model accurately. The second is differentiability. Drake's automatic differentiation tools enable simple computation of the dynamics partials $f_{\bm{x}}$ and $f_{\u}$ even through contact. While this is computationally expensive, it is easy to implement and provides an important proof-of-concept regarding the usefulness of the underlying gradients. \subsection{Iterative LQR}\label{sec:ilqr} In this section, we present a brief overview of the iLQR algorithm \cite{li2004iterative}. iLQR and its second-order variant, Differential Dynamic Programming (DDP) \cite{mayne1966second}, are popular due to rapid convergence as well as that fact that a local feedback controller is generated alongside an optimal trajectory. The basic idea behind iLQR is to use a linear approximation of the system dynamics and a quadratic approximation of the optimal cost-to-go to iteratively update a guess of the optimal trajectory. More specifically, DDP/iLQR considers optimal control problems of the form \begin{subequations} \begin{align} \min~ & \sum_{k=0}^{N-1}l(\bm{x}_k,\u_k) + l_f(\bm{x}_N) \\ \mathrm{s.t.~} & \bm{x}_0 \text{ fixed} \\ & \bm{x}_{k+1} = f(\bm{x}_k,\u_k), \end{align} \end{subequations} of which problem (\ref{eq:trajectory_optimization}) is clearly a special case. DDP/iLQR is composed of a sequence of forward and backwards passes. First, the system is simulated forward to produce a nominal trajectory with control inputs $\bar{\u}$ and states $\bar{\bm{x}}$. In the backwards pass, we consider the the optimal cost-to-go $V(\bm{x},k)$ defined by the Bellman equation: \begin{equation*} V(\bm{x},k) = \min_{\u}[l(\bm{x},\u) + V(f(\bm{x},\u),k+1)] = \min_{\u} Q_k(\bm{x},\u), \end{equation*} where $V(\bm{x},N) = l_f(\bm{x})$. We then consider a second-order approximation of $Q_k$ around ($\bar{\u},\bar{\bm{x}}$): \begin{multline*} \delta Q_k(\delta \bm{x}, \delta \u) = Q_k(\bar{\bm{x}}+\delta \bm{x}, \bar{\u}+\delta \u) - Q_k(\bar{\bm{x}},\bar{\u}) \\ \approx \frac{1}{2}\begin{bmatrix}1 \\ \delta \bm{x} \\ \delta \u \end{bmatrix}^T \begin{bmatrix} 0 & Q_{\bm{x}}^T & Q_{\u}^T \\ Q_{\bm{x}} & Q_{\bm{x}\x} & Q_{\bm{x}\u} \\ Q_{\u} & Q_{\u\bm{x}} & Q_{\u\u} \end{bmatrix} \begin{bmatrix}1 \\ \delta \bm{x} \\ \delta \u\end{bmatrix}. \end{multline*} The coefficients of this expansion can be written in terms of the cost-to-go at the following timestep, where we write $V(\bm{x},k+1) = V'$ for conciseness: \begin{subequations} \begin{align} Q_{\bm{x}} &= l_{\bm{x}} + f_{\bm{x}}^TV_{\bm{x}}' \\ Q_{\u} &= l_{\u} + f_{\u}^TV_{\bm{x}}' \\ Q_{\bm{x}\x} &= l_{\bm{x}\x} + f_{\bm{x}}^TV_{\bm{x}\x}' + V_{\bm{x}}' \cdot f_{\bm{x}\x} \\ Q_{\u\u} &= l_{\u\u} + f_{\u}^TV_{\bm{x}\x}' + V_{\bm{x}}' \cdot f_{\u\u} \\ Q_{\u\bm{x}} &= l_{\u\bm{x}} + f_{\u}^TV_{\bm{x}\x}' + V_{\bm{x}}' \cdot f_{\u\bm{x}} \end{align} \end{subequations} The terms involving second-order dynamics partials (e.g., $V_{\bm{x}}' \cdot f_{\bm{x}\x}$) are used in DDP but dropped in iLQR. Including these terms improves convergence \cite{mayne1966second}, but at the cost of additional complexity. While there are promising recent results on computing these second-order terms more efficiently \cite{nganga2021accelerating}, we focus in this paper on iLQR rather than DDP in the interest of easy implementation. To complete the backwards pass, $V_{\bm{x}}$ and $V_{\bm{x}\x}$ at the current timestep can be computed as \begin{subequations} \begin{align} V_{\bm{x}} &= Q_{\bm{x}} - Q_{\u}^TQ_{\u\u}^{-1}Q_{\u\bm{x}} \\ V_{\bm{x}\x} &= Q_{\bm{x}\x} - Q_{\u\bm{x}}^TQ_{\u\u}^{-1}Q_{\u\bm{x}}. \end{align} \end{subequations} The nominal trajectory is then updated in a forward pass, where new control inputs are chosen according to the control law \begin{equation} \u_k = \bar{\u}_k - \epsilon \bm{\kappa}_k - \bm{K}_k(\bm{x}_k -\bar{\bm{x}}_k), \end{equation} where $\bm{K}_k = Q_{\u\u}^{-1}Q_{\u\bm{x}}$, $\bm{\kappa}_k = Q_{\u\u}^{-1}Q_{\u}$, and $\epsilon \in (0,1]$ is a linesearch parameter used to ensure that the cost decreases monotonically. The updated trajectory is used to perform a subsequent backwards pass, and the process repeats until convergence. After convergence, the local control policy \begin{equation}\label{eq:ilqr_local_feedback} \u_k = \bar{\u}_k - \bm{K}_k(\bm{x}_k -\bar{\bm{x}}_k) \end{equation} is optimal in the neighborhood of the nominal trajectory. \section{Simulation Results}\label{sec:simulation} In this section we present simulation results applying iLQR to systems with hydroelastic contact. We used a simple Python implementation of iLQR, available at \url{https://bit.ly/ilqr_hc}. We use the Drake simulator \cite{drake} and Drake's automatic differentiation tools to compute the dynamics partials $f_{\bm{x}}$ and $f_{\u}$. All experiments were performed on a laptop with an Intel i7 processor and 32GB RAM. \subsection{Quadruped Gait Generation} In this section, show how iLQR over hydroelastic contact can be used for automatic gait generation for a Mini Cheetah quadruped \cite{katz2019mini} walking over flat ground. No a-priori contact sequence or reference motions were specified, only a quadratic cost of the form (\ref{eq:trajectory_optimization}), which aims to drive the robot forward at a desired velocity. \begin{figure*} \centering \includegraphics[width=0.8\linewidth]{figures/walk_composite.png} \caption{Simulation snapshots of optimal trajectory with a target velocity of 1 m/s. The contact sequence was not specified a priori, and the solver discovers a gait automatically. Opposite pairs of legs (e.g., front left and back right) tend to move in tandem, similar to the trotting gait exhibited by quadrupeds in nature.} \label{fig:quadruped_composite} \end{figure*} \textbf{Model Details: } The Mini Cheetah has 18 degrees of freedom, from 12 joints and the floating base. The state is \begin{equation} \bm{x}^T = [\bm{q}^T~\v^T] = [\begin{array}{ccc;{2pt/2pt}ccc}\bm{\theta}^T_B&\bm{p}^T_B&\bm{q}^T_J&\bm{\omega}^T_B&\dot{\bm{p}}^T_B&\v^T_J\end{array}], \end{equation} where $\bm{\theta}_B$ is the body orientation (as a quaternion), $\bm{p}_B$ is the body position, $\bm{q}_J$ are joint angles, $\bm{\omega}_B$ is the body angular velocity, $\dot{\bm{p}}_B$ is the body linear velocity, and $\v_J$ are joint velocities. The system is discretized with a $5~ms$ timestep. Contact interactions were only considered between the feet, the ground, and the main body: the collision geometry of the legs was ignored for simplicity. The ground was modeled as a large ($25m \times 25m \times 1m$) box with a hydroelastic modulus of $5\times10^6~Pa(N/m^2)$ and dissipation of $0~s/m$. The feet were modeled as perfectly rigid spheres (i.e., infinite hydroelastic modulus) and the body as a compliant box with a small hydroelastic modulus of $1\times10^4~Pa(N/m^2)$. We found that this ``soft body'' helped iLQR convergence, since some of the early trajectories involve the body striking the ground. Static and dynamic coefficients of friction of $0.6$ and $0.5$ respectively roughly approximate walking on a hard floor. \textbf{Initialization: } The robot's initial state was the stationary standing position shown at the right of Figure \ref{fig:quad_gait}. The initial guess $\bar{\u}$ was joint torques to hold this standing position. To improve efficiency and increase the trajectory length, we solved the optimization problem in receding horizon fashion. We first solved the iLQR problem with a time horizon of $0.2s$, or 40 timesteps. We then shifted the horizon forward by 4 timesteps, used the optimal control sequence from the prior time window to generate a new initial guess $\bar{\u}$, and resolved the optimization problem. We repeated this process 100 times to obtain a trajectory with a total length of roughly 2 seconds. \textbf{Cost Function: } The cost function was designed to move the robot forward at a desired velocity, $v^{des}_x$. The nominal state $\bm{x}^{nom}$ was composed of the following elements: base orientation $\bm{\theta}_B$ corresponding to a level body, base position $\bm{p}_B$ shifted forward according to the desired velocity, joint angles $\bm{q}_J$ corresponding to the initial standing posture, base angular velocity $\bm{\omega}_B=0$, base linear velocity $\dot{\bm{p}}_B = [v^{des}_x~0~0]$, and joint velocities $\v_J = 0$. The cost weights $\bm{Q},\bm{Q}_f$ were defined as diagonal matrices \begin{align*} \bm{Q} &= \text{diag}([\begin{array}{ccc;{2pt/2pt}ccc} ~2.0 & 1.0 & 0.0 & 0.01 & 0.01 & 0.01 \end{array}]), \\ \bm{Q}_f &= \text{diag}([\begin{array}{ccc;{2pt/2pt}ccc} \undermat{\bm{\theta}_B}{10.0} & \undermat{\bm{p}_B}{5.0} & \undermat{\bm{q}_J}{0.1} & \undermat{\bm{\omega}_B}{1.0~} & \undermat{\dot{\bm{p}}_B}{1.0~} & \undermat{\v_J}{0.01}\end{array}]). \\ \end{align*} Note that the running cost $\bm{Q}$ puts no penalty on joint angles, and that the largest cost terms are related to the body position and velocity. The control penalty was $\bm{R}=0.01\bm{I}$. \textbf{Results: } We solved the optimization problem with target velocities of $0.5$ and $1.0~m/s$. Optimal trajectories can be seen in the accompanying video. Plots of the forward base velocity for both cases are shown in Figure~\ref{fig:forward_vel_plot}. Snapshots from the $1.0~m/s$ case are shown in Figure \ref{fig:quadruped_composite}. Interestingly, both trajectories exhibit trot-like behavior, where opposite pairs of legs tend to move together. \begin{figure} \centering \includegraphics[width=0.7\linewidth]{figures/quadruped_forward_vel.png} \caption{Actual (solid) and desired (dashed) forward base velocity of the mini cheetah quadruped for two target velocities.} \label{fig:forward_vel_plot} \end{figure} Solve times were very slow in both cases, averaging around 3 seconds per iteration, as shown in Figure~\ref{fig:iteration_times}. This is largely due to the use of automatic differentiation to compute dynamics partials $f_{\bm{x}}$ and $f_{\u}$. Each receding horizon resolve required 5-6 iLQR iterations, leading to total solve times around 25 minutes. \begin{figure*} \centering \includegraphics[width=\linewidth]{figures/forward_push_frames_lowres.png} \caption{Snapshots of a forward push motion synthesized with iLQR over hydroelastic contact in simulation and on hardware. (1) The robot starts just above the ball and lowers its arm to make contact. (2) The robot starts to roll the ball forward. (3) As the next link of the robot strikes the ball, the ball transitions from a rolling to a sliding mode. (4) The ball continues to slide forward. (5) The arm comes to rest on top of the ball, stopping its forward motion.} \label{fig:forward_push_hardware} \end{figure*} \subsection{Whole-Arm Manipulation}\label{sec:arm} In this section, we consider a 7 degree-of-freedom Kinova Gen3 robot arm tasked with moving a large ball. The ball is too big to be grasped, and the robot must instead exploit contact interactions with the whole arm. \textbf{Model Details: } The system state includes both the arm and the ball, leading to 13 total degrees of freedom. For simplicity, we assume the gripper is fixed in the open position. This gives \begin{equation} \bm{x}^T = [\bm{q}^T~\v^T] = [\begin{array}{ccc;{2pt/2pt}ccc}\bm{q}_J^T&\bm{\theta}_b^T&\bm{p}_b^T&\v_J^T&\bm{\omega}_b^T&\dot{\bm{p}}_b^T\end{array}] \end{equation} where $\bm{q}_J$ are joint angles, $\bm{\theta}_b$ is the ball's orientation, expressed as a quaternion, $\bm{p}_b$ is the ball's position, $\v_J$ are joint velocities, $\bm{\omega}_b$ is the ball's angular velocity, and $\dot{\bm{p}}_b$ is the ball's linear velocity. A timestep of $10~ms$ was used to simulate the system over a $0.5s$ horizon. Parameters of the ball were chosen to roughly match those of an oversized tennis ball used in the hardware experiments (see Section~\ref{sec:hardware}). The ball has a radius of $0.1~m$, mass of $0.258~kg$, static and dynamic coefficients of friction of roughly $0.3$ and $0.2$ respectively, and is modeled as a hollow sphere. We used a hydroelastic modulus of $5\times10^6~Pa(N/m^2)$ and a relatively large dissipation of $5~s/m$ to model the ball. The same ground model was used as in the quadruped example described above, but with lower friction coefficients. The collision model for the robot arm was defined using mesh files supplied by Kinova. The original high-resolution meshes were downsampled to improve the efficiency of the hydroelastic contact engine. The robot arm was modeled as perfectly rigid, i.e., infinite hydroelastic modulus. \textbf{Initialization} An initial guess of $\bar{\u} = \S \bm{g}$ was chosen to simply compensate for gravity. Because the time horizon was relatively short, we did not use any receding-horizon resolves. We did take care to define initial joint angles such that the robot was close to the ball. \textbf{Cost Function: } The quadratic cost was defined to prioritize the movement of the ball while minimally restricting the robot arm itself. In addition to a control penalty $\bm{R}=0.01\bm{I}$, $\bm{Q}$ and $\bm{Q}_f$ were defined as \begin{align*} \bm{Q} &= \text{diag}([\begin{array}{ccc;{2pt/2pt}ccc} 0.0 & 0.0 & 100 & 0.1 & 0.1 & 0.1 \end{array}]), \\ \bm{Q}_f &= \text{diag}([\begin{array}{ccc;{2pt/2pt}ccc} \undermat{\bm{q}_J}{0.0} & \undermat{\bm{\theta}_b}{0.0} & \undermat{\bm{p}_b}{100} & \undermat{\v_J}{0.1} & \undermat{\bm{\omega}_b}{1.0} & \undermat{\dot{\bm{p}}_b}{1.0}\end{array}]). \\ \end{align*} Note that there is no cost associated with the joint angles $\bm{q}_J$, and that the primary focus is on $\bm{p}_b$. The nominal state $\bm{x}^{nom}$ was defined by a target ball position $\bm{p}_b^{nom}$ and zero velocity. \textbf{Results: } We considered three target positions $\bm{p}_b^{nom}$, defined to move the ball forward $0.2~m$, left $0.15~m$, and up $0.2~m$. The same cost function was used in all three cases, with the exception that no penalty on the horizontal position of the ball was applied in the lifting up case. Screenshots from the resulting trajectories are shown in Figures~\ref{fig:forward_push_hardware}, \ref{fig:sideways_roll}, and \ref{fig:front_page}. In the forward scenario, the robot uses a combination of rolling and sliding to move the ball forward. In the leftward scenario, the ball is rolled through the entire motion, with the side of the gripper used to extend the roll. In the upward lifting scenario, the robot uses contact with several of the links to roll the ball against the robot's base. Iteration times for iLQR were again very slow, averaging 4-12 seconds as shown in Figure~\ref{fig:iteration_times}. The forward and upward scenarios were significantly slower due to the more complex contact interactions involved. The three scenarios (left, forward, up) required 21, 30, and 33 iterations respectively, leading to total solve times of 80, 225, and 361 seconds. \begin{figure} \centering \includegraphics[width=0.8\linewidth]{sideways_roll_both.png} \caption{Comparison of actual (hardware) and planned (simulation) tests for rolling the ball to the left.} \label{fig:sideways_roll} \end{figure} \section{Hardware Experiments}\label{sec:hardware} To validate the physical realism of this approach, we executed the optimal trajectories generated in Section~\ref{sec:arm} on a Kinova Gen3 manipulator. Trajectories generated offline were executed in open-loop. Due to the fact that direct measurements of the ball's state are not available, we used a stiff PD+ controller \begin{equation} \bm{\tau} = \bar{\u} - \bm{K}_p(\bm{q}^J-\bar{\bm{q}}^J) - \bm{K}_d(\v^J-\bar{\v}^J), \end{equation} with $\bm{K}_p = 500\bm{I}$ and $\bm{K}_d = 5\bm{I}$, rather than the local feedback controller from iLQR (\ref{eq:ilqr_local_feedback}). This torque control loop was executed at $1~kHz$. To stay well below the torque and velocity limits of the robot, the trajectories were executed at half speed, with $\bar{\u},\bar{\bm{q}}^J,\bar{\v}^J$ updated every $20~ms$. Despite these simplifications, hardware experiments exhibited remarkable similarities to the simulation. Video can be found at \url{https://youtu.be/IqxJKbM8_ms}. Snapshots from the forward scenario are shown in Figure~\ref{fig:forward_push_hardware}, where the planned (simulation) trajectory includes a transition from rolling to sliding contact around frame 3. This contact mode transition also occurs on hardware, despite a lack of direct feedback related to the ball and the slower playback speed. The largest difference between planned and actual trajectories can be seen in frame 5 of Figure~\ref{fig:forward_push_hardware}, where the ball ends up further forward in simulation than on hardware. This difference is most likely due to the fact that the hardware trajectory was executed at half speed, reducing the ball's forward momentum between frames 4 and 5. A lack of feedback related to the ball's position and imprecise initial placement of the ball are also possible contributing factors. Leftward and upward trajectories were also played back on hardware, as illustrated in Figures \ref{fig:front_page} and \ref{fig:sideways_roll}. \begin{figure} \centering \includegraphics[width=0.8\linewidth]{figures/iteration_times.png} \caption{Box plots showing iteration times for each of the examples. } \label{fig:iteration_times} \end{figure} \section{Discussion}\label{sec:discussion} These preliminary results show that iLQR over hydroelastic contact is a good candidate for reliable and physically realistic contact-implicit trajectory optimization. Relatively few iterations ($<40$) were required to produce contact-rich whole-arm manipulation trajectories from scratch. Anecdotally, this method required relatively little cost-function tuning, and open-loop trajectories could be executed directly on hardware. The numerical reliability of this approach is supported by the fact that no special modifications to the contact model or optimization algorithm were required. Instead, a vanilla implementation of the standard iLQR algorithm was all that was needed to produce physically realistic contact-rich trajectories. Computation time is a major limitation, however. Iteration times on the order of seconds are far too slow for practical use, especially for MPC-style control. One source of slowness is computational overhead from our naive Python implementation of iLQR. The more prominent bottleneck, however, is automatic differentiation for the dynamics partials $f_{\bm{x}}$ and $f_{\u}$. This is especially notable in contact-rich configurations (Figure~\ref{fig:iteration_times}). More efficient computation of gradients through hydroelastic contact is a promising area of future research. Similar developments for the MuJoCo contact model \cite{todorov2014convex} reduced DDP iteration times to the order of milliseconds \cite{chatzinikolaidis2021trajectory}. Another limitation stems from the physical accuracy of the hydroelastic contact model. Since hydroelastic contact does not include force-at-a-distance, iLQR cannot direct the robot to make contact with distant objects, something that can be accomplished if force-at-a-distance is allowed \cite{onol2020tuning}. With this in mind, iLQR over hydroelastic contact may be most useful in conjunction with a higher-level planner. Nonetheless, this method was able to synthesize complex behaviors that require making and breaking contact, such as quadruped locomotion, without a high-level planner or force-at-a-distance. \section{Conclusion}\label{sec:conclusion} iLQR over hydroelastic contact enables numerically reliable and physically realistic contact-implicit trajectory optimization. While computation time is currently a major drawback, there is good reason to believe that this is not a fundamental limitation, and that future research on computing gradients through hydroelastic contact could enable a major step towards fast and reliable contact-implicit trajectory optimization. \section{Acknowledgements} Thanks to Patrick Wensing and He Li for many helpful discussions. \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-01T02:58:03', 'yymm': '2202', 'arxiv_id': '2202.13986', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13986'}
arxiv
\section{Acknowledgement} This work was partially financed by the SCALE-IoT project (Grant No. DFF - 7026-00042B) granted by the Danish Council for Independent Research, the Aarhus Universitets Forskningsfond Starting Grant Project AUFF-2017-FLS-7-1, Aarhus University's DIGIT Centre, the ERC Horizon 2020 Grant No 669255 (MPCPRO), the ELLIIT grant and the Swedish Foundation for Strategic Research, grant RIT17-00. } Finally, the authors would like to kindly thank Prof. Claudio Orlandi for useful discussions and insights on our work. \fi \bibliographystyle{IEEEtran} \section{The \name Protocol}\label{sec:contribution} \begin{figure*}[t] \centering \begin{tikzpicture}[ node distance=0pt, start chain = A, X/.style = {rectangle, draw minimum width=3ex, minimum height=3.5ex, outer sep=0pt, on chain}, B/.style = {decorate, decoration={brace, amplitude=5pt, pre=moveto,pre length=1pt,post=moveto,post length=1pt, raise=1mm, #1}, thick}, B/.default=mirror, ] \foreach \i in {4,10,1,8,9,7} \node[X,right] {\i}; \node[X,text=red,right] {1}; \foreach \i in {2,2, 12} \node[X,right] {\i}; \node (end)[X, right] {15}; \node (begin)[X, right = 1.3cm] {4}; \foreach \i in {10,1,8,9,7,2,2, 12,15} \node[X, right] {\i}; \node[X,text=blue, right = 1cm] {6}; \node[X, text=red, right] {1}; \draw [arrow] (end) -- (begin); \node (B1) [inner sep=1pt,above=of A-7.north west] {Input}; \node (B2) [inner sep=1pt,above=of A-17.north west] {Output}; \node (B3) [inner sep=1pt,above=of A-23.north west] {Deviation ($\local$)}; \foreach \x [count=\i] in {0, ...,6} \node [below=of A-\i]{\textcolor{black!50}{\x}}; \node [below=of A-7]{\textcolor{blue}{6}}; \foreach \x [count=\i] in {7, ...,10}{ \pgfmathtruncatemacro{\y}{\x+1}; \node [below=of A-\y]{\textcolor{black!50}{\x}};}; \node[below=of A-1, xshift=-30pt]{\textcolor{black!50}{$position$}}; \foreach \x in {0, ...,9} \pgfmathsetmacro{\i}{\x+12} \node [below=of A-\i,xshift=-5pt, yshift=-6pt]{\textcolor{black!50}{\x}}; \node [below=of A-22]{\textcolor{blue!50}{{$P$}}}; \node [below=of A-23]{\textcolor{red!50}{$V$}}; \node[left=of A-1, xshift = -8pt]{\textcolor{black}{$\deletions:$}}; \end{tikzpicture} \caption{An illustration of \deletions, where \bits=3. In this example the symbol with value 1 from position 6 is deleted from \file.} \label{fig:Del} \end{figure*} We begin by providing an overview of \name followed by a detailed description of the actions performed in the \cloud and the \user. We conclude with a detailed explanation of the whole the protocol \subsection{\name in a nutshell}\label{sec:transformations} We employ a similar system model as~\cite{yggdrasil}, namely, a single \cloud storage provider connected to multiple \users. \users wish to outsource their data to the \cloud in a privacy-preserving manner, while the \cloud wishes to reduce the storage footprint of the received outsourced data. To achieve privacy-preserving dual deduplication, each \user applies a transformation $\transformation()$ to the original file \file to generate the pair $(\outsource, \local)\gets\transformation(\file)$. Intuitively, \outsource is the record \user outsources to \cloud, and this should leak as little information about the original file \file as possible (to preserve privacy). \local is called the client-side deviation and condenses instructions on how to reconstruct \file from \outsource. The \transformation entails a number of manipulations as shown in Section \ref{sec:client} and Fig.~\ref{fig:client}. For the sake of simplicity, we describe only the main manipulation in \transformation, i.e., \deletions (deletion), in more detail. As the name suggests, this transformation removes symbols from \file. The outcome is a sub-string \outsource of the original file \file. To build intuition, \deletions acts as a deletion channel. Thus, it simultaneously performs two tasks (1) it reduces the size of the outsourced record, and (2) it makes it harder for the \cloud (and thus an adversary \adversary) to guess the exact original data \file from \outsource. To enable the reconstruction of \file from \outsource, \deletions returns an additional output that contains the list of deleted positions (in the form of pointers) and the corresponding deleted values (in the form of alphabet symbols) in form of the client-side deviation \local. With \local at hand, the \user can efficiently reconstruct \file from \outsource. Fig.~\ref{fig:Del} illustrates an example of how \deletions works. In this example, the symbol `1' from position `6' is deleted. The local deviation contains two values: `6' is a pointer indicating the position of the deleted symbol, and `1' is the deleted symbol. In \name, we employ a PRNG function to select the positions where we perform deletions. Concretely, the \user selects a pre-determined number of seeds for each chunk, and interprets the output of the PRNG of each seed as a sequence of positions on which to apply \deletions in the chunk. The use of seeds instead of storing positions alongside values, as done in~\cite{yggdrasil}, significantly reduces the storage requirement on the \user. This means that all positions of deleted elements in \local can be stored by a single seed. Further details on how to combine the PRNG and \deletions, and the other manipulations involved in \transformation, are given in Section~\ref{sec:client}. We also analyze how the use of a PRNG impacts security in Section~\ref{sec:security_proofs}. \bonsai employs a novel way to perform generalized deduplication on the \cloud side. Upon receiving an outsource \outsource, instead of looking for similar bases according to classical distance metrics, e.g., Hamming ~\cite{Vestergaard2019a} and Swap~\cite{yggdrasil}, the \cloud in \name processes \outsource to generate a sorted base \base and a set of strings, called \emph{cloud-side deviation}. After this transformation, the \cloud applies deduplication on \base. We call this \cloud-side process \cloudtransformation. Its aim is to identify an alternative representation of \outsource that deduplicates with higher probability. The manipulations in \cloudtransformation are: grouping, Huffman coding and sorting as detailed in Section~\ref{sec:cloud}. \iffalse In order to make this process reversible, \cloudtransformation must output some information about the alterations performed. We refer this information as deviation. Our experiments show that \bonsai's paradigm `process first, deduplicate next' successfully increases the compression potential of the system when the outsourced data has a heterogeneous distribution. Interestingly, even in more homogeneous data, our solution does not significantly diminish the compression potential in the \cloud. \fi To give an intuition, the \cloud in \name identifies each symbol with three values. We denote these values by \Bid, \Sid, and \Vid. These three values uniquely identify eqach symbol (more details in section~\ref{sec:cloud}) . Upon receiving an \outsource, the \cloud generates a string containing the \Bid of for all symbols in \outsource, and sorts it in ascending order. This string is called base and is denoted by \base. As the base \base is sorted, the \cloud stores the \base of all of the received \outsource in a forest structure (called \baseset), to help find duplicates in time $O(\log \nob)$, where $\nob$ is the number of bases in \baseset. Using this forest structure, instead of directly storing the \base for each \outsource, the \cloud assigns a pointer to \base in \baseset, and uses this pointer to store each \outsource. The \cloud needs to store the necessary information to reconstruct \outsource from \base upon \user's request. This information is stored in what we call cloud-side deviation. Cloud-side deviation contains of three strings: \Change, \Addendum, \ChangedValues. In detail, \Change contains information about the position of the symbols in the original outsource \outsource; \Addendum contains the \Sid of the symbols; and \ChangedValues contains the \Vid of the symbols. \Change is created by using an algorithm inspired by Cycle Sort~\cite{bartle2000introduction} to identify the required swaps needed to sort \base. This algorithm is detailed in Algorithm \ref{alg:cap}, in Section~\ref{sec:cloud}. In order to reduce the size of the \Sid and \Vid for the symbols, and ultimately having a bigger compression gain in the \cloud, the \cloud uses Huffman coding to represent the \Sid and \Vid of the symbols in each Bracket. We discuss the choice of Huffman coding and its implications in Section \ref{sec:cloud}. \vspace{-0.1cm} \subsection{\policy and protocols between \cloud and \user} The communication between \cloud and \user consists of two algorithms: \upload and \get. With \upload the \user sends \outsource to the \cloud; while with \get the \user requests back the uploaded data from the \cloud. In order to ensure consistency, the \user uses a file identifier, \id, for each outsource \outsource it uploads to \cloud. The identifier \id is sent to the \cloud alongside the \outsource and is used by \get as a reference to \outsource. Since we assume \cloud not to be malicious, \id does not serve as an integrity tool. Employing a cryptographic secure hash function would, however, mitigate some attack scenarios in the presence of a malicious cloud, or provide secure file sharing among \users~\cite{sehat2022bifrost}. In \name, the \cloud performs deduplication to optimize space and reduce the storage requirements. Therefore, the compression potential increases if the received outsource \outsource are similar to each other. This is achieved by enforcing a certain probability distribution on the uploaded records. In order to ensure that the \cloud receives \emph{deduplication friendly} data, \name adopts policies on the probability distribution of symbols in \outsource. Policies are publicly available to \users and should be fetched before \upload and taken into consideration when running \transformation. In detail, $\policy = [\clouddistribution, \sbase]$ where \sbase is the expected size of \outsource and \clouddistribution is defined an array of values $\clouddistribution = [p^{\prime}_{0},\ldots,p^{\prime}_{\alphabetSize-1}]$, and $p^{\prime}_{i}$ indicates the probability of symbol $i$ in the \cloud. This policy is calculated by the \cloud from the set of stored bases \baseset. This increases the potential for deduplication between outsourced data by creating \outsource that are similar to each other, leading to higher deduplication rates and lower storage requirement in the \cloud and ultimately higher compression gain. The \policy may include more detailed information to further increase compression capability of \cloud or for other use cases such as ensuring reliability. We leave other information that can be included in \policy and the effect of such information on performance and compression potential of \name to future work. \subsection{The \user of \name}\label{sec:client} \begin{figure*}[t] \centering \begin{tikzpicture}[ node distance=0pt, X/.style = {align=left, rectangle, draw minimum width=2.5ex, max width=2.5ex, minimum height=2.8ex, outer sep=0pt}, Y/.style = {align=left, rectangle, draw minimum width=3.5ex, minimum height=3.5ex, outer sep=0pt}, ] { [start chain =A], \node[X,right, on chain = A] at (-2,-1.7) {\footnotesize 4}; \node[X,right, on chain = A] {\footnotesize 10}; \node[X,right, on chain = A] {\footnotesize \textcolor{red!80}{1}}; \foreach \i in {8,9} \node[X,right, on chain = A] {\footnotesize \i}; \node[X,right, on chain = A] {\footnotesize \textcolor{red!30}{7}}; \foreach \i in {1,2} \node[X,right, on chain = A] {\footnotesize \i}; \node[X,right, on chain = A] {\footnotesize \textcolor{red!60}{2}}; \node[X,right, on chain = A] {\footnotesize 12}; \node(endA) [X, right, on chain = A] {\footnotesize 15}; } \foreach \x [count=\i] in {0,1} \node [below=of A-\i]{\textcolor{black!50}{\tiny \x}}; \node [below=of A-3]{\tiny \textcolor{blue!80}{2}}; \foreach \x [count=\i] in {3,4} \pgfmathsetmacro{\i}{\x+3} \node [below=of A-\i,xshift=-28pt, yshift=-6pt]{\textcolor{black!50}{\tiny \x}}; \node [below=of A-6]{\tiny \textcolor{blue!30}{5}}; \node [below=of A-7]{\tiny \textcolor{black!50}{6}}; \node [below=of A-8]{\tiny \textcolor{black!50}{7}}; \node [below=of A-9]{\tiny \textcolor{blue!60}{8}}; \node [below=of A-10]{\tiny \textcolor{black!50}{9}}; \node [below=of A-11]{\tiny \textcolor{black!50}{10}}; \node [inner sep=1pt,above=of A-6.north east] {\footnotesize Original Data ($\file$)}; { [start chain = B], \node (sResult1) [X,right, on chain = B] at (1.5,0) {\tiny \textcolor{blue!30}{5}}; \node[X,right, on chain = B] {\tiny \textcolor{blue!60}{8}}; \node(seed1)[X,right, on chain = B] {\tiny \textcolor{blue!80}{2}}; } \node (PRNG1) [X, left=0.5cm of B-1, label={\tiny PRNG}, fill=black!30] {}; \node (s1) [left=1.2cm of B-1]{$s_{1}$}; \node [below=of B-1]{\textcolor{black!50}{\tiny $P1$}}; \node [below=of B-2]{\textcolor{black!50}{\tiny $P2$}}; \node [below=of B-3]{\textcolor{black!50}{\tiny $P3$}}; \draw [arrow] (s1) -- (PRNG1); \draw [arrow] (PRNG1) -- (sResult1); { [start chain = C], \node (sResult2) [X,right, on chain = C] at (1.5,-3.5) {\tiny 6}; \node[X,right, on chain = C] {\tiny 1}; \node (seed2) [X,right, on chain = C] {\tiny 3}; } \node (PRNG2) [X, left=0.5cm of C-1, label={\tiny PRNG}, fill=black!30] {}; \node (s2) [left=1.2cm of C-1]{$s_{2}$}; \draw [arrow] (s2) -- (PRNG2); \draw [arrow] (PRNG2) -- (sResult2); \node [below=of C-1]{\textcolor{black!50}{\tiny $P1$}}; \node [below=of C-2]{\textcolor{black!50}{\tiny $P2$}}; \node [below=of C-3]{\textcolor{black!50}{\tiny $P3$}}; { [start chain =A1], \node(beginA1)[X,right, on chain = A1] at (4,0) {\footnotesize 4}; \foreach \i in {10,8,9,1,2,12} \node[X,right, on chain = A1] {\footnotesize \i}; \node (endA1) [X,right, on chain = A1] {\footnotesize 15}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of A1-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of A1-5.north west] {\footnotesize Outsource ($\outsource_{1}$)}; { [start chain =A2], \node(beginA2)[X,right, on chain = A2] at (4,-3.5) {\footnotesize 4}; \foreach \i in {1,9,7,2,2,12} \node[X,right, on chain = A2] {\footnotesize \i}; \node (endA2)[X,right, on chain = A2] {\footnotesize 15}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of A2-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of A2-5.north west] {\footnotesize Outsource ($\outsource_{2}$)}; { [start chain =A1D], \node(beginA1D)[X,right, on chain = A1D] at (8,0) {\footnotesize 0}; \node[X,right, on chain = A1D] {\small $s_{1}$}; \node[X,right, on chain = A1D] {\footnotesize \textcolor{red!30}{7}}; \node[X,right, on chain = A1D] {\footnotesize \textcolor{red!60}{2}}; \node[X,right, on chain = A1D] {\footnotesize \textcolor{red!80}{1}}; } \node [below= of A1D-1]{\textcolor{black!50}{\tiny \invertbit}}; \node [below=of A1D-3]{\textcolor{black!50}{\tiny $V1$}}; \node [below=of A1D-4]{\textcolor{black!50}{\tiny $V2$}}; \node [below=of A1D-5]{\textcolor{black!50}{\tiny $V3$}}; \node [inner sep=1pt,above=of A1D-3.north] {\footnotesize Deviation ($local_{1}$)}; { [start chain =A2D], \node(beginA2D)[X,right, on chain = A2D] at (8,-3.5) {\footnotesize 0}; \node[X,right, on chain = A2D] {\small $s_{2}$}; \foreach \i in {1,10,8} \node[X,right, on chain = A2D] {\footnotesize \i}; } \node [below= of A2D-1]{\textcolor{black!50}{\tiny \invertbit}}; \node [below=of A2D-3]{\textcolor{black!50}{\tiny $V1$}}; \node [below=of A2D-4]{\textcolor{black!50}{\tiny $V2$}}; \node [below=of A2D-5]{\textcolor{black!50}{\tiny $V3$}}; \node [inner sep=1pt,above=of A2D-3.north] {\footnotesize Deviation ($local_{2}$)}; { [start chain = IA1] \node(beginIA1)[X, right, on chain= IA1] at (4,-1.7) {\footnotesize 11}; \foreach \i in {5,7,6,14,13,3,0} \node[X,right, on chain = IA1] {\footnotesize \i}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of IA1-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of IA1-5.north west] {\footnotesize Outsource ($\outsource_{3}$)}; { [start chain = IA2] \node(beginIA2)[X, right, on chain= IA2] at (4,-5.3) {\footnotesize 11}; \foreach \i in {14,6,8,13,13,3,0} \node[X,right, on chain = IA2] {\footnotesize \i}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of IA2-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of IA2-5.north west] {\footnotesize Outsource ($\outsource_{4}$)}; { [start chain =IA1D], \node (beginIA1D)[X,right, on chain = IA1D] at (8,-1.7) {\footnotesize 1}; \node[X,right, on chain = IA1D] {\small $s_{1}$}; \node[X,right, on chain = IA1D] {\footnotesize \textcolor{red!30}{7}}; \node[X,right, on chain = IA1D] {\footnotesize \textcolor{red!60}{2}}; \node[X,right, on chain = IA1D] {\footnotesize \textcolor{red!80}{1}}; } \node [below =of IA1D-1]{\textcolor{black!50}{\tiny \invertbit}}; \node [below=of IA1D-3]{\textcolor{black!50}{\tiny $V1$}}; \node [below=of IA1D-4]{\textcolor{black!50}{\tiny $V2$}}; \node [below=of IA1D-5]{\textcolor{black!50}{\tiny $V3$}}; \node [inner sep=1pt,above=of IA1D-3.north] {\footnotesize Deviation ($local_{3}$)}; { [start chain =IA2D], \node(beginIA2D)[X,right, on chain = IA2D] at (8,-5.3) {\footnotesize 1}; \node[X,right, on chain = IA2D] {\footnotesize $s_{2}$}; \foreach \i in {1,10,8} \node[X,right, on chain = IA2D] {\footnotesize \i}; } \node [below =of IA2D-1]{\textcolor{black!50}{\tiny \invertbit}}; \node [below=of IA2D-3]{\textcolor{black!50}{\tiny $V1$}}; \node [below=of IA2D-4]{\textcolor{black!50}{\tiny $V2$}}; \node [below=of IA2D-5]{\textcolor{black!50}{\tiny $V3$}}; \node [inner sep=1pt,above=of IA2D-3.north] {\footnotesize Deviation ($local_{4}$)}; \path [->] (endA) edge (beginA1); \node [rotate=42] at (3.2,-.77) {\tiny Deletions}; \path [->] (seed1) edge (beginA1); \path [->] (endA) edge (beginA2); \node [rotate=318] at (3.2,-2.67) {\tiny Deletions}; \path [->] (seed2) edge (beginA2); \path[->] ([yshift=3pt]beginA1.west) edge [bend right] (beginIA1.west); \node [rotate=270] at (3.95,-.77) {\tiny invert}; \path[->] ([yshift=3pt]beginA2.west) edge [bend right] (beginIA2.west); \node [rotate=270] at (3.95,-4.47) {\tiny invert}; \node (Dname) at (-1.7,-9.35) {\footnotesize $\clouddistribution$}; { [start chain = PD] \node (Dnode1)[Y,right, on chain = PD] at(-1,-9.35) {\footnotesize 3/16}; \node (Dnode2)[Y,right, on chain = PD] {\footnotesize 1/16}; \foreach \i in {1/16,1/24,1/16,1/24} \node[Y,right, on chain = PD] {\footnotesize \i}; \node (Dnode6)[Y,right, on chain = PD] {\footnotesize 1/24}; \foreach \i in {3/64,1/16,1/24,1/24,3/64,1/24,3/64,3/64} \node[Y,right, on chain = PD] {\footnotesize \i}; \node(endPD) [Y, right, on chain=PD] {\footnotesize 1/8}; } \foreach \x [count=\i] in {0, ...,15}{ \node [below=of PD-\i]{\textcolor{black!50}{\tiny \x}};}; \node [below=of Dname] {\textcolor{black!50}{\tiny $symbol$}}; \node (Dname2) at (-1.7,-7) {\footnotesize $\distribution_{\outsource_{4}}$}; { [start chain = DA4] \node (DA4node1) [Y,right, on chain = DA4] at(-1,-7) {\footnotesize 1/8}; \node (DA4node2) [Y,right, on chain = DA4] {\footnotesize 0}; \foreach \i in {0,1/8,0,0} \node[Y,right, on chain = DA4] {\footnotesize \i}; \node (DA4node6) [Y,right, on chain = DA4] {\footnotesize 1/8}; \foreach \i in {0,1/8,0,0,1/8,0,2/8,1/8} \node[Y,right, on chain = DA4] {\footnotesize \i}; \node(endDA4) [Y, right, on chain=DA4] {\footnotesize 0}; } \foreach \x [count=\i] in {0, ...,15}{ \node [below=of DA4-\i]{\textcolor{black!50}{\tiny \x}};}; \node [below=of Dname2] {\textcolor{black!50}{\tiny $symbol$}}; \path[->] ([yshift=-3pt]beginIA2.west) edge [bend right] ([xshift=3pt]DA4node1.north); \node (Cname) at (-2.5,-8.17) {\footnotesize $(\distribution_{\outsource_{4}}[i] - \clouddistribution[i])^{2} $}; \node (calc1) at(-0.7,-8.17) {\footnotesize 0.0040}; \node at(-.1,-8.17) {\footnotesize +}; \node (calc2) at (0.6, -8.17) {\footnotesize 0.0040}; \node at(1.2,-8.17) {\footnotesize +}; \node at(1.6,-8.17) {\footnotesize $\cdots$}; \node at(1.9,-8.17) {\footnotesize +}; \node (calc3)at (2.6, -8.17) {\footnotesize 0.0070}; \node at(3.15,-8.22) {\footnotesize =}; \node (calcres) at (3.7, -8.17) {\footnotesize 0.1117}; \node (DDA1) at (11.7,0) {\textcolor{teal}{$\distance_{\outsource_{1}} = 0.2926$}}; \node (DDA2) at (11.7,-1.7) {$\distance_{\outsource_{2}} = 0.2948$}; \node (DDA3) at (11.7,-3.5) {$\distance_{\outsource_{3}} = 0.3399$}; \node (DDA4) at (11.7,-5.3) {$\distance_{\outsource_{4}} = 0.3341$}; \path[->] (Dnode1.north) edge (calc1.south); \path[->] (Dnode2.north) edge (calc2.south); \path[->] (Dnode6.north) edge (calc3.south); \path[->] ([xshift=4pt]DA4node1.south) edge (calc1.north); \path[->] (DA4node2.south) edge (calc2.north); \path[->] ([xshift=-3pt]DA4node6.south) edge (calc3.north); \draw[->, to path={-| (\tikztotarget)}] (calcres.east) to (DDA4.south); \node at (8.3, -7.95) {\footnotesize Square root}; \draw [thick] (-2.2,0.8) rectangle (2.8,-4); \node at (0.3, 1){\footnotesize Step1: Generating random seeds}; \draw[thick] (3.65,0.8) rectangle (10.4,-6); \node at (6.97, 1){\footnotesize Step2: Generating potential outsources}; \draw[thick] (-3.65,-6.5) rectangle (11,-10); \node at (3.8, -6.3){\footnotesize Step3: comparing generated outsources with Policy}; \draw[thick] (10.6,0.8) rectangle (13,-6); \node [rotate= 270] at (13.2, -2.6){\footnotesize Step4: Selecting the optimal outsource}; \end{tikzpicture} \caption{Summary of Operations in the \user when uploading a file \file to the \cloud.} \label{fig:client} \end{figure*} The \user that wishes to upload its data \file to the \cloud, receives a policy $\policy=[\clouddistribution, \sbase]$ that is generated by the \cloud based on the already stored data. Following the \policy, the \user performs \deletions until the string \outsource has size of \sbase. In \name, deletions are carried out on locations identified by the output of a seeded Pseudo-Random Number Generator (PRNG). More specifically, the \user does not need to store the positions of the deleted symbols. The seed of the PRNG and the deleted values suffice to reconstruct the original file \file from \outsource. To make sure the output of \transformation fits the \policy in the best possible way, for each file \file, the \user generates a set of \test PRNG seeds, where \test is a \user-wide constant, and unique for each \user. If the value of \test is large, there is a higher opportunity for the the generated \outsource to follow the probability distribution indicated in the \policy. However, the \user has to allocate more time and computational power to perform the transformation for each seed. Fig.~\ref{fig:client} illustrates a complete example of \transformation, i.e., the transformations the \user performs on \file prior to \upload. In this example, we consider the same \file as in Fig.~\ref{fig:Del}, $k=4$, and $\test=2$, and we assume that the policy \policy is: \begin{equation} \begin{split} \policy = & [[\frac{3}{16},\frac{1}{16},\frac{1}{16},\frac{1}{24},\frac{1}{16},\frac{1}{24},\frac{1}{24},\frac{3}{64}, \\ &\frac{1}{16},\frac{1}{24},\frac{1}{24},\frac{3}{64},\frac{1}{24},\frac{3}{64},\frac{3}{64},\frac{1}{8}],\; 8]. \\ \end{split} \label{eq:distribution} \end{equation} In this case, the \user starts by generating two random seeds, namely $\seed_{1}$ and $\seed_{2}$. By using $\seed_{1}$ and $\seed_{2}$ as the seeds the PRNG, the \user generates two sets of values, each containing $\sorg-\sbase = 3$ elements. The generated set of values indicate the position of the symbols to be deleted for the construction of the respective outsource strings $\outsource_{1}$ and $\outsource_{2}$. This step is shown as step~1 in Fig.~\ref{fig:client}. In this particular example, $\seed_{1}$ generates the set of positions $\{5,8,2\}$ and $\seed_{2}$ generates the set $\{6,1,3\}$. In step~2 of Fig.~\ref{fig:client}, the \user proceeds to delete the symbols in the given positions, storing the values of the deleted symbols in the order of deletion in $\local$. The result is a potential outsource $\outsource$ and a client-side deviation $\local$. At this point, $\local$ contains the random seed that was used to generated the \outsource and deleted values in the order that the PRNG outputs the positions. In this particular example, considering seed $s_{1}$ generates 5, 8, and 2 in that order, the first values stored in $\local$ is the value in position 5, i.e., 7, followed by the value in position 8, which is 2 and finally the value in position 2, i.e., 1. In order to increase the possibility of generating a string that best adheres to the probability distribution \clouddistribution in \policy, we make use of another well-known information-theoretic transformation: invert (\invert). In the binary case, when a string is transformed by \invert, all bits that has the value of 1 are flipped to 0 and vice-versa. More generally, \invert replaces each symbol $i$ with its complement $\alphabetSize-i-1$. In step~2 of Fig.~\ref{fig:client} we show how the inverted outsource files are generated for a given file. As this example suggests, after generating the possible outsource files using \deletions, the \user proceeds to create the inverted counterpart of each outsource. In Fig.~\ref{fig:client}, $\outsource_{3}$ is generated by performing \invert on $\outsource_{1}$ and $\outsource_{4}$ is the result of \invert on $\outsource_{2}$. Note that as the client-side deviation is only stored locally and it is not necessary for \local to follow the probability distribution of the \policy. Therefore, \local does not get inverted. In order to identify if an outsource \outsource is inverted or not, the \user adds a bit to its client-side deviation \local, denoted by \invertbit. The value of \invertbit is equal to 1 if the \outsource has been inverted and zero otherwise. After these actions, which conclude Step 2, the \user has a total of $2\cdot \test$ possible \outsource that can be used as the outsourced data to the \cloud. The \user chooses the \outsource that best adheres the probability distribution \clouddistribution mentioned in the \policy. In other words, the frequency of the symbols in the chosen \outsource must be the closest one to the distribution of symbols in the policy, i.e., \clouddistribution. We define the frequency of the symbols in \outsource as \begin{description} \item[Frequency of the symbols in \outsource:] \begin{equation}\label{eq:freq} \distribution^{\outsource} = [p^{\outsource}_{0}, ..., p^{\outsource}_{N-1}], \end{equation} \end{description} \begin{figure*}[!t] \centering \begin{tikzpicture} \node (symbolprobs) at (-2,0) {\footnotesize \begin{tabular}{|c|c|} \hline Probability & Symbol \\ \hline 3/16 & 0000\\ 1/8 & 1111\\ \vdots &\vdots \\ 3/64 & 1101 \\ \vdots & \vdots\\ 1/24 & 0011\\ \hline \end{tabular}}; \node () at (-2,2.4) {\tiny \begin{tabular}{c} Symbols sorted in descending\\ order of probability \end{tabular}}; \node (table) at (2,0) {\footnotesize \begin{tabular}{|c|c|c|c|} \hline \multicolumn{4}{|c|}{\Bid} \\ 00 & 01 & 10 & 11\\ \hline 0000 & 1111 & 0001 & 0010 \\ 0100 & 1000 & 1110 & 1011 \\ 1101 & 0111 & 0101 & 0110 \\ 1001 & 1010 & 1100 & 0011 \\ \hline \end{tabular}}; \draw [->] ([yshift=26pt,xshift=-13pt] symbolprobs.east) to node [above] {} ([xshift=9pt, yshift=7pt]table.west); \draw [->] ([yshift=-12pt,xshift=-14pt] symbolprobs.east) to node [above] {} ([xshift=9pt, yshift=-7pt]table.west); \draw [->] ([yshift=-42pt,xshift=-13pt] symbolprobs.east) [bend right=10] to node [above] {} ([xshift=94pt, yshift=-31pt]table.west); \node (row1)[right=of table, xshift = -25pt, yshift=6pt] {\footnotesize 3/16+1/8+1/16+1/16 = \;\, 7/16}; \node (row2)[right=of table, xshift = -25pt, yshift=-6.8pt] {\footnotesize 1/16+1/16+3/64+3/64=\quad 7/32}; \node (row3)[right=of table, xshift = -25pt, yshift=-18.6pt] {\footnotesize 3/64+3/64+1/24+1/24 = 34/192}; \node (row4)[right=of table, xshift = -25pt, yshift=-31pt] {\footnotesize 1/24+1/24+1/24+1/24=\;\;\; 1/6}; \node at (6,0.7) {\tiny Sum of probabilities of each row}; \draw [->] ([yshift=6pt,xshift=-10pt] table.east) to node [above] {} (row1.west); \draw [->] ([yshift=-6.8pt,xshift=-10pt] table.east) to node [above] {} (row2.west); \draw [->] ([yshift=-18.6pt,xshift=-10pt] table.east) to node [above] {} (row3.west); \draw [->] ([yshift=-31pt,xshift=-10pt] table.east) to node [above] {} (row4.west); \node (prob1) at (9,-0.85) {\footnotesize 11/32}; \node (prob2) at (10,-0.5) {\footnotesize 9/16}; \node (prob3) at (11, -0.15) {\footnotesize 1}; \draw ([xshift=5pt] row4.east) -- node [below] {\tiny 1} ([yshift=-1pt] prob1.west); \draw ([xshift=-1pt] row3.east) -- node [above] {\tiny 0} ([yshift=1pt] prob1.west); \draw ([xshift=-3pt] prob1.east) -- node [below, xshift=2pt, yshift=2pt] {\tiny 1} ([yshift=-3pt]prob2.west); \draw ([xshift=4pt] row2.east) -- node [above] {\tiny 0} ( prob2.west); \draw ([xshift=-3pt] prob2.east) -- node [below, xshift=2pt, yshift=2pt] {\tiny 1} ([yshift=-2pt]prob3.west); \draw ([xshift=4pt] row1.east) -- node [above] {\tiny 0} ([yshift=1pt] prob3.west); \node at (9.5,0.7) {\tiny Create Huffman Coding}; \node (table) at (12,0) {\footnotesize \begin{tabular}{|c|} \hline \Sid \\ \\ \hline 0 \\ 10 \\ 110 \\ 111 \\ \hline \end{tabular}}; \end{tikzpicture} \caption{An illustration of generating Brackets using Huffman codes for $\bits = 4$ ($\alphabet= \{0,1\}^4$) and $\distribution$ as in Eq.~\ref{eq:distribution}.} \label{fig:Huffman} \end{figure*} where $p^{\outsource}_{i} = \frac{\#i}{\sbase}$ for each symbol $i$, and $\#i$ is the number of occurrences of each symbol $i$ in the \outsource. Multiple metrics can be used in order to calculate the closeness between the frequency of symbols in a given \outsource, ($\distribution_{\outsource}$) and \clouddistribution, e.g., Hamming distance, Euclidean distance, or Manhattan distance. In this work, the notion of closeness between the probability distribution \clouddistribution and $\distribution_{\outsource}$ is calculated by the Euclidean distance between the two vectors, i.e., the selected \outsource is the one with minimum value of $\distance_{\outsource} = \sqrt{\sum\limits_{i=1}^{N} (p^{\outsource}_{i} - p^{\prime}_{i})^{2}}.$ Hence, as shown in Step~3 in Fig.~\ref{fig:client}, the \user first calculates the frequency of symbols in each \outsource, creating $\distribution_{\outsource}$. Fig.~\ref{fig:client} shows the calculated $\distribution_{\outsource_{4}}$ for $\outsource_{4}$. We see that $\outsource_{4}$ has one element 0, therefore, $\#0 = 1$ and $p^{\outsource}_{i} = 1/8$. After generating the distribution of symbols for all generated \outsource, the \user calculates the value of $\distance_{\outsource}$. This calculation is carried out for $\outsource_{4}$ in Fig.~\ref{fig:client}. After calculating the value of $\distance_{\outsource}$ for all generated \outsource is Step 2, the \user chooses the \outsource with the minimum value of $\distance_{\outsource}$ as the last step (Step 4). In the given example, $\outsource_{1}$ has the lowest value of $\distance_{\outsource}$, and therefore is chosen by the \user to be outsourced to the cloud. Then, the client proceeds with generating \id for the selected \outsource, sending \id and \outsource to the \cloud, while storing \id and \local locally. \subsection{The \cloud of \name} \label{sec:cloud} As mentioned, the \cloud uses an innovative method to store the received \outsource and find possible deduplications in the received data. In this section, we explore the ideas and theory that lead to \cloudtransformation, and describe \cloudtransformation and deduplication in the \cloud in more detail. We also show a toy example to illustrate \cloudtransformation visually. \paragraph{Motivation} The main idea behind \cloudtransformation is to reduce the time needed to find potential deduplication between received data in the \cloud. The idea of \cloudtransformation consists of four main ideas to increase the performance and compression rate in the \cloud. These ideas include splitting data in brackets, sorting, Huffman coding and changing values. \begin{table}[!b] \caption{An illustration of brackets for $\bits = 4$, i.e., $\alphabet= \{0,1\}^4$. \vspace{-.8em} \centering \begin{tabular}{|cc|c|c|c|c|} \hline & & \multicolumn{4}{c|}{\Bid} \\ & & 00 & 01 & 10 & 11 \\ \hline \multirow{4}{*}{\Sid} & 00 & 0000 & 0100 & 1000 & 1100\\ & 01 & 0001 & 0101 & 1001 & 1101\\ & 10 & 0010 & 0110 & 1010 & 1110 \\ & 11 & 0011 & 0111 & 1011 & 1111 \\ \hline \end{tabular} \label{tab:brackets} \end{table} \textbf{Data Split using Brackets}. This process organizes symbols in brackets. Each bracket is assigned a \Bid and each symbol in the bracket is identified with a \Sid. The brackets are pre-defined and unique for each value of \bits. Table~\ref{tab:brackets} gives an example of the bracket system where $\bits = 4$, where each column represents the \Bid and each row represents the \Sid of a the given symbol. Using this table, the \cloud transforms the received outsource \outsource into two different strings: 1. A base \base which includes the \Bid of the symbols, sorted in ascending order, which is used for deduplication; and 2. An addendum \Addendum which includes the \Sid of the symbols, which is added to the cloud-side deviation. In order to reduce the number of bracket IDs used we divide the aforementioned table into four zones. Each zone is a sub-table of size $2{^\frac{k}{4}}$ . At its core, this approach is a sub-categorization where rarely used \Bid values are omitted and the symbols are fitted into fewer Brackets. This is detailed in the Change Values section. \textbf{Sorting}. After performing the data split using brackets, the generated \base is sorted. A String \Change indicating the set of swaps performed to sort the \base is stored in cloud-side deviation. The \base is stored in a forest data structure to ease the search process and further compress the bases. In order to reverse the process of sorting, we store the required swaps (\swap) needed to sort \base. Due to the split in brackets, the \cloud can perform swaps for $2{^\frac{k}{2}}$ values instead of $N=2^{k}$ values, reducing the overhead and time complexity to store and find the required swaps. \textbf{Huffman Coding.} We leverage the fact that the \outsource received by the \cloud follows a certain probability distribution (ensured by the policy), and use Huffman coding in order to reduce the expected size of the \Sid that the \cloud needs to store in the cloud-side deviation. To generate the \Sid of the symbols based on their probability distribution, the \cloud creates a table with $\frac{\bits}{2}$ columns, which represent the \Bid of symbols. Then, the \cloud populates the table by putting the symbols with highest probability distribution in the table first. The way that the table is populated depends on the particular structure of the data. In this work, we populate the table by filling the rows first. An example is illustrated in Fig. \ref{fig:Huffman} for $\bits = 4$. Other methods for filling the table are possible, e.g., columns first, with implications in compression and system performance. By filling the rows first, the \cloud optimizes the size of \Sid for the symbols, as the symbols with higher probability are assigned the same \Sid. However, as the frequent symbols are assigned to different \Bid, the average number of swaps would be high. On the other hand, if the table is filled by columns first, the expected size of \Sid is higher, but the average number of swaps is smaller. The choice of the method and the optimal outcome for the compression rate heavily depends on the structure and statistical characteristics of the files in \database. After populating the table, the \cloud treats each row as a variable, and calculates the probability of each row, which is equal to the summation of the probability of the symbols in the given row. Then, the \cloud generates the Huffman code for the rows of the table, and sets the value of the Huffman code as the \Sid of that row. As an intuition, consider the same probability distribution as the example in Eq.~\eqref{eq:distribution}. In this case, the procedure of generating the \Bid and \Sid of symbols is illustrated in Fig.~\ref{fig:Huffman}. \begin{table}[!b] \caption{An illustration of brackets used for \cloudtransformation for $\bits = 8$. \vspace{-.8em} \centering \begin{tabular}{|cc|cccc|ccc|} \hline & & \multicolumn{7}{c|}{\Bid} \\ & & 000 & 001 & $\cdots$ & 111 & 000 & $\cdots$ & 111 \\ \hline \multirow{5}{*}{\Sid} & $id_{1}$ & $p_{0}$ & $p_{1}$ & $\cdots$ & $p_{7}$ & $p_{64}$ & $\cdots$ & \\ & $id_{2}$& $p_{8}$ & $p_{9}$ & $\cdots$ & & $\vdots$ & $\ddots$ & \\ & \vdots & \vdots & & $\vdots$ & $\vdots$ & & & \\ & $id_{7}$& $p_{56}$ & $p_{57}$ & $\cdots$ & $p_{63}$ & $p_{120}$ & $\cdots$ & $p_{127}$ \\ \hline \multirow{3}{*}{\Sid} & $id_{1}$ & $p_{128}$ & $p_{129}$ & $\cdots$ & $p_{135}$ & $p_{192}$ & $\cdots$ & \\ & \vdots&\vdots & & $\ddots$ & & & $\ddots$ & \\ & $id_{7}$& $p_{184}$ & & $\cdots$ & $p_{191}$ & $p_{248}$ & $\cdots$ & $p_{255}$ \\ \hline \end{tabular} \label{tab:Huffman8} \end{table} \textbf{Change Values.} The \Sid for symbols with high probability distribution is significantly shorter than the symbols with lower probability. However, the size of \Sid for symbols with lower probability distribution is large, and therefore, these symbols have diminishing effect on the compression potential. It is also beneficial to have as few \Bid as possible to reduce the number of swaps in the sorting stage. Thus, we propose using Change Value transformation (\changev) and describe it for $\bits=8$. Using this transformation, the \cloud changes the value of symbols with the lowest probability to symbols with the highest probability. In order to perform this transformation, we divide the brackets table into 4 zones, as described in the Bracket stage. Table.~\ref{tab:Huffman8} shows an example for $\bits = 8$. In this table, we assume that the symbols are sorted based on their probability distribution, where $p_{0}$ denotes the symbol with the highest probability, followed by $p_{1}$, and so on, e.g., $p_{255}$ is the symbol with the lowest probability. The \cloud fills the table by filling the first zone, which is the zone on the top left corner, followed by the second zone on the top right corner and then bottom left and bottom right. In each zone, the symbols are put in their place using the rows first methods, as discussed in the Huffman coding section. Then, the \cloud assigns a a variable for each row of all four zones, generating the \Sid for each row as discussed earlier. Also, each zone is assigned a Value ID \Vid. The \Vid for each zone is generated using the same idea of \Sid. In the end of this procedure, each symbol has a position $[i,j]$ in its zone, an assigned \Bid, \Sid and \Vid. Upon receiving an outsource \outsource, the \cloud first performs a change value operation. For each symbol, the \cloud finds the position of the symbol in its zone in the table, Assuming the symbol is in position $[i,j]$ of one of the zones, the \cloud change the value of that symbol to the value in the position $[i,j]$ in the first zone (top left corner). Then, the \cloud stores the \Vid for the symbols in a string \ChangedValues, which is added to the cloud-side deviation. The transformed string is stored and is used to create \base and \Addendum as discussed before. Using this technique, the data becomes more homogenous, reducing the potential number of \Bid, and therefore reducing the expected number of swaps, while also reducing the expected length of the \Sid for the symbols by eliminating the symbols with lower probability distribution. This improvement is achieved by only storing an overhead value of \Vid for each symbol, which is smaller for symbols with higher probabiltiy distribution. \paragraph{\cloudtransformation} Let us describe in detail the journey on an \outsource as it reaches the the \cloud. The \cloud has already generated the Brackets table before receiving \outsource. We support our description using an example for $\bits =4$, where the Bracket table is given in Table.~\ref{tab:brackets2}. Fig.~\ref{fig:cloud} illustrates the actions performed by the \cloud after receiving an outsource. For the sake of simplicity, we assume that in our example, the \Vid for the zones are $00$,$01$,$10$,$11$. \begin{figure*}[!t] \centering \begin{tikzpicture}[ node distance=0pt, X/.style = {align=left, rectangle, draw minimum width=2ex, max width=2ex, minimum height=2.8ex, outer sep=0pt}, Y/.style = {align=left, rectangle, draw minimum width=3.5ex, minimum height=3.5ex, outer sep=0pt}, ] { [start chain =F1], \node(beginF1)[X,right, on chain = F1] at (-4,0) {\footnotesize 4}; \node(exampleSymbol)[X, right, on chain = F1] {\footnotesize \textcolor{blue!80}{10}}; \foreach \i in {8,9,1,2,12} \node[X,right, on chain = F1] {\footnotesize \i}; \node (endF1) [X,right, on chain = F1] {\footnotesize 15}; } \node [below=of F1-1]{\tiny \textcolor{black!50}{0}}; \node [below=of F1-2]{\tiny \textcolor{black!50}{1}}; \foreach \x [count=\i from 3] in {2, ...,7} \node [below=of F1-\i]{\tiny \textcolor{black!50}{\x}}; \node [inner sep=1pt,above=of F1-5.north west] {\footnotesize Outsource ($\outsource_{1}$)}; { [start chain =F2], \node(beginF2)[X,right, on chain = F2] at (-4,-1.5) {\footnotesize 0}; \foreach \i in {1,6,15,12,1,0} \node[X,right, on chain = F2] {\footnotesize \i}; \node (endF2)[X,right, on chain = F2] {\footnotesize 11}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of F2-\i]{\tiny \textcolor{black!50}{\x}}; \node [inner sep=1pt,above=of F2-5.north west] {\footnotesize Outsource ($\outsource_{2}$)}; % \node(BidTable) at (2,2) { \tiny{ \begin{tabular}{|cc|cc|cc|} \hline & & \multicolumn{4}{c|}{\Bid} \\ & & 0 & 1 & 0 & 1 \\ \hline \multirow{4}{*}{\Sid} & 0 & \textcolor{red!80}{0000} & 0100 & 1000 & 1100\\ & 1 & 0001 & 0101 & 1001 & 1101\\ \cline{2-6} & 0 & 0010 & 0110 & \textcolor{blue!80}{1010} & 1110 \\ & 1 & 0011 & 0111 & 1011 & 1111 \\ \hline \end{tabular} }}; \node [above=of BidTable] {\tiny Brackets Table (Binary)}; { [start chain =F11], \node(beginF11)[X,right, on chain = F11] at (2,0) {\footnotesize 4}; \node(exampleBid)[X, right, on chain = F11] {\footnotesize \textcolor{red!80}{0}}; \foreach \i in {0,1,1,0,4} \node[X,right, on chain = F11] {\footnotesize \i}; \node (endF11) [X,right, on chain = F11] {\footnotesize 5}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of F11-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of F11-5.north west] {\footnotesize $\chnvResult_{1}$}; \draw [->] (endF1) to node [above] {\footnotesize \changeVs} (beginF11); { [start chain =F21], \node(beginF21)[X,right, on chain = F21] at (2,-1.5) {\footnotesize 0}; \foreach \i in {1,4,5,1,1,0} \node[X,right, on chain = F21] {\footnotesize \i}; \node (endF21) [X,right, on chain = F21] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of F21-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of F21-5.north west] {\footnotesize $\chnvResult_{2}$}; \draw [->] (endF2) to node [above] {\footnotesize \changeVs} (beginF21); % % % % % % { [start chain =C1], \node(beginC1)[X,right, on chain = C1] at (5.4,0) {\footnotesize 0}; \node[X,right, on chain = C1] {\footnotesize 3}; \foreach \i in {1,1,0,2,1} \node[X,right, on chain = C1] {\footnotesize \i}; \node (endC1) [X,right, on chain = C1] {\footnotesize 3}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of C1-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of C1-5.north west] {\footnotesize $\ChangedValues_{1}$}; { [start chain =C2], \node(beginC2)[X,right, on chain = C2] at (5.4,-1.5) {\footnotesize 0}; \foreach \i in {0,2,3,1,0,0} \node[X,right, on chain = C2] {\footnotesize \i}; \node (endC1) [X,right, on chain = C2] {\footnotesize 3}; } % \foreach \x [count=\i] in {0, ...,7} \node [below=of C2-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of C2-5.north west] {\footnotesize $\ChangedValues_{2}$}; % % % % % % \node (Line1S) at (10.67,1){\footnotesize $\outsource$}; \node (line1G)at (10.15,0){\footnotesize$\chnvResult$}; \node (Line1E)at (10.67,0){\footnotesize ,}; \node (line1CV)at (11.2,0){\footnotesize $\ChangedValues$}; \node [text width=2cm]at (-3.5, 3) {\footnotesize \begin{tabular}{c} Step 1: \\ \changeVs \end{tabular}}; \draw [->] (Line1S) -- (Line1E); \node(BidTable2) at (2,-3.9) { \tiny{ \begin{tabular}{|cc|cc|cc|} \hline & & \multicolumn{4}{c|}{\Bid} \\ & & 0 & \textcolor{red!80}{1} & 0 & 1 \\ \hline \multirow{4}{*}{\Sid} & \textcolor{green!80}{0} & 0000 & \textcolor{blue!80}{0100} & 1000 & 1100\\ & 1 & 0001 & 0101 & 1001 & 1101\\ \cline{2-6} & 0 & 0010 & 0110 & 1010 & 1110 \\ & 1 & 0011 & 0111 & 1011 & 1111 \\ \hline \end{tabular}} }; \node [above=of BidTable2] {\tiny Brackets Table (Binary)}; { [start chain =F12], \node(beginF12)[X,right, on chain = F12] at (-4,-5.5) {\footnotesize \textcolor{blue!50}{4}}; \foreach \i in {0,0,1,1,0,4} \node[X,right, on chain = F12] {\footnotesize \i}; \node (endF12) [X,right, on chain = F12] {\footnotesize 5}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of F12-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of F12-5.north west] {\footnotesize $\chnvResult_{1}$}; { [start chain =F22], \node(beginF22)[X,right, on chain = F22] at (-4,-7) {\footnotesize 0}; \foreach \i in {1,4,5,1,1,0} \node[X,right, on chain = F22] {\footnotesize \i}; \node (endF22) [X,right, on chain = F22] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of F22-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of F22-5.north west] {\footnotesize $\chnvResult_{2}$}; % % % % { [start chain =H1], \node(beginH1)[X,right, on chain = H1] at (1.4,-5.5) {\footnotesize \textcolor{red!50}{1}}; \foreach \i in {0,0,0,0,0,1} \node[X,right, on chain = H1] {\footnotesize \i}; \node (endH1) [X,right, on chain = H1] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of H1-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of H1-5.north west] {\footnotesize $\sepResult_{1}$}; \draw [->] (endF12) to node [above] {\footnotesize \sep} (beginH1); { [start chain =H2], \node(beginH2)[X,right, on chain = H2] at (1.4,-7) {\footnotesize 0}; \foreach \i in {0,1,1,0,0,0} \node[X,right, on chain = H2] {\footnotesize \i}; \node (endH2) [X,right, on chain = H2] {\footnotesize 0}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of H2-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of H2-5.north west] {\footnotesize $\sepResult_{2}$}; \draw [->] (endF22) to node [above] {\footnotesize \sep} (beginH2); % % % % % { [start chain =A1], \node(beginA1)[X,right, on chain = A1] at (4.7,-5.5) {\footnotesize \textcolor{green!50}{0}}; \foreach \i in {0,0,1,1,0,0} \node[X,right, on chain = A1] {\footnotesize \i}; \node (endA1) [X,right, on chain = A1] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of A1-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of A1-5.north west] {\footnotesize $\Addendum_{1}$}; { [start chain =A2], \node(beginA2)[X,right, on chain = A2] at (4.7,-7) {\footnotesize 0}; \foreach \i in {1,0,1,1,1,0} \node[X,right, on chain = A2] {\footnotesize \i}; \node (endA2) [X,right, on chain = A2] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of A2-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of A2-5.north west] {\footnotesize $\Addendum_{2}$}; % % % % \node at (9.45, -5.25) {(}; \node (line2H)[inner sep=1pt] at (9.7,-5.25){$\sepResult$}; \node (line2E)[inner sep=1pt] at (10.15,-5.25){,}; \node (line2A)[inner sep=1pt] at (10.5,-5.25){$\Addendum$}; \node at (10.75, -5.25) {)}; \node (line2E2)[inner sep=1pt] at (10.9,-5.25){,}; \node (line2CV)[inner sep=1pt] at (11.2,-5.25){$\ChangedValues$}; \draw [->] (line1G) -- ([yshift=2pt]line2E.north); \draw [->] (line1CV) -- (line2CV); \node [text width=2cm]at (-3, -3.7) {\footnotesize \begin{tabular}{c} Step 2: \\ \sep \end{tabular}}; \node [text width=2cm]at (-4.1, -9.3) {\footnotesize \begin{tabular}{c} Step 3: \\ \baseSort \end{tabular}}; { [start chain =H11], \node(beginH11)[X,right, on chain = H11] at (-3.5,-8.5) {\footnotesize 1}; \node(swapnode1)[X,right, on chain = H11] {\footnotesize 0}; \node[X,right, on chain = H11] {\footnotesize 0}; \node(swapnode2)[X,right, on chain = H11] {\footnotesize 0}; \foreach \i in {0,0,1} \node[X,right, on chain = H11] {\footnotesize \i}; \node (endH11) [X,right, on chain = H11] {\footnotesize 1}; } \node [below=of H11-1]{\textcolor{red!50}{\tiny 0}}; \foreach \x [count=\i] in {2, ...,5} \node [below=of H11-\x]{\textcolor{black!50}{\tiny \i}}; \node [below=of H11-6]{\textcolor{red!50}{\tiny 5}}; \node [below=of H11-7]{\textcolor{black!50}{\tiny 6}}; \node [below=of H11-8]{\textcolor{black!50}{\tiny 7}}; \node [inner sep=1pt,above=of H11-5.north west] {\footnotesize $\sepResult_{1}$}; { [start chain =H21], \node(beginH21)[X,right, on chain = H21] at (-3.5,-10) {\footnotesize 0}; \foreach \i in {0,1,1,0,0,0} \node[X,right, on chain = H21] {\footnotesize \i}; \node (endH21) [X,right, on chain = H21] {\footnotesize 0}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of H21-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of H21-5.north west] {\footnotesize $\sepResult_{2}$}; { [start chain =B1], \node(beginB1)[X,right, on chain = B1] at (1.4,-8.5) {\footnotesize 0}; \foreach \i in {0,0,0,0,1,1} \node[X,right, on chain = B1] {\footnotesize \i}; \node (endB1) [X,right, on chain = B1] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of B1-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of B1-5.north west] {\footnotesize $\base_{1}$}; { [start chain =B2], \node(beginB2)[X,right, on chain = B2] at (1.4,-10) {\footnotesize 0}; \foreach \i in {0,0,0,0,0,1} \node[X,right, on chain = B2] {\footnotesize \i}; \node (endB2) [X,right, on chain = B2] {\footnotesize 1}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of B2-\i]{\textcolor{black!50}{\tiny \x}}; \node [inner sep=1pt,above=of B2-5.north west] {\footnotesize $\base_{2}$}; \draw [->] (endH11) to node [above] {\footnotesize \baseSort} (beginB1); \draw [->] (endH21) to node [above] {\footnotesize \baseSort} (beginB2); { [start chain =S1], \node(beginS1)[X,right, on chain = S1] at (4.7,-8.5) {\footnotesize 1} \foreach \i in {0,0,0,0,0,0,0} \node[X,right, on chain = S1] {\footnotesize \i}; \node (endS1) [X,right, on chain = S1] {\tiny \textcolor{red!50}{5}}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of S1-\i]{\textcolor{black!50}{\tiny \x}}; \node[below =of S1-9]{\tiny \textcolor{red!50}{P}}; % \node [inner sep=1pt,above=of S1-5.north west] {\footnotesize $\Change_{1}$}; { [start chain =S2], \node(beginS2)[X,right, on chain = S2] at (4.7,-10) {\footnotesize 0}; \foreach \i in {0,1,1,0,0,0,0} \node[X,right, on chain = S2] {\footnotesize \i}; \node [X,right, on chain = S2] {\tiny 6}; \node (endS2) [X,right, on chain = S2] {\tiny 7}; } \foreach \x [count=\i] in {0, ...,7} \node [below=of S2-\i]{\textcolor{black!50}{\tiny \x}}; \node[below =of S2-9]{\tiny \textcolor{black!50}{P}}; \node[below =of S2-10]{\tiny \textcolor{black!50}{P}}; \node [inner sep=1pt,above=of S2-6.north west] {\footnotesize $\Change_{2}$}; \node at (9.2, -9.2) {(}; \node (line3B)[inner sep=1pt] at (9.4,-9.2){$\base$}; \node (line3E)[inner sep=1pt] at (9.7,-9.2){,}; \node (line3C)[inner sep=1pt] at (9.97,-9.2){$\Change$}; \node at (10.15,-9.2) {)}; \node (line3E2)[inner sep=1pt] at (10.3,-9.2){,}; \node (line3A)[inner sep=1pt] at (10.5,-9.2){$\Addendum$}; \node (line3E3)[inner sep=1pt] at (10.9,-9.2){,}; \node (line3CV)[inner sep=1pt] at (11.2,-9.2){$\ChangedValues$}; \draw [->] (line2H) -- ([yshift=2pt]line3E.north); \draw [->] (line2A) -- (line3A); \draw [->] (line2CV) -- (line3CV); \node [text width=2cm]at (-3.7, -11.5) {\footnotesize \begin{tabular}{c} Step 4: \\ \dedup \end{tabular}}; \node (forest) at (-0,-11.5) {\begin{tikzpicture}[level distance = 6 mm, sibling distance = 5mm, grow = right] \node {0} child { node{0} child { node{0} edge from parent child { node {0} child { node {0} child { node{0} child { node{0} child { node{1} child { node{1} } } } child { node{1} child { node{1} child { node{1} } } } } } } } }; \end{tikzpicture}}; \node at (0,-12.7) {$\base_{1}$ and $\base_{2}$ stored in \baseset.}; \node (basepointer1) at (4.5, -11.28) {$\basepointer_{1}$ (Pointer to $\base_{1}$)}; \node (basepointer2) at (4.5, -11.75) {$\basepointer_{2}$ (Pointer to $\base_{2}$)}; \draw [->] (basepointer1) -- ([xshift=-4.3pt, yshift=6pt]forest.east); \draw [->] (basepointer2) -- ([xshift=-4.3pt, yshift=-7pt]forest.east); \node (line4P)[inner sep=1pt] at (9.4,-11.8){$\basepointer$}; \node (line3E)[inner sep=1pt] at (9.7,-11.8){,}; \node (line4C)[inner sep=1pt] at (9.97,-11.8){$\Change$}; \node (line4E2)[inner sep=1pt] at (10.3,-11.8){,}; \node (line4A)[inner sep=1pt] at (10.5,-11.8){$\Addendum$}; \node (line4E3)[inner sep=1pt] at (10.9,-11.8){,}; \node (line4CV)[inner sep=1pt] at (11.2,-11.8){$\ChangedValues$}; \draw [->] (line3B) -- (line4P); \draw [->] (line3C) -- (line4C); \draw [->] (line3A) -- (line4A); \draw [->] (line3CV) -- (line4CV); \draw [thick] (-5,4) rectangle (9,-2.2); \draw [thick] (-5,-2.45) rectangle (9,-7.6); \draw [thick] (-5,-7.8) rectangle (9,-10.7); \draw [thick] (-5,-10.9) rectangle (9,-13); \end{tikzpicture} \caption{Example of the Transformations in the \cloud after receiving \outsource.} \label{fig:cloud} \end{figure*} \begin{table}[!t] \caption{The brackets table for the toy example of Fig. \ref{fig:cloud}} \vspace{-.8em} \centering \begin{tabular}{|cc|cc|cc|} \hline & & \multicolumn{4}{c|}{\Bid} \\ & & 0 & 1 & 0 & 1 \\ \hline \multirow{4}{*}{\Sid} & 0 & 0000 & 0100 & 1000 & 1100\\ & 1 & 0001 & 0101 & 1001 & 1101\\ \cline{2-6} & 0 & 0010 & 0110 & 1010 & 1110 \\ & 1 & 0011 & 0111 & 1011 & 1111 \\ \hline \end{tabular} \label{tab:brackets2} \end{table} In the first step, if $\bits= 8$, the \cloud changes the value (\changev) of the symbols to the respective symbol in the first zone of the brackets table, while storing the value id \Vid of all symbols in a separate string denoted by \ChangedValues. This step transforms the received \outsource to a new string denoted by \chnvResult, which includes the values of the symbols after \changev (only 4 possible values). This step is illustrated as Step 1 in Fig.~\ref{fig:cloud}. As an example, the value of symbol ``10'' in position 1 is going to change. Looking at the Brackets table, the binary representation of ``10'', i.e., ``1010'' is in position $[0,0]$ of zone 4, therefore, its value is changed to the symbol in position $[0,0]$ of zone 1, which is ``0000'' in Binary, i.e., ``0''. The \cloud inserts the \Vid of zone 4, i.e., ``3'' into \ChangedValues. After generating \chnvResult, the \cloud uses the Brackets table to separate each symbol into its \Bid and \Sid, creating two strings. \begin{enumerate*} \item String \sepResult which contains the \Bid of the symbols, and \item String \Addendum which contains the \Sid of the symbols. \end{enumerate*} This step is illustrated as step 2 in Fig.~\ref{fig:cloud}. As an example, the first symbol in $\outsource_{1}$, i.e., $4$ has a $\Bid = 1$ and a $\Sid=0$. Therefore, the \cloud inserts 1 in the first position of \base, and 0 in the first position of \Addendum. \begin{algorithm}[!b] \caption{The algorithm to find swaps}\label{alg:cap} \begin{algorithmic} \STATE Initiate $swaps$ as an empty vector. \STATE $j\gets 0$ \WHILE {$j < \sorg$} \IF {$\base[j] \neq \sepResult[j]$} \STATE Find minimum $k$ where $\base[k] = \sepResult[j] \neq \sepResult[k]$ \STATE Swap $\sepResult[j]$ and $\sepResult[k]$ \STATE Add $(j,k)$ to $swaps$ \ENDIF \STATE $j\gets j+1$ \ENDWHILE \end{algorithmic} \end{algorithm} In the next step, the cloud sorts \sepResult to generate \base. We use Mergesort~\cite{cormen2009introduction} as a quick and scalable sorting algorithm in order to generate \base from \sepResult. In order to reconstruct \sepResult and ultimately \outsource later in decompression phase, the \cloud stores the necessary information about the difference between \sepResult and \base. This information is stored in \Change as the required swaps to trasnform \sepResult into \base. In order to identify the required swaps, the \cloud compares \base with \sepResult, using an algorithm inspired by Cycle Sort~\cite{cormen2009introduction}, Our algorithm does not sort \sepResult, instead, it attempts to find the minimum number of \swap required to transform \sepResult into \base. In detail, the algorithm finds the first position $j$, where the symbol is different in \sepResult and \base, i.e., $\base[j] \neq \sepResult[j]$ This indicates that the value needs to be swapped in order to generate \base. Then, the algorithm finds the first possible position $k > j$ in \base where $\base[k] = \sepResult[j]$, so that if the symbols in positions $j$ and $k$ are swapped in \sepResult, the symbol in position $j$ will be equal to the corresponding symbol in \base. In order to mitigate extra swaps, the \cloud ensure that the symbol in position $k$ is not already in correct position by checking if the symbol in position $k$ in \base is equal to the symbol in position $k$ of \sepResult. i.e., the swap is only performed if $\base[k] \neq \sepResult[k]$, otherwise the \cloud searches for the next valid $k$. This algorithm continues until all the symbols are in their sorted positions. Algorithm~\ref{alg:cap} shows the pseudocode for the steps taken by our algorithm. Note that our algorithm is sub-optimal (finding the minimal number of swaps to make two arrays identical is NP-hard \cite{gutin2014parameterized}). After identifying the swaps, The \cloud generates \Change. \Change consists of two parts, a bitmap of size \sbase, and an array consisting of positions. The \cloud starts by setting all values in the bitmap to zero, and initiating an empty array. For each identified swap between two positions $i$ and $j$, where $i <j$, the \cloud: \begin{enumerate*} \item Sets the value of position $i$ in the bitmap to 1. \item Adds $j$ to the array that stores the positions. \end{enumerate*} Step 3 of Fig.~\ref{fig:cloud} shows the final result of this algorithm in our toy example. In this particular example, for $\outsource_{1}$, only one swap is needed between the symbols in positions 0 and 5. Hence, in \Change, the value in position 0 is set to ``1''. The \cloud adds ``5'' to \Change, which uniquely identifies the performed swap to be between positions ``0'' and ``5''. The \cloud stores all bases in a set \baseset. We leverage the fact of having sorted bases in the \cloud to create an efficient data structure to search for possible deduplications. To achieve this, we use a forest structure to store \baseset. The roots are the first elements of the stored bases and each child has the next element of its parents. Each leaf represents a single \base. The \cloud assigns a pointer to each leaf, which will indicate the \base associated to it. Step 4 of Fig.~\ref{fig:cloud} gives an intuition of how this structure is generated, given the \cloud only has the two bases of the \outsource shown in our example. In our case, the forest structure is composed by single tree, due to the fact that both of the bases in the \cloud have the same initial element (with value $0$). After creating \base, the \cloud searches for \base in \baseset. If \base is found in the \baseset, the \cloud deduplicates \base and store the pointer \basepointer to the \base along with the respective \Addendum, \Change and \ChangedValues of the \outsource. Otherwise, the \cloud will add \base to \baseset, assign a pointer \basepointer to it and store \basepointer, \Addendum, \Change and \ChangedValues to represent \outsource. Using this structure, it is easy to see that the time complexity for searching for a \base in \baseset is $O(\sbase)$ time. The addition of a new base to the tree takes $O(\sbase)$ time. This is a significant improvement compared to Yggrdasil \cite{yggdrasil}, where the possible deduplications are found using brute-force search, taking up to $O(\sbase^{2}\cdot \nob)$ time. \paragraph{Decompression} When the \cloud receives a request from a \user that wants to retrieve its data, it reconstructs the \outsource from \basepointer, \Addendum, \Change and \ChangedValues. In this procedure, the \cloud simply reverses the steps taken to generate the four strings. \subsection{Protocol Breakdown}\label{sec:algo} We describe our protocol for privacy-aware dual deduplication in multi client settings by pointing out the algorithms done in \user, \cloud and between them. At initialization \cloud holds an initial set $n_b$-size strings called bases $\baseset=\{\base_1,\ldots, \base_b\}$. $\baseset$ may be empty at the start of the algorithm, in the case that the cloud has not received any data yet. However, $\baseset$ is updated over time by the outsourced data from the \users. \begin{figure}[!t] \centering \begin{tikzpicture}[font=\small\sffamily, thick, scale=0.7] \node[cloud, cloud puffs=19, cloud ignores aspect, minimum width=6.5cm, minimum height=2.5cm, align=center, draw] at (0cm, 0cm) {}; \node [alias=cloud] at (0,-1.2){}; \node [alias=setup,style={rectangle, draw=red!60, fill=red!5, very thick}] at (-2.5,0){1. \setup}; \node [alias=dedup,style={rectangle, draw=red!60, fill=red!5, very thick}] at (2,0){3. \dedup}; \node [alias=set] at ([xshift=25,yshift=22] setup.east){$\baseset$}; \node [alias=rec,style={rectangle, draw=red!60, fill=red!5, very thick}] at (-0.14,-1){\decompress}; \draw (.7,-3.2) node[anchor=north,rounded rectangle,minimum width=3.3cm, minimum height=.8cm, draw, alias=one]{}; \node[alias=get,style={rectangle, draw=blue!60, fill=blue!5, very thick}] at (-.5,-3.8) {{\get}}; \node[alias=upload,style={rectangle, draw=blue!60, fill=blue!5, very thick}] at ([xshift=42pt]get.east) {2. \upload}; \node [alias=policy, style={rectangle, minimum width=1.1cm,minimum height=1.1cm, draw=black!60, thin}] at ([xshift=-60pt,yshift=20pt] get.west){$\policy$}; \path[->, dashed,thin] ([yshift=-3pt]policy.south) edge [bend right] ([xshift=-3pt,yshift=-6pt]one.west); \path[->, thick,red] ([yshift=-3pt,xshift=-10pt]setup.south) edge [bend right] ([yshift=2pt]policy.north); \path[->, very thick,blue] ( [yshift=3pt]upload.north) edge [bend right] ([yshift=-3pt]dedup.south); \path[->, very thick,blue] ( [xshift=-6pt,yshift=3pt] get.north) edge [bend left] ([xshift=-8pt,yshift=-3pt]rec.south); \path[->, thick,red] ( [xshift=8pt,yshift=-3pt] rec.south) edge [bend left] ([xshift=6pt,yshift=3pt]get.north) ; \path[<->, dashed,thin] ([xshift=-3pt]set.east) edge (dedup.west); \path[->, dashed,thin] ([xshift=-3pt]set.west) edge ([yshift=3pt]setup.east); \path[->, dashed,thin] ([xshift=1pt]set.south) edge (rec.north); \end{tikzpicture} \vspace{-.8em} \caption{\name System Model for Secure, Multi-client Dual Deduplication} \label{fig:bonsai} \vspace{-1.5em} \end{figure} \begin{description} \item[$\setup(\baseset)$:] This algorithm is run by the \cloud periodically. It takes as input the set of bases \baseset and outputs a policy $\policy = \{\sbase, \clouddistribution\}$. \item[$\upload(\policy,\file)$:] This algorithm is run by \user. On input \policy and a file \file, the \user runs local transformations \transformation to generates a base \outsource of size $n_{b}$, and its corresponding deviation \local. Then, it generates a unique file identifier \id. The algorithm outputs the triple (\id, \outsource, \local). The pair (\id, \outsource) is outsourced to the \cloud, while (\id, \local) is stored locally by the \user. \item[$\dedup(\id, \outsource, \baseset)$:] This algorithm is run by the \cloud. On the input a file identifier \id, a string \outsource, and the set of bases \baseset, the \cloud generates the respective \base, \Addendum, \Change and \ChangedValues; the \cloud checks whether $\base\in \baseset$, in which case it stores its respective pointer, \basepointer, if not, \cloud adds \base to \baseset and assigns a pointer \basepointer to it; The algorithm outputs (\id, \basepointer, \Addendum, \Change, \ChangedValues). \item[$\get(\id, \local)$:] This algorithm collects the \user's procedures of an interactive protocol with \cloud to retrieve an outsourced data item. First, \user sends \id, symbolizing a request to retrieve the item that was outsourced with that \id. Upon receiving a response \outsource from \cloud, the \user uses the information encoded in \local to invert the deletions that led to \outsource, reconstructing \file. \item[$\decompress(\database, \id)$:] This algorithm collects the \cloud's procedures of an interactive protocol to let a \user download an outsourced data item. Upon receiving an \id request, \cloud checks whether \id exists in the database. If not, it ignores the query. Otherwise, it retrieves the corresponding record (\id, \basepointer, \Addendum, \Change, \ChangedValues); inverts the deduplication performed by \dedup; reconstructs the decompressed \outsource corresponding to the outsourced string; and returns \outsource back to the \user. \end{description} \section{Introduction} \label{intro} Due to emerging applications that produce massive amounts of data, many systems choose to use Cloud Service Providers (CSPs) to outsource the storage of their data. In order to deliver a cost-effective service to their clients, CSPs tend to use compression techniques to reduce the fingerprint of the data. This includes a number of file compression techniques, e.g., DEFLATE \cite{deutsch1996rfc1951}, BZIP2 \cite{gilchrist2004parallel}, Brotli \cite{alakuijala2018brotli}, as well as delta encoding approaches, e.g., VCDIFF \cite{korn2002vcdiff}, which focus on individual chunks of data or files for compression. As an alternative, data deduplication~\cite{Jin2009} removes duplicate data across different files and even different users in the system. Data deduplication stores a copy of each unique chunk and represents files with pointers to these unique chunks. In a nutshell, it avoids storing duplicates \cite{xia2016comprehensive}. In most practical storage systems, both deduplication and compression are used for a more efficient reduction of the fingerprint of the data \cite{constantinescu2011mixing}. Recently, generalized deduplication \cite{rasmus} has been proposed as an improvement to data deduplication. In this case, the storage system is not only capable of removing exact duplicates, but also chunks of files that are close to each other according to a certain metric~\cite{Vestergaard2019a}. At its core, generalized deduplication in a cloud setting works as follows. The CSP maintains a set of bases. For each received chunk of file, if the chunk is already present in the set of bases the CSP deduplicates it by storing a file identifier and a pointer representing the base. Otherwise, the CSP looks for a base similar to the given chunk, i.e., a chunk in the set of bases that has a short distance to the received chunk, e.g., according to the Hamming distance~\cite{Vestergaard2019a} or the Swap distance~\cite{yggdrasil}. If such a base is found, the CSP deduplicates this record in a generalized way by storing a file identifier, a pointer representing the closest base, and a string containing the difference between the base and the chunk. Finally, if no similar bases are present in the set of stored bases, the CSP considers the chunk as a new base to add to the list of bases. A major drawback of allowing the CSP to carry out (generalized) deduplication is that the CSP must be provided with the actual data. This is not desirable in applications where clients may upload sensitive information or are concerned about data privacy. A naive solution would be to encrypt the data and upload only ciphertexts. This approach, however, drastically reduces the deduplication capability on the CSP, as secure encryption implies little or no correlation among ciphertexts. An alternative approach is to use convergence encryption~\cite{bellare2013message}, to maintain a balance between privacy and compression. The main weakness of convergence encryption is that a nosy CSP or even a malicious client can attack the system to discover which chunks have been stored previously in the system, exposing sensitive information to the malicious party. Moreover, the CSP can obtain exact information about the files of each user given sufficient time and resources, by breaking the encryption of the outsourced data~\cite{akhila2016study}. The work by Vestergaard et al.~\cite{lucani2020secure} proposes an alternative mechanism to convergence encryption, which is called Multi-Key revealing Encryption (MKRE). In~\cite{lucani2020secure} chunks are transformed before upload so that any two similar chunks yield outsourced data that are close to each other. Although this method is shown to be more robust against attempts to break the encryption, its security is proven only in the programmable random oracle model, which is not realistic as it cannot be faithfully implemented by hash functions. Recently, the work by Sehat et al.~\cite{yggdrasil} bypasses the programmable random oracle challenge and introduces a unique privacy-aware deduplication mechanism for multi-client environments called \emph{dual deduplication}. In dual deduplication, clients perform information-theoretic transformations on their data before uploading it to the CSP. These transformations aim at puncturing the data to simultaneously increase deduplication capabilities on the CSP, and creating uncertainty for the CSP about the possible pre-images of the uploaded chunk. From a high level perspective, to the eye of a CSP or an attacker, the dual deduplication system proposed in~\cite{yggdrasil} mimics a \emph{deletion channel} from information theory \cite{mitzenmacher2009}. In particular it is known that retrieving the original data after transmission through the deletion channel is a hard problem. predicting how input data will be modified by the channel is hard as well~\cite{mitzenmacher2009}. While these properties are undesirable to establish a reliable communication between two parties, dual deduplication uses them as key features for proving the privacy of the system. In this work, we build on the dual deduplication idea introduced in~\cite{yggdrasil}, and mitigate the three major drawbacks of the original construction. First, clients in~\cite{yggdrasil} need to store a significant portion of their data locally. This is contrary to the intent of outsourcing data to a CSP and minimizing local storage. Second, the CSP in~\cite{yggdrasil} must perform a brute force search to find the matches for each uploaded chunk to achieve the best compression rate. Third, the system in \cite{yggdrasil} is proven private only as long as the CSP lacks information about the probability distribution of the client's original data. This assumption does not hold for databases that are very homogeneous, or with predictable data such as time-series data or e-mail texts. The main goal of our paper is to face the aforementioned drawbacks and provide concrete, efficient solutions to address these issues. To this end, we propose \emph{Bonsai}, a fully fledged, yet scaled down (in terms of storage requirements and complexity) alternative to the Yggdrasil approach proposed in \cite{yggdrasil}. The name \name is chosen to maintain a connection to and provide figurative comparison with the original dual deduplication method Yggdrasil, named after the tree of life in Norse mythology. Moreover, in \name the CSP transforms and stores the received data in a tree structure that resembles a bonsai, which is a small-size version of a tree. \subsection{Our Contribution} We propose a new transformation mechanism for dual deduplication that improves the \emph{scrambling} of outsourced data, and achieves better privacy guarantees than~\cite{yggdrasil}. Compared to~\cite{yggdrasil}, our method requires less storage on the client side and maintains good compression rates on the CSP. This is done by employing a Pseudo-Random Number Generator (PRNG) to determine the positions of the symbols to be deleted. This change removes the need to store the positions of deleted elements on the client side, thus effectively reducing the storage requirements from 18\% in \cite{yggdrasil}, to only 5\% in \name. We present an innovative deduplication mechanism that lets the CSP identify possible deduplications efficiently (instead of bruteforcing as in \cite{yggdrasil}). Our technique stores bases on the CSP in a forest data structure, which reduces the computational cost of finding deduplicates and adding new bases as well as reducing the storage cost for the bases. In addition, we improve the compression potential on the CSP using an approach inspired by Huffman Codes and replacing the symbols with lower probability distribution. Our method achieves a competitive compression rate of 68\% in the cloud, while allowing deduplication and maintaining privacy guarantees. We prove our proposed method to be privacy-aware, in the sense that an honest-but-curious CSP faces a high degree of uncertainty when guessing what the original data of the clients is. In contrast to~\cite{yggdrasil}, this claim holds even assuming the CSP has knowledge of the distribution of clients' original data, as well as of the number of performed deletions. \begin{figure}[!t] \centering \begin{tikzpicture} [scale=0.65] \begin{axis}[ xlabel= $chunksize \,(Bytes)$, ylabel=$Compression\; rate$, xlabel style={font=\large}, xtick = {6,8,10,12,14,16}, xticklabels = {$2^{6}$,$2^{8}$, $2^{10}$, $2^{12}$, $2^{14}$, $2^{16}$}, ymin=0, ymax = 1.3, grid=major, legend pos= outer north east] \addplot[mark= +, smooth ,black, thick] plot coordinates { (5, 0.84 (6, 0.88 (7, 0.94 (8, 0.98 (9,1.02) (10,1.05) (11,1.09) (12, 1.12) (13, 1.14) (14,1.14) (15,1.14) (16,1.14) }; \addlegendentry{SecDedup\cite{zhang2020secdedup}} \addplot[mark = o, smooth, red, thick] plot coordinates { (5, 0.54 (6, 0.56 (7, 0.58 (8, 0.64 (9,0.69) (10,0.74) (11,0.78) (12, 0.83) (13, 0.87) (14, 0.91) (15,0.94) (16,0.97) }; \addlegendentry{\name} \addplot[mark=x, blue, thick] plot coordinates { (5, 0.54 (6, 0.58 (7, 0.62 (8, 0.69 (9,0.76) (10,0.82) (11,0.87) (12, 0.96) (13, 1.03) (14, 1.09) (15, 1.17) (16, 1.26) }; \addlegendentry{Yggdrasil \cite{yggdrasil}} \addplot[mark=diamond, smooth,teal, thick] plot coordinates { (5, 0.32 (6, 0.33 (7, 0.35 (8, 0.37 (9, 0.39) (10, 0.42) (11, 0.45) (12, 0.48) (13, 0.52) (14,0.55) (15,0.57) (16,0.59) }; \addlegendentry{Brotli\cite{alakuijala2018brotli}} \addplot[mark=oplus, smooth,violet, thick] plot coordinates { (5, 0.27 (6, 0.25 (7, 0.25 (8, 0.26 (9,0.28) (10,0.30) (11, 0.32) (12, 0.34) (13, 0.36) (14,0.37) (15,0.38) (16, 0.39) }; \addlegendentry{\name + Brotli \addplot[mark=pentagon, dashed, smooth, brown, thick, mark options={solid}] plot coordinates { (5, 0.23 (6, 0.22 (7, 0.24 (8, 0.26 (9,0.28) (10, 0.30) (11, 0.32) (12, 0.34) (13, 0.36) (14, 0.37) (15, 0.38) (16, 0.39) }; \addlegendentry{SecDedup +\name + Brotli \end{axis} \end{tikzpicture} \caption{Total compression rates for different chunk sizes using \name (this work), Yggdrasil~\cite{yggdrasil}, SecDedup \cite{zhang2020secdedup}, Brotli~\cite{alakuijala2018brotli}, and combination of these techniques (lower is better). \label{fig:intro} \end{figure} Finally, to showcase the performance impact of \name on a cloud storage system, we used a DVI dataset of 10~GB and collected simulations for compression ratios achieved by \name, Yggrdasil~\cite{yggdrasil}, data deduplication (DD)~\cite{zhang2020secdedup}, and Brotli~\cite{alakuijala2018brotli}. The comparison is illustrated in Fig.~\ref{fig:intro}, where plots display the ratios between the total storage required after compression (considering both client and CSP) and the size of the actual data. A compression rate of 1 indicates no compression and values above 1 expand the size of the data. The lower the compression rate, the less storage is needed for each original bit (i.e., better compression). As Fig~\ref{fig:intro} suggests, \name has better compression rate than its predecessor Yggrasil \cite{yggdrasil}, especially on larger chunk sizes. Brotli outperforms \name in compression rate, which is expected as \name is mostly a deduplication technique, which tend to have lower compression rates than universal compressors. However, Brotli provides no privacy guarantees, in contrast to \name. Interestingly, combining \name with Brotli (i.e., using Brotli to compress the result of the deduplication process) yields much better compression than each individual approach. This suggests that \name creates highly compressible data, even when the original data is homogenous. Finally, applying data deduplication to find repeated blocks of data before applying \name and Brotli further increases the compression gain for low chunk size. Intuitively, this is due to the fact that \name adds metadata to find matches across \emph{different} data blocks, which is unnecessary for deduplicating identical chunks. The gains are seen for smaller chunk sizes, disappearing for larger chunk sizes due to the fact that the probability of finding an exact duplicates is reduced as the size of the chunks increases. The outline of this paper is as follows. In Section~\ref{sec:RelWork}, we describe the related work on (generalised) deduplication and privacy in systems using deduplication. In Section~\ref{sec:model}, we present our system model. In Section~\ref{sec:contribution}, we propose \name and clearly describe its core algorithms and processing steps. Section~\ref{sec:analysis} includes the analysis of the system in terms of privacy, compression rate and computation cost. Section~\ref{sec:experiments} includes our simulation results and discussion about the performance of \name. Finally, we conclude in Section~\ref{sec:conclusion}. \section{Simulation Results and Discussion}\label{sec:experiments} In this section, we show and discuss the performance of \name in terms of its compression rate and privacy. We use three different real world datasets, including, $14$~GB of email texts in enron-mail dataset \cite{shetty2004enron}, $18$~GB of Hadoop Data File System (HDFS) logs \cite{he2020loghub} and $10$~GB of DeVice Independant (DVI) files \cite{10.3389/fncir.2019.00005}. We developed a C++ implementation consisting of a \name client applying deletions and a server performing deduplication algorithm described in this work. For the sake of storage friendly implementation, we defined the \id of bases to be a global variable auto-incremented by the Cloud. This is also used for the pointers to the bases in the \cloud. \textbf{Compression rate for different symbol size:} Fig.~\ref{fig:result1} shows the compression rate of \bonsai for the three datasets for two different symbol size of $\bits=4$ and $\bits=8$. For $\bits = 8$, \name achieves a total compression rate of $\compratio = 0.6473$ for the DVI dataset, where the \cloud achieves a compression rate of $\ccr = 0.6391$, and the \user stores $\ucr = 0.0082$ of the data. For the same dataset, the total compression rate for $\bits = 4$ is equal to $\compratio = 0.8207$, where the \cloud and the \user store $\ccr = 0.8125$ and $\ucr = 0.0082$ of the data respectively. We note that \name does not drop significantly in compression potential by using diverse data, as the total compression rate for all three datasets is $\compratio = 0.7473$ when $\bits = 8$ and $\compratio = 0.7986$ when $\bits=4$. This is an interesting characteristic of \name which shows the potential to outperform other compression techniques in heterogenous datasets or workloads (e.g., mixed data sources with different characteristics and statistics). Fig.~\ref{fig:result1} also suggests that for a fixed size of the original file $\bits\cdot\sorg = 2048$, the total compression rate and the compression rate on the \cloud is better when the size of symbols is set as $k=8$. This is because (1) \name cannot reduce the size of \Sid and \Vid using Huffman coding when $\bits=4$, as opposed to $k=8$ leading to more storage requirement for \Addendum and \ChangedValues when $k=4$; and, (2) there are more symbols when $k=4$, therfore, the \cloud needs to assign more storage for the positions when storing swaps in \Change. \begin{figure}[!t] \centering \begin{tikzpicture}[ scale=0.7, every axis/.style={ ybar stacked, ylabel = {\compratio}, xlabel = {\bits}, xmin={[normalized]0}, xmax={[normalized]3}, xtickmax={[normalized]2}, xtick distance = 1, ymin = 0, ymax = 1, symbolic x coords={ 0, $4$, $8$ }, bar width=8pt, legend style={legend columns=-1,at={(0.267,0.93),},anchor=west}, }, ] \begin{axis}[bar shift=-13.5pt, hide axis] \addplot+[fill=green] coordinates {($4$,0.7351)($8$,0.7045)}; \addplot+[fill=blue] coordinates {($4$,0.0082)($8$,0.0082)}; \legend{\strut \cloud, \strut \user} \end{axis} \begin{axis}[bar shift=-4.5pt, hide axis] \addplot+[fill=green] coordinates {($4$,0.8125)($8$,0.6391)}; \addplot+[fill=blue] coordinates {($4$,0.0082)($8$,0.0082)}; \legend{\strut \cloud, \strut \user} \end{axis} \begin{axis}[bar shift=0pt] \end{axis} \begin{axis}[bar shift=4.5pt, hide axis] \addplot+[fill=green] coordinates {($4$,0.8333)($8$,0.7616)}; \addplot+[fill=blue] coordinates {($4$,0.0082)($8$,0.0082) }; \end{axis} \begin{axis}[bar shift=13.5pt, hide axis] \addplot+[fill=green] coordinates {($4$,0.7904)($8$,0.7391)}; \addplot+[fill=blue] coordinates {($4$,0.0082)($8$,0.0082) }; \end{axis} \end{tikzpicture} \vspace{-1em} \caption{The compression rate in the \cloud and the \user for $\bits\cdot\sorg = 2048 bits$ and $\bits\cdot\sbase = 1928 bits$. The first column is for HDFS dataset. The second column is for DVI dataset, the third column is for enron-mail and the fourth column is when all three datasets are used.} \label{fig:result1} \end{figure} \textbf{Compression rate for different number of deletions:} Fig.~\ref{fig:results0} shows the behavior of \name for different number of deletions in the \user side and its effect on the total compression rate. As this figure suggests, increasing the number of deletions in the \user, initially results in \name gaining in terms of total compression rate. This is due to the fact that a larger number of deletions have two effects on the outsourced data. First, it reduces the size of the outsourced data, allowing for more potential deduplications and lower number of required swaps. Second, it alters the probability distribution of the outsourced data more, giving more chance to have a closer probability distribution as the distribution indicated in the policy. However, after a certain threshold (14 deletions for $\bits=4$ and 15 deletions for $k=8$), this trend does not continue and the compression rate stays the same. This is due to the fact that after this threshold, the compression gain on the \cloud is quite low, and is offset by higher storage requirements in the \user. As the \cloud does not compress \Addendum and \Change, which consist of \Sid and \Vid of the symbols, there is a lower bound on the compression rate achievable by the \cloud. After this point, the compression rate on the \cloud improves this improvement, but it is equal to or less than the loss of compression in the \user, leading to a roughly constant total compression rate. This behavior can be seen for both cases of $\bits = 4$ and $bits=8$. However, in the case of $\bits=8$ the compression rate declines faster by increasing the numjber of deletions, compared to $\bits=4$; as deletion of the symbols with low probability distribution has a higher effect on reducing the number of required swaps; and shaping the probability distribution of the symbols, leading to more optimal values for \Sid and \Vid. \begin{figure}[!t] \centering \begin{tikzpicture} [scale=0.8] \begin{axis}[ xlabel= {$\sorg-\sbase [ Bytes] $}, ylabel=$\compratio$, xlabel style={font=\large}, ymin =0, ymax = 1.5, grid=major, legend pos= south east] \addplot[mark=+, smooth ,red, thick] plot coordinates { (1, 0.8841) (2, .8612) (3, .8439 (4, .8273 (5, .8149 (6, .8041 (7, .7950 (8, .7877) (9, .7789) (10, .7720) (11, .7667) (12, .7621) (13, .7568 (14, .7459 (15, .7433 (16, .7415) (17, .7404) (18, .7396) (19, .7392) }; \addlegendentry{$k=4$} \addplot[mark=x, smooth, dotted, blue, thick, mark options={solid}] plot coordinates { (1, 0.9932) (2, .9767) (3, .9607 (4, .9395 (5, .9164 (6, .8957 (7, .8749 (8, .8542) (9, .8339) (10, .8033) (11, .7728) (12, .7527) (13, .7339 (14, .7230 (15, .7127 (16, .7122) (17, .7122) (18, .7122) (19, .7122) }; \addlegendentry{$k=8$} \end{axis} \end{tikzpicture} \caption{Compression rates for HDFS dataset for different values of $\sbase$ when $\sorg = 256$. (Lower is better.)} \label{fig:results0} \end{figure} \textbf{Comparison between Bonsai, Yggdrasil and MKRE:} Fig.~\ref{fig:result2} shows the comparison of \name with the closest related work, namely Generalized Deduplication via Multi-Key Revealing Encryption (MKRE) ~\cite{Vestergaard2019b}, and Dual Deduplication via Yggdrasil \cite{yggdrasil}. In terms of the global compression rates, as we saw in Fig.~\ref{fig:result1}, \bonsai has a better compression rate for \bits=8 for all datasets used in this work; therefore, this figure only contains the compression rate for \bits=8. In this Fig.~\ref{fig:result2}, we compare the total compression ratio gained for each dataset using different values of \sorg. As illustrated in this figure, the best compression rate achievable by MKRE~\cite{Vestergaard2019b} and Yggdrasil is nearly the same as the compression ratio achieved by \name for HDFS datasets, with \name eventually outperforming both Yggdrasil and MKRE for large files ($\bits\cdot\sorg \geq 2^{12}$). In more homogeneous datasets, such as DVI, MKRE outperforms both Yggdrasil and \name by achiveing a compression rate of 0.33 for file size of $2^{10}$, compared to 0.82 for Yggdrasil and 0.74 for \name. Whereas \name outperforms MKRE when using datasets with more diversity, such as enron-mail dataset. For example, The difference between compression rate of \name and MKRE for a file size of $\bits\cdot\sorg = 2^{9}$ is 0.26. We note that \name provides information-theoretic security compared to cryptographic security provided by MKRE, giving an edge to \name in many use cases, while maintaining a competitive compression potential. This figure also suggests that in all datasets, \name outperforms Yggdrasil when the file size is $\bits\cdot\sorg \geq 2^{10}$. In lower chunk sizes, Yggdrasil outperforms \name in both HDFS logs and enron-mail dataset, yggdrasil outperforms \name for a file size of $\bits\cdot\sorg \leq 2^{10}$. However, unlike \name, Yggdrasil finds potential deduplications by brute-force search, which introduces huge time complexity for large amounts of data. \begin{figure}[!t] \centering \subfloat[HDFS]{\begin{tikzpicture} [scale=0.7] \begin{axis}[ xlabel= {$\bits\cdot \sorg [Bits]$}, ylabel=$\compratio$, xlabel style={font=\large}, xtick = {0,1,2,3,4,5,6,..., 16}, xticklabels = {,,,,,$2^{5}$,$2^{6}$,$2^{7}$,$2^{8}$,$2^{9}$,$2^{10}$,$2^{11}$,$2^{12}$,$2^{13}$,$2^{14}$,$2^{15}$,$2^{16}$}, ymin=0, ymax = 1.5, grid=major, legend pos= north west] \addplot[mark= +, smooth ,black, thick] plot coordinates { (5, 0.49) (6, 0.63) (7, 0.68 (8, 0.65 (9, 0.66 (10, 0.65 (11, 0.68 (12, 0.73) (13,0.78) (14,0.85) (15,0.89) (16,0.91) }; \addlegendentry{$MKRE$} \addplot[mark = o, smooth, violet, thick] plot coordinates { (5, 0.60) (6, 0.63) (7, 0.64 (8, 0.65 (9, 0.68 (10, 0.72 (11, 0.74 (12, 0.77) (13,0.80) (14,0.84) (15,0.88) (16,0.92) }; \addlegendentry{Yggdrasil} \addplot[mark=x, smooth,blue, thick] plot coordinates { (5, 0.68) (6, 0.71) (7, 0.70 (8, 0.69 (9, 0.68 (10, 0.72 (11, 0.71 (12, 0.69) (13,0.72) (14,0.77) (15,0.82) (16,0.85) }; \addlegendentry{\name} \end{axis} \end{tikzpicture}} \\ \subfloat[DVI]{\begin{tikzpicture} [scale=0.7] \begin{axis}[ xlabel= {$\bits\cdot\sorg [Bits]$}, ylabel=$\compratio$, xlabel style={font=\large}, xtick = {0,1,2,3,4,5,6,..., 16}, xticklabels = {,,,,,$2^{5}$,$2^{6}$,$2^{7}$,$2^{8}$,$2^{9}$,$2^{10}$,$2^{11}$,$2^{12}$,$2^{13}$,$2^{14}$,$2^{15}$,$2^{16}$}, ymin=0, ymax = 1.5, grid=major, legend pos= north west] \addplot[mark= +, smooth ,black, thick] plot coordinates { (5, 0.42) (6, 0.39) (7, 0.37 (8, 0.35 (9, 0.34 (10, 0.33 (11, 0.33 (12, 0.33) (13,0.38) (14,0.42) (15,0.48) (16,0.52) }; \addlegendentry{$MKRE$} \addplot[mark = o, smooth, violet, thick] plot coordinates { (5, 0.54 (6, 0.58 (7, 0.62 (8, 0.69 (9,0.76) (10,0.82) (11,0.87) (12, 0.96) (13, 1.03) (14, 1.09) (15, 1.17) (16, 1.26) }; \addlegendentry{Yggdrasil} \addplot[mark=x, smooth,blue, thick] plot coordinates { (5, 0.54 (6, 0.56 (7, 0.58 (8, 0.64 (9,0.69) (10,0.74) (11,0.78) (12, 0.83) (13, 0.87) (14, 0.91) (15,0.94) (16,0.97) }; \addlegendentry{\name} \end{axis} \end{tikzpicture}} \\ \subfloat[Enron-mail]{\begin{tikzpicture} [scale=0.7] \begin{axis}[ xlabel= {$\bits\cdot\sorg [ Bits]$}, ylabel=$\compratio$, xlabel style={font=\large}, xtick = {0,1,2,3,4,5,6,..., 16}, xticklabels = {,,,,,$2^{5}$,$2^{6}$,$2^{7}$,$2^{8}$,$2^{9}$,$2^{10}$,$2^{11}$,$2^{12}$,$2^{13}$,$2^{14}$,$2^{15}$,$2^{16}$}, ymin=0, ymax = 1.5, grid=major, legend pos= south west] \addplot[mark= +, smooth ,black, thick] plot coordinates { (5, 1.08) (6, 0.98) (7, 0.96 (8, 0.99 (9, 1.06 (10, 1.09 (11, 1.28 (12, 1.33) (13,1.35) (14,1.40) (15,1.41) (16,1.42) }; \addlegendentry{MKRE} \addplot[mark = o, smooth, violet, thick] plot coordinates { (5, 0.73) (6, 0.76) (7, 0.78 (8, 0.78 (9, 0.82 (10, 0.80 (11, 0.79 (12, 0.85) (13, 0.93) (14,0.95) (15,1.05) (16,1.16) }; \addlegendentry{Yggdrasil} \addplot[mark=x, smooth,blue, thick] plot coordinates { (5, 0.78) (6, 0.82) (7, 0.85 (8, 0.83 (9, 0.80 (10, 0.78 (11, 0.79 (12, 0.76) (13,0.81) (14,0.82) (15,0.85) (16,0.93) }; \addlegendentry{\name} \end{axis} \end{tikzpicture}} \caption{The total compression rate for different values of \sorg using \name, Yggdrasil~\cite{yggdrasil} and MKRE~\cite{rasmus} and \name for symbol size $\bits=8$. (Lower is better.)} \label{fig:result2} \end{figure} Fig.~\ref{fig:resultcomp} provides a more detailed side-by-side comparison of the best achievable compression rate on the HDFS dataset using different methods with file size of $\sorg=256$ and symbol size of $\bits = 8$. In this case, Yggdrasil achieves the best compression rate on the \cloud (0.6312\%), with the expense of high storage requirements on the \user (0.1819). MKRE achieves the best total compression rate of 0.7561 between the three methods that provide privacy, i.e., Yggdrasil (0.8131) and \name (0.7668) . We note that \name holds the middle ground by providing competitive compression rate, both in terms of total compression rate and the compression rate on the \cloud. We also note that the privacy provided by \name holds without any cryptographic assumptions. AS this figure suggests, Brotli outperforms all deduplication schemes by achieveing a compression rate of 0.3517. However, this is expected as the DVI dataset is a highly compressable dataset with a low number of duplicate files, which works well with traditional compression techniques as opposed to deduplication schemes. \begin{figure}[!t] \vspace{-2em} \centering \begin{tikzpicture}[] \begin{axis}[scale=0.7, ybar stacked, ylabel = {\compratio}, ymin=0, ymax = 1, symbolic x coords={ $GD$, $ME$, $YG$, $BN$, $BT$ }, bar width=8pt, xtick=data, bar shift=-4pt, legend style={legend columns=-1,at={(0.167,0.93),},anchor=west}, ] \addplot+[fill=green, on layer={axis foreground}] coordinates {($YG$,0.6312)($GD$,0.8106) ($ME$,0.6508) ($BN$, 0.7118) ($BT$, 0.3517)}; \addplot+[fill=blue, on layer={axis foreground}] coordinates {($YG$,0.1819)($GD$,0) ($ME$,0.1053) ($BN$, 0.05) ($BT$,0)}; \legend{\strut \cloud, \strut \user}; \end{axis} \end{tikzpicture} \vspace{-1em} \caption{Compression ratios for different deduplication techniques on files from DVI dataset for $\sorg=256$ and $\bits=8$. $ME$ and $YG$ denote Multi-key revealing encryption~\cite{rasmus} and Yggdrasil~\cite{yggdrasil} respectively. $BN$ denotes \name. $GD$ and $BT$ denote generalized deduplication~\cite{Vestergaard2019a} and Brotli~\cite{alakuijala2018brotli} respectively. $GD$ and $BT$ do not provide privacy for the users' data.} \label{fig:resultcomp} \end{figure} \textbf{Privacy:} Fig.~\ref{fig:leakage1} shows the amount of leakage for a strong adversary and weak adversary when the PRNG has been broken. This figure suggests that \name leaks significantly less information to a strong adversary compared to a weak adversary. As a practical example, for $\bits=8$ and $\sorg-\sbase = 15$, Leakage to \Sadversary is 0.3963 compared to 0.94 leakage to \Wadversary. This is due to the fact that the strong adversary already has a lot of information about the data before receiving the outsourced file \outsource. We note that in a real-life scenario, the adversary is somewhere between the \Wadversary and the \Sadversary. Fig.~\ref{fig:uncertainty} shows the uncertainty metric for the same variables. This figure includes the uncertainty for $\bits =8$, where \Sadversary and \Wadversary are considered in two scenarios, where (a) the adversary has broken the PRNG, and (b) the adversary cannot break the PRNG in polynomial time. We choose $\bits = 8$ as a Byte-sized symbol is more practical in real-life scenarios. Fig.~\ref{fig:uncertainty} shows that even the strong adversary with a broken PRNG faces a large uncertainty to guess the real file \file. As an example, deleting 15 symbols or 15 Bytes of data leads to an average of $95.02$ Shannon bits of entropy for \Sadversary with negligible probability of breaking the PRNG, and $83.40$ bits of Shannon entropy for the said \Sadversary if it breaks the PRNG. These shanon bits of entropy when the \user performs as low as 9 deletions, are $61.11$ when the adversary can not break the PRNG, and $54.11$ when the PRNG is broken. As a standard in information-theoretic literature, 49 bits of entropy is considered secure against an adversary with the goal of identifying the original file~\cite{eastlake2005randomness}. We note that the assumption of breaking the PRNG is a very hard assumption for the adversary to fulfill (as it entails guessing the seed used by \user to create \outsource). Our results suggest that \name is still information-theoretically secure even when the output of the PRNG is known to the adversary. This is not surprising, as such information only leaks the deleted positions, but not the deleted values. \begin{figure}[!t] \centering \begin{tikzpicture} [scale=0.7] \begin{axis}[ xlabel= {$\sorg - \sbase [bytes]$}, ylabel=$Leakage(\leakage)$, xlabel style={font=\large}, ymin=0, grid=major, legend pos= south west] \addplot[mark = |, smooth, red, thick] plot coordinates { (1, .6673) (2, .6417) (3, .6226 (4, .6019 (5, .5867 (6, .5627 (7, .5439 (8, .5258) (9, .5073) (10, .4891) (11, .4696) (12, .4502) (13, .4317 (14, .4132 (15, .3963 (16, .3741 (17, .3553 (18, .3381) (19, .3097) (20, .2873) (21, .2638) (22, .2478) (23, .2339 (24, .2177 (25, .2091 }; \addlegendentry{$\bits=8$, \Sadversary} \addplot[mark=x, smooth,blue, thick] plot coordinates { (1, .8073) (2, .7817) (3, .7626 (4, .7419 (5, .7267 (6, .7027 (7, .6839 (8, .6558) (9, .6373) (10, .6191) (11, .5996) (12, .5602) (13, .5317 (14, .5132 (15, .4963 (16, .4741 (17, .4553 (18, .4381) (19, .4097) (20, .3677) (21, .3438) (22, .3277) (23, .3039 (24, .2877 (25, .2691 }; \addlegendentry{$\bits=4$, \Sadversary} \addplot[ domain = 1:25, thick ] {(256-x)/256}; \addlegendentry{$\bits=8$, \Wadversary} \addplot[ domain = 1:25, thick, green ] {(512-x)/512}; \addlegendentry{$\bits=4$, \Wadversary} \end{axis} \end{tikzpicture} \caption{Expected leakage for $\bits\cdot \sorg = 2048\, bits$ for HDFS dataset for different values of $\sbase$ when the PRNG has been broken. Expected value is calculated for 9999 chunks.} \label{fig:leakage1} \end{figure} \begin{figure}[!t] \centering \begin{tikzpicture} [scale=0.7] \begin{axis}[ xlabel= {$\sorg - \sbase [bytes]$}, ylabel=$Uncertainty(\unmetric)$, xlabel style={font=\large}, ymin=0, grid=major, legend pos= north west] % \addplot[mark = |, smooth, red, thick] plot coordinates { (1, 9.63) (2, 13.39) (3, 21.45 (4, 30.59 (5, 37.76 (6, 42.77 (7, 48.36 (8, 54.40) (9, 61.11) (10, 66.51) (11, 71.62) (12, 76.12) (13, 81.33 (14, 89.37 (15, 95.02 (16, 103.42 (17, 106.24 (18, 111.74) (19, 118.00) (20, 123.95) (21, 127.17) (22, 135.25) (23, 139.51 (24, 142.91 (25, 150.39 }; \addlegendentry{$\Sadversary$, PRNG} \addplot[mark=x, smooth,blue, thick] plot coordinates { (1, 6.39) (2, 12.13) (3, 18.58 (4, 26.95 (5, 32.47 (6, 37.63 (7, 43.69 (8, 47.23) (9, 54.11) (10, 59.45) (11, 66.27) (12, 71.04) (13, 76.33 (14, 79.37 (15, 83.40 (16, 88.31 (17, 92.42 (18, 97.74) (19, 105.01) (20, 113.59) (21, 117.97) (22, 120.83) (23, 125.53 (24, 129.26 (25, 131.59 }; \addlegendentry{$\Sadversary$, no PRNG} \addplot[mark= +, smooth ,black, thick] plot coordinates { (1, 15.99) (2, 30.98) (3, 45.38 (4, 59.36 (5, 67.69 (6, 77.12 (7, 86.93 (8, 94.03) (9, 101.74) (10, 106.54) (11, 116.27) (12, 126.04) (13, 133.36 (14, 139.73 (15, 150.20 (16, 153.38 (17, 162.42 (18, 171.47) (19, 180.50) (20, 189.53) (21, 197.71) (22, 205.83) (23, 213.95 (24, 222.19 (25, 230.59 }; \addlegendentry{$\Wadversary$, PRNG} \addplot[ domain = 1:25, thick, green ] {8*(x)}; \addlegendentry{$\Wadversary$, no PRNG} \end{axis} \end{tikzpicture} \caption{Expected uncertainty in the \cloud for $ \sorg = 256\, bits$ and $\bits = 8$ for HDFS dataset and different values of $\sbase$. Expected value is calculated for 9999 chunks.} \label{fig:uncertainty} \end{figure} Another interesting metric to analyse the privacy of \name is the probability of the original \file compared to other possible pre-images of \outsource. In order to assign a scientific understanding to this measure, we calculated the percentage of outsources, where the original file \file is among the highest probable \guess pre-images of the outsource \outsource. In other words, considering the case where the adversary generates all the possible pre-images of \outsource and sorts then based on their probability, assuming that the adversary can pick the first \guess chunks in this sorted list, what is the probability that the original file \file is among the selected pre-images? We conducted a Monte Carlo test using 9999 chunks that was created by a client of \name, where $\sorg = 256$ and $\bits=8$. Fig.~\ref{fig:guess} shows the percentage of outsources where the original file is among the highest probable \guess pre-images of the outsource based on probability of pre-images. For the case of \Sadversary breaking the PRNG (worst case), Fig.~\ref{fig:guess} shows that there is less than $50$~\% probability that the original file is among the top $2^{14}$ pre-images of the outsource \outsource. In fact, the strong adversary \Sadversary has to select the highest $2^{32}$ pre-images based on their probability to have at least 90\% probability of having the original file among the selected pre-images. From a practical perspective, selecting from a pool of 4 Billion pre-images for each chunk introduces a high degree of uncertainty for recovering any useful information (although clearly not as strong as cryptographic security). \begin{figure}[!t] \centering \begin{tikzpicture} [scale=0.7] \begin{axis}[ xlabel= {\guess}, ylabel={Outsources \%}, xlabel style={font=\large}, xtick = {2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40}, xticklabels = {$2^{2}$,,,$2^{8}$,,,$2^{14}$,,,$2^{20}$,,,$2^{26}$,,,$2^{32}$,,,$2^{38}$}, ymin=0, grid=major, legend pos= south east] % \addplot[mark = |, smooth, red, thick] plot coordinates { (2, 0) (4, 4.19) (6, 10.75 (8, 18.31 (10, 28.42 (12, 39.53 (14, 51.72 (16, 64.18) (18, 73.29) (20, 81.51) (22, 89.62) (24, 96.18) (26, 99.54 (28, 100 (30, 100 (32, 100 (34, 100 (36, 100) (38, 100) (40, 100) }; \addlegendentry{$\Sadversary$, PRNG} \addplot[mark=x, smooth,blue, thick] plot coordinates { (2, 0) (4, 1.81) (6, 7.53 (8, 14.71 (10, 24.12 (12, 35.91 (14, 47.62 (16, 58.14) (18, 69.11) (20, 78.82) (22, 86.20) (24, 93.32) (26, 96.41 (28, 98.28 (30, 99.17 (32, 100 (34, 100 (36, 100) (38, 100) (40, 100) }; \addlegendentry{$\Sadversary$, no PRNG} \addplot[mark= +, smooth ,black, thick] plot coordinates { (2, 0) (4, 0) (6, 0 (8, 4.18 (10, 9.32 (12, 16.62 (14, 25.18 (16, 36.21) (18, 47.52) (20, 59.96) (22, 71.82) (24, 81.66) (26, 89.52 (28, 95.31 (30, 97.26 (32, 98.90 (34, 99.42 (36, 99.78) (38, 99.99) (40, 100) }; \addlegendentry{$\Wadversary$, PRNG} \addplot[mark= o, smooth ,green, thick] plot coordinates { (2, 0) (4, 0) (6, 0 (8, 0 (10, 2.51 (12, 6.62 (14, 12.53 (16, 21.82) (18, 33.15) (20, 48.28) (22, 60.06) (24, 72.41) (26, 81.21 (28, 86.73 (30, 90.15 (32, 93.59 (34, 95.71 (36, 97.72) (38, 98.53) (40, 99.58) }; \addlegendentry{$\Wadversary$, no PRNG} % \end{axis} \end{tikzpicture} \caption{Percentage of chunks that \file is among the top \guess pre-iamges of \outsource with highest probability. This values are calculated by a monte-carlo test using 9999 chunks, for $\sorg=256$ and $\bits=8$.} \label{fig:guess} \end{figure} \section{Performance Analysis}\label{sec:analysis} In the following, we analyze the compression rate achieved by \name, the transformation cost in both \users and \cloud, and discuss the privacy achieved by \system. Unless stated otherwise, we use $\log(x)$ as the logarithm in base $2$ of $x$. \vspace{-5pt} \subsection{Client Compression Ratio} \label{SS:CCR} We begin our analysis with studying the compression ratio on the client side, i.e., \ucr in Eq.~\eqref{eq:ucr}. For each file \file, the user stores the respective \local and \id. To compute \ucr for one file \file, we accurately measure the size of \local. As the \user uses a PRNG to identify the position of the deleted elements, the required size to store the positions is equal to the size of the PRNG seed. we denote this size by \sseed. The \user performs $\nodel = \sorg - \sbase$ subsequent \deletions on \file, where the \user stores the value of all deleted symbols in \local. Thus, \local contains a total of $\nodel\cdot \bits$ bits to store the value of the deleted symbols. \local also contains 1 bit, indicating whether the \invert transformation has been applied to \outsource. Therefore, the required storage needed in \user is equal to: \begin{equation*} \size(\user_{i}, \file) = \sseed + \nodel\cdot \bits + \sizefid + 1, \end{equation*} where $\sizefid$ is the size in bits of a file identifier If the database for the client $i$, i.e., $\database_{i}$ has \nof files, the required storage on the \user side is: \begin{equation*} \size(\user_{i}, \database_{i}) = \nof\cdot (\sseed + \nodel\cdot \bits + \sizefid + 1). \end{equation*} The original size required for $\database_{i}$ prior to the transformations of \name is: \begin{equation*} |\database_{i}| = \nof\cdot \bits\cdot n_{o}. \end{equation*} Thus, \begin{equation} \ucr = \frac{\size(\user_{i}, \database_{i})}{|\database_{i}|} = \frac{\sseed + \nodel\cdot \bits + \sizefid + 1}{\bits\cdot \sorg}. \label{eq:ygg_ucr} \end{equation} \subsection{Cloud Compression Ratio} The compression rate on the \cloud, i.e., \ccr, according to Eq.~\eqref{eq:ccr}, considering the different contributing effects. As described is Section~\ref{sec:contribution}, the cloud stores three strings \Addendum, \Change, and \ChangedValues for each received \outsource, as well as the identifier \id and a pointer to the base \base. The bases are stored in \baseset, where we denote the size of \baseset as the size of the forest \sizeforest used to represent all stored bases Note that $\sizeforest < \sbase\cdot |\baseset|$, as the forest structure removes the redundancy between different bases in \baseset. Thus, the total storage in the cloud is equal to the cost of storing \Addendum, \Change, \ChangedValues, the \id and a pointer to the respective \base for each received \outsource plus the required storage for the \baseset. Our experiments show that \sizeforest is very small compared to the size of the data as the \cloud is able to perform deduplication on a large number of bases. The expected size of the \Addendum is equal to the expected length of Huffman Coding, which is equal to the entropy of the data in the \cloud, i.e., $H(\cloud)$. The size of \Change is dependent on the number of swaps needed to sort the base \base. For each \swap, the cloud needs to store 1 position for the position of the swapped elements, and each position requires $\log\sbase$ space. \Change also includes a bitmap of symbols, which has the size of \sorg bits. Therefore, the \cloud requires $\sorg + \nswap \cdot \log\sbase$ storage for \Change, where \nswap is the number of swaps required to sort \sepResult. The number of swaps \nswap is heavily dependant on the structure of the data and the way the files are chunked from the database \database. In \ChangedValues the \cloud stores the Huffman representation of the zones, so the size of this string is also dependent on the structure and the probability distribution of the data. In worst case, the size of \Vid for each symbol is exactly 2 bits, leading to $2\sorg$ required storage for \ChangedValues. In the following analysis, we use this value. In practice, the \cloud uses Huffmann codes to determine the size of \Vid, so the size of \Vid for most probable symbols is usually 1 bit, leading to lower rquired storage for use cases. For each \outsource, we have: \begin{equation*} \begin{split} E(\size(\cloud, \file)) = & H(\clouddistribution) + 3\sorg + \nswap\cdot\log\sbase +\\ & \sizefid + \sizep, \end{split} \end{equation*} where \sizep is the size of the pointer or identifier to the \base in \baseset. Thus, the total compression rate on the cloud is \begin{equation} \footnotesize \ccr = \frac{\sizeforest + \nof(H(\clouddistribution) + 3\sorg + \nswap\cdot\log\sbase + \sizefid + \sizep)}{\nof\cdot\bits\cdot\sorg}. \label{eq:ygg_ccr2} \end{equation} \subsection{Global Compression Ratio} The required storage size in \user side does not change and can be calculated as \size(\user, $\database_{i}$) in section~\ref{SS:CCR}. Therefore, the global compression ratio of the system is given by the sum of the \user compression ratio and the \cloud one \begin{equation} \footnotesize \compratio = \frac{\sizeforest + \nof(\cons + H(\clouddistribution) + \nodel\cdot \bits + 3\sorg + \nswap\cdot\log\sbase)}{\nof\cdot k\cdot \sorg}, \label{eq:C1} \end{equation} where \cons is a constant number, denoting the size of the pointers and the random seed of the PRNG, and is equal to $\cons = \sseed + \sizep + 2\sizefid + 1$. \subsection{Transformation Costs} In this section, we calculate the computation cost of the algorithms discussed in Section~\ref{sec:contribution} in \cloud and \user. We provide two theorems for the computational cost of operations in \cloud and \user. \begin{theorem} The computational cost of the procedures applied in the \user during \upload is $O(\test\cdot \sorg)$. \end{theorem} \begin{IEEEproof} The \user performs \deletions for each file prior to upload, which is in the \upload procedure. The \user performs two set of instructions in \upload. First, performing \deletions for each file and PRNG seed. Second, calculating the probability distribution of the generated \outsource to choose the one that adheres the best with the distribution \clouddistribution provided in the \policy. Using a vector data structure for file \file, results in linear complexity for deletion of $\sorg-\sbase$ elements in the size of the \file, i.e., $O(\sorg)$. This can be performed by copying elements not scheduled for deletion to a different vector of size $\sbase$, skipping the copy of deleted elements. Since the procedure is performed $\test$ times for \test different seeds, the total complexity of this instruction is $O(\test\cdot \sorg)$. For each generated \outsource and its inverted \outsource, the \user must calculate the probability distribution. Calculating the probability distribution requires reading all the symbols, i.e., $O(\sorg)$ operations. As we have $2\cdot\test$ possible \outsource to evaluate, this instruction has compelxity $O(\test\cdot \sorg)$. Thus, the complexity at the \user is $O(\test\cdot \sorg)$. \end{IEEEproof} \begin{theorem} The computational cost of procedure in the \cloud after receiving an \outsource form a \user during \dedup is equal to $O(\sbase(\log\sbase+\alphabetSize))$ when using MergeSort for the Sorting phase. \end{theorem} \begin{IEEEproof} The cloud performs three sets of transformations on the received \outsource, namely \changev, \sep and \sort. Therefore, in order to calculate the time complexity at the \cloud after receiving an \outsource, we calculate the time complexity of these transformations. In \changev, the \cloud needs to (1) find the symbols in the Brackets table and (2)change the value of the symbol and insert the new value, as well as \Vid in the two output strings \chnvResult and \ChangedValues. The most efficient way to perform this transformation is to search for each symbol in the outsource \outsource instead of searching for each symbol in the table. Searching for a symbol has a time complexity of $O(\sorg)$. As the \cloud has to search for $\alphabetSize$ symbols in total, this step has complexity $O(\sorg\cdot\alphabetSize)$. As we use vector data structure, the \cloud can create the two output strings in linear time, i.e., $O(\sbase)$. Therefore, the total time complexity of \changev is equal to $O(\sbase\cdot\alphabetSize)$. During \sep, the cloud creates 2 strings \Addendum and \sepResult from \chnvResult. For each symbol, the \cloud needs to find the respective value of \Sid and \Bid from the Brackets Table. This process requires a brute-force search, and therefore has a time complexity of $O(\alphabetSize)$. Populating both strings is done in linear time complexity after finding the \Sid and \Bid of each symbol. Thus, the total time complexity of this step is equal to $O(\sbase\cdot \alphabetSize)$. The computational cost of the transformations applied in the \cloud during \sort depends on the sorting algorithm that is used. In this work, we use Mergesort in order to sort the \sepResult, which has a time complexity of $O(\sbase\log\sbase)$. Then, the \cloud finds the swaps required using a linear comparison between the sorted base \base and \sepResult. As this algorithm is linear, it has a time complexity of $O(\sbase)$. Therefore, in total, the time complexity of \sort is equal to $O(\sbase\log\sbase)$. Combining these three time complexities gives the final time complexity of the \dedup procedure. \end{IEEEproof} \begin{theorem} The computational cost of the transformations applied during the client in \get is $O(\sorg)$. \end{theorem} \begin{IEEEproof} The \user needs to insert the deleted values in \local into their respective positions in the \outsource. This is linear in cost with the size of $\sorg$. \end{IEEEproof} \begin{theorem} The computational cost of the transformations applied during the client in \decompress is $O(\nob + \sbase\cdot\alphabetSize)$. \end{theorem} \begin{IEEEproof} The cloud performs \decompress in four steps. First, retrieving the \base from \baseset. Second, undoing the \swap transformations. Third, recreating the symbols from their respective \Bid and \Sid. Lastly, restoring the changed values. Retrieving the base from \baseset requires a search on the received \id. Although the bases are stored in a structured way, there is no guarantee that the \id is stored in the same way. Therefore, searching for a \id requires linear time dependent on the number of bases in the baseset, i.e., $O(\nob)$. After retrieving the \base, the \cloud needs to reverse the swaps stored in \Change to retrieve \sepResult by first identifying the required swaps. This is done by a read through \Change, that has linear complexity, i.e., $O(\sbase)$. Then, the cloud performs the swaps. In the worst case,the number of swaps is linear to the size of the \base, i.e., $O(\sbase)$. Restoring the \outsource from \sepResult requires replacing each triple of \Sid, \Bid and \Vid with its respective symbol. Therefore, for each symbol in \sepResult, the \cloud needs to scan through the Brackets table to find the value associated with the triple. In the worst case scenario, the \cloud needs to scan through the whole table for each symbol, leading to a time complexity of $O(\alphabetSize)$ for each symbol. Therefore, in worst case, the time complexity of this action is equal to $O(\sbase\cdot\alphabetSize)$. Combining these three time complexities concludes the proof. \end{IEEEproof} \subsection{Privacy Analysis}\label{sec:security_proofs} In the following, we calculate \bonsai's leakage \leakage and uncertainty \unmetric for an honest-but-curious \cloud. In detail, we consider \Wadversary and \Sadversary as introduced in Section \ref{sec:sec_model}, and for each adversary type, we investigate two scenarios. First, the adversary has negligible probability of breaking the PRNG. Second, the adversary breaks the PRNG. \subsubsection{Weak Adversary} Recall that \Wadversary has no information about the distribution of original files. This means that in its perspective, all possible values of $\file$ have the same probability of being the \user's data. Therefore, $H(\file) = \bits\cdot \sorg$. In scenario 1, the PRNG behaves like a truly random function in \Wadversary's view, and therefore it leaks no information about the position of the deleted elements. Given $F^{\prime}$, the original string \file can be any of the possible strings that generate $F^{\prime}$. As \Wadversary does not have any extra information, each potential \file has the same probability of being the original string, so $H(\file|\outsource) = log(\nopreim)$, where \nopreim is the number of possible pre-images of \outsource. as it has been shown in~\cite{yggdrasil}, we have: \begin{equation*} \nopreim = \sum_{j=0}^{\sorg-\sbase} {\sorg \choose j+\sbase} (2^{\bits}-1)^{\sorg-\sbase-j}. \end{equation*} Therefore, the leakage for \Wadversary is \begin{equation*} \leakage(F^{\prime}) = \frac{\bits\cdot \sorg - \log(\nopreim)}{\bits\cdot \sorg}, \end{equation*} and the uncertainty \unmetric that the \Wadversary faces after receiving \outsource is \begin{equation*} \unmetric = \log(\nopreim). \end{equation*} In scenario 2, \Wadversary breaks the PRNG, this means that it gains knowledge about the position of the deleted symbols. Therefore, the total number of possible pre-images of the \outsource, \nopreim has a different value. However, the adversary still cannot distinguish between the different possible pre-images, as in the adversary's viewpoint, all possible pre-images has the same probability of being the original data. In order to generate a possible pre-image, the adversary can insert a symbol in the positions that the deletions has occurred. As there are $\sorg-\sbase$ positions and each position has $2^{\bits}$ possible values as the symbol, the number of pre-images of the \outsource is equal to: \begin{equation*} \nopreim = 2^{\bits(\sorg-\sbase)}. \end{equation*} The rest of the analysis is the same as the previous case, therefore, if the \Wadversary breaks the PRNG, we have the following value of leakage after receiving the \outsource: \begin{equation*} \leakage(F^{\prime}) = \frac{k\cdot \sorg - \log(m)}{k\cdot \sorg} = \frac{\sbase}{\sorg}. \end{equation*} The Uncertainty for the attacker in this case is equal to: \begin{equation*} \unmetric = \log(\nopreim) = \bits(\sorg-\sbase). \end{equation*} \subsubsection{Strong Adversary} Recall that \Sadversary has knowledge about the probability distribution of symbols in the client. We further assume here that the adversary has a negligible probability of breaking the PRNG, i.e., has no information about the position of the deleted symbols. In this case, $H(\file) \neq \bits\cdot \sorg$. When the cloud receives \outsource, the original string \file can be any of the possible strings that generate \outsource. The cloud can generate all possible values of \file. The probability that a given \singlefile is the actual data of the \user is higher if 1.\singlefile has higher probability based on \distribution and 2.\singlesource can be generated by \singlefile with various deletions. We define $W(\file = \singlefile|\outsource = \singlesource)$ is the number of ways that \outsource can be generated from \file, i.e., number of distinct occurrences of \singlesource in \singlefile as a subsequence. This value is calculated using a recursive algorithm and dynamic programming. Using this variable, the probability of each \file in cloud's perspective is equal to: \begin{equation*} P(\file = \singlefile|\outsource=\singlesource) = \frac{W(\file = \singlefile|\outsource = \singlesource) P(\file = \singlefile)} {\sum\limits_{\singlefile}W(\file = \singlefile|\outsource = \singlesource)P(\file = \singlefile)}. \end{equation*} Using the value of $P(\file = \singlefile|\outsource=\singlesource)$, we calculate the value for $H(\file|\outsource)$ which is equal to the uncertainty of the \Sadversary after it receives \outsource. The leakage of information to \Sadversary is calculated using the value of \unmetric and Eq.~\eqref{eq:leakage}. If the adversary breaks the PRNG, this analysis still holds, and we need to calculate the value of $P(\file = \singlefile|\outsource=\singlesource)$ for each possible pre-image. However, the difference between the two cases is the more information that the adversary possesses if it breaks the PRNG means that the number of possible pre-images is lower, therefore, after receiving the \outsource, on average more information is leaked to the \cloud. The uncertainty provided against a strong adversary is upper bounded by the uncertainty of the weak adversary, i.e., $k(\sorg-\sbase)$. This fact is useful to argue for privacy against a real adversary, which lies somewhere between the weak and strong adversaries. In Section~\ref{sec:experiments} we calculate the values of leakage and uncertainty against weak and strong adversaries and discuss the implications of it in real life scenarios. \section{Related Work}\label{sec:RelWork} Data deduplication is a powerful way to reduce the storage footprint of highly correlated data \cite{Jin2009,meyer2012study}. Delta deduplication falls into the category of redundant data reduction techniques, which also include Delta Compression techniques such as Xdelta~\cite{macdonald2000file}. The big difference between the two methods is the facts that Delta encoding techniques use copy/insert instructions to record the ``difference'' between two files on string-level, while the data Deduplication techniques remove the ``redundancy'' between files, either on file-level~\cite{bolosky2000single} or chunk-level~\cite{quinlan2002venti}. The theoretical bounds of deduplication and generalized deduplication are discussed extensively in \cite{niesen2019information, Vestergaard2019a, lou2020data}. Implementations of generalized deduplication have been proposed for file systems~\cite{MinervaFS} and CSPs~\cite{Alexandria}. The introduction of deduplication in the early 2000s sparked many research directions aiming at improving or enhancing the compression method. Problems and proposed solutions can summarized into three major categories. \begin{itemize} \item \textbf{Increasing performance and throughput:} This line of research includes, but is not limited to optimization of deduplication~\cite{zhang2020secdedup}, acceleration of computational tasks~\cite{ren2021accelerating}, reduction of the access time to metadata~\cite{zhu2008avoiding}, and improvements of the chunking procedure based on the content~\cite{yu2015leap, zhou2013hysteresis}. \item \textbf{Reducing the storage requirement:} These solutions focus on reducing the fingerprint of the data. Some of the major research outputs in this category deal with reducing the overhead of the metadata~\cite{li2019metadedup}, improving the efficiency of deduplication in the cloud and reducing the size of fingerprints~\cite{bhagwat2009extreme}, and reducing the overhead of the data by establishing a communication between the cloud and the clients \cite{vestergaard2020cider, pooranian2018rare, yu2018privacy}. \item \textbf{Improving the privacy and security of the clients' data:} Privacy issues arise in Data Deduplication as all the data from the clients are deduplicated together, leaving the storage system vulnerable to leaking the information of the data. As this category is the closest line of research to the solution proposed in this paper, we take a closer look at this category. \end{itemize} For privacy-aware data owners (clients), the CSP should be able to provide storage solutions without needing access to the content of their data. If conventional encryption is used to protect clients' data, the compression potential on the cloud severely worsens~\cite{akhila2016study}. As an alternative, Message Leaked Encryption (MLE)~\cite{douceur2002reclaiming} has been proposed, which allows one to encrypt data securely, while preserving the deduplication potential. The most widely used MLE technique in deduplication techniques is called Convergence Encryption (CE)~\cite{whiting1998system}. However, CE has been shown to be exploitable by brute-force~\cite{almrezeq2021enhanced}, and is vulnerable to frequency attacks~\cite{li2020information}. The proposed adjustments to improve CE, such as DUPLESS~\cite{keelveedhi2013dupless}, and Duan's scheme~\cite{duan2014distributed}, require a trusted cloud or a third-party dealer to ensure the privacy of the data. Alternative approaches rely on the Blockchain technology~\cite{zhang2019blockchain}, on gateways~\cite{leontiadis2018secure}, sacrifice computational efficiency~\cite{zhao2017updatable}, or generate large overhead for the clients~\cite{liu2015secure}. More recently, Multi-Key Revealing Encryption~\cite{lucani2020secure} has been proposed to ensure privacy of the clients' data while maintaining deduplication capabilities. This solution uses programmable random oracles which are not instantiatable in practice. There have been surveys that describe the privacy solutions in more depth~\cite{zhang2020secure,shin2017survey}. We also note that~\cite{xia2016comprehensive} provides a general survey on deduplication with a comprehensive study of the state-of-the-art. \section{Conclusion}\label{sec:conclusion} This paper proposes \name, a privacy-aware dual deduplication system that preserve the privacy of \user's data while achieving attractive compression for cloud storage providers. Similarly to Yggrasil \cite{yggdrasil}, Bonsai's privacy relies on deletions of symbols from the original data; however, Bonsai achieves significantly better compression rates on the client side by replacing random deletion with deletion on locations indicated by a PRNG. This behavior mimics a deletion channel. We implement a filtering method using multiple seeds of a PRNG function to ensure that the generated base can be deduplicated in the cloud with higher probability. To improve its compression capabilities and enable efficient search, the \cloud in \bonsai periodically generates a \policy, which tells to the \users the expected probability distribution of symbols in the outsourced data. The \user uses the \policy to generate deduplication-friendly data to outsource to the \cloud. Bonsai implements an innovative mapping function in the \cloud combined with a forest data structure in order to efficiently find and deduplicate incoming data. Our experiments show that \bonsai achieves significant compression rates compared to state-of-the-art (generalized) deduplication approaches. In addition, \bonsai protects the confidentiality of \users' data thanks to a deletion-channel-like approach. We argue the proposed approach provides good privacy guarantees: our analysis shows that an attacker faces a high degree of uncertainty when trying to reconstruct \users' original data from what is outsourced. In real-life scenarios, The strongest possible adversary faces an average 83.40 Shannon bits of entropy while trying to guess the original data, even if the adversary has full knowledge about the characteristics and statistics of the original data source. We further show that there is only 50\% chance that the adversary can guess the correct original data from the received outsourced data, by checking $2^{15}$ possible strings for each chunk of data. Even if the adversary has the possbility to check $2^{32}$ possible strings, The chance of guessing the correct file for each chunk is still less than 90\%. Future work will study additional mechanisms for Bonsai to improve compression, e.g., using more compact representations for the sorting step, improve privacy, e.g., combine random deletions with value changes or insertions at the \user side, and efficient secure sharing mechanisms with third parties. \section{System Model and Performance Metrics}\label{sec:model} In this section, we describe our system model, the type of data handled by the system, the attacker model and, finally, the performance metrics used to evaluate \name. \subsection{System Model} We adopt the dual deduplication system introduced in \cite{yggdrasil}. Concretely, our system \system consists of a number of independent users, referred to as \users, and a single CSP, referred to as \cloud. The \users' goal is to maximize the data they outsource to the \cloud\ while retaining some level of privacy on each record; the \cloud's goal is to minimize the space required to store the \users' outsourced data. The system \system allows the \users to locally process their data, by applying a transformation \transformation on their data before upload and storing the information about the transformations locally. Note that the \cloud has no access to the information stored locally by any \user. This fact is crucial to argue the privacy of \name. Finally, we assume that the communication channel between the \users and \cloud is authenticated and error-free. \subsection{Data Type} The data handled by \cloud and \users in \system are files \file represented as strings of \sorg symbols, where each symbol is a value consisting of \bits bits. i.e., our alphabet is $\alphabet=\{0,1\}^\bits$ and files are $\file\in \alphabet^{\sorg}=\{0,1\}^{\bits \cdot \sorg}$. We denote the size of the alphabet as $\alphabetSize = |\alphabet| = 2^{k}-1$. Recall that each \user performs some transformations \transformation on their files \file prior to upload. In what follows, we denote the output of \transformation as an outsource-local pair $(\outsource, \local)\gets\transformation(\file)$, where \outsource, called outsource is the data outsourced to the \cloud; and \local is the secret piece of information stored locally by \user. We call this secret information client-side deviation. Note that both outsource and client-side deviation are strictly shorter than the original file; namely the length of outsource $|\outsource| = \sbase < \sorg$ and the length of the client-side deviation $|\local| < \sorg$. \subsection{Attacker Model}\label{sec:sec_model} Our adversary \adversary is a honest-but-curious \cloud. Concretely, \adversary has access to the whole data stored in the \cloud, i.e., any record \outsource ever outsourced by any \user. The goal of the adversary is to breach \user's privacy by retrieving their original data \file. i.e., to identify the complete string \file\ from which the \user derived the outsource \outsource. We recall that \adversary has no access to the client-side deviation \local\ stored by the \user locally. In this work we consider two types of adversaries: $\bullet$ A \emph{weak} adversary, \Wadversary, does not have any information on the distribution of clients' original data \file. This weak adversary emulates settings where clients upload unpredictable data, e.g., very diverse types of files, or uncorrelated information. $\bullet$ A \emph{strong} adversary, \Sadversary, knows the distribution \distribution of the original files, i.e., the probability distribution with which a specific string \file is produced by a \user. Notably, \Sadversary has knowledge of the correlation between the symbols in \file. As expected, the strong adversary is more realistic than the weak one. While it is reasonable to assume that in real systems the CSP may have some information about the files generated by the clients; knowing the exact probability distribution for any possible file \file is a requirement hard to meet. Hence, we believe a real-world attacker lies somewhere in-between the two types of adversaries we consider. Our protocol, \bonsai, makes minimal use of cryptographic tools. Namely, the only cryptographic primitive required is a PRNG (Pseudo-Random Number Generator) function, run by the \users within the \transformation process. All other transformations employed in \bonsai are information theoretic. To further strengthen our security outcomes, for each type of adversary, we consider two potential scenarios: $\bullet$ \emph{Case 1}: \adversary has negligible probability of breaking the PRNG (this correspond to a classical adversary that is computationally bounded and runs in probabilistic polynomial time). $\bullet$ \emph{Case 2}: \adversary can break the PRNG (this corresponds to quantum adversary that is computationally unbounded and equipped with a quantum computer, or an adversary that knows the seed input to the PRNG). \noindent We remark that, in \bonsai the PRNG is employed to provide better compression on the \user side. Therefore, it is possible to obtain a complete information theoretic secure version of protocol by replacing the use of the PRNG with a truly random function, though this impacts negatively the performance of the system by reducing the compression potential on the \cloud. Finally we argue that assuming \adversary is not fully malicious is needed to guarantee the correctness of the overall system. For example, if the \cloud tampers with outsourced items, \users may reconstruct incorrect data and the service loses reliability. We consider that in the specific setting of outsourced storage, an honest-but-curious attacker is more realistic than a malicious one. For this reason, we leave the analysis of the implications of having a malicious \cloud or a malicious \user as future work. \subsection{Compression Ratios} The main goal of \name is to reduce the fingerprint of the data via dual deduplication (i.e., compressing data on both the \user and the \cloud sides). Therefore, it is natural to define performance metrics that measure the compression ratio of the system by looking at the \user, the \cloud, and the overall system perspective. We employ the performance metrics introduced by Yggdrasil, the state-of-the-art work on dual deduplication \cite{yggdrasil}. In what follows, \database denotes the set of all the data of all the \users ; and $\database_{i}$ denotes the set of the data of a single \user $i$. Both \database and $\database_{i}$ contain a number of files \file. We assume that our system \system has a total of \userCount \users, which are enumerated in a set $\userSet =\{ \user_{1}, ...., \user_{\userCount} \}$. In order to formally define the compression rate of \name in different parties (\user and \cloud), we use a function size(party, D), which we define as follows. \begin{description} \item[size(\sf{party}, D):] On the input of $\sf{party}\in \{\cloud,\user\}$ and some data D, this function outputs the total number of bits required to store D in the given party. \end{description} Equipped with this notation we can define the \user Compression ratio as : \begin{equation}\label{eq:ucr} \ucr = \frac{\size(\user_{i}, \database_{i})}{|\database_{i}|}, \end{equation} where $|\database_{i}|$ denotes the total size of the data in the posession of $\user_{i}$. As the \cloud stores data from all the clients, we calculate the total compression rate of the \cloud with respect to \database, therefore, the \cloud compression rate is defined as: \begin{equation}\label{eq:ccr} \ccr = \frac{\size(\cloud, \database)}{|\database|}. \end{equation} Another interesting compression metric is the total compression rate, which indicates the total storage required by all the parties (\users and the \cloud) to store the whole database \database compared to the size of the original \database. This metric allows us to compare the performance of \name with other compression methods that only store the data on the \cloud. Intuitively, the total required storage in \name is equal to the summation of the required storage in all \users and the required storage on the \cloud, therefore, the total compression rate is: \begin{equation}\label{eq:gcr} \footnotesize \compratio = \frac{\size(\cloud, \database)+\sum\limits_{i=1}^{\userCount}\size(\user, \database_{i})}{|\database|}. \end{equation} \subsection{Privacy Metrics} We estimate the privacy level of a dual deduplication system \system in terms of the uncertainty metric \unmetric and the leakage \leakage. The uncertainty metric shows the amount of unpredictability that an adversary \adversary faces when it attempts to guess the value of a given record \file, having seen only its outsourced version \outsource. We acknowledge that the adversary may have some knowledge about the file \file prior to receiving the \outsource, therefore, after receiving the \outsource, the uncertainty of the adversary drops as it gains more information about the file \file. The leakage \leakage measures this drop in the uncertainty of the adversary \adversary after receiving \outsource, i.e., the amount of information about \file leaked to \adversary after receiving \outsource. We use the notation of Shannon's entropy \cite{cover1999elements} to calculate the uncertainty metric and leakage for our adversaries. We assume that \adversary uses its knowledge to generate the list of all possible preimages $\Pset\gets\adversary(\distribution, \file')$ of a given base \outsource. It is clear that the original file belongs in this list, $\file\in\Pset$. Then the adversary tries to predict the real value of \file using the preimages in \Pset and the probability that each one of them is the real \file. The uncertainty that the attacker faces to guess the original file \file is equal to the entropy of the set \Pset. Therefore, we define uncertainty metric as follows. \begin{description} \item[Uncertainty Metric:] \begin{equation}\label{eq:uncertainty} \unmetric(\file) = H(\file|\outsource), \end{equation} \end{description} where $H(\file|\outsource)$ is the Shannon's entropy of \file given \outsource. Based on our definition, the uncertainty prior to receiving \outsource is equal to $H(\file)$. Therefore, the leakage of information that occurs when sending \outsource is calculated as follows. \begin{description} \item[Leakage:] \begin{equation}\label{eq:leakage} \leakage = \frac{H(\file) - H(\file|\outsource)}{H(\file)}. \end{equation} \end{description} Note that the Shannon's entropy of file, i.e., $H(F)$ is calculated in the viewpoint of the adversary. This means that if we consider the weak adversary, the value for $H(F)$ is equal to the Shannon's entropy for a uniformly random probability distribution and not the actual value of the Shannon's entropy based on the statistical properties of the database \database.
{'timestamp': '2022-03-30T02:38:03', 'yymm': '2202', 'arxiv_id': '2202.13925', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13925'}
arxiv
\section{Introduction} Introduced in \cite{jacobsME}, a mixtures of experts (ME) model can be defined as \begin{equation} \label{eq: FME general} \textstyle f(y|x) = \sum_{k=1}^K \text{Gate}_k(x)\,\text{Expert}_k(y|x), \end{equation} in which $f(y|x)$, the distribution of the response $y$ given the covariate $x$, is modeled as a mixture distribution with covariate-dependent mixing proportions $\text{Gate}_k(x)$, referred to as gating functions, and conditional mixture components $\text{Expert}_k(y|x)$, referred to as experts functions, $K$ being the number of experts. Some ME studies that may be mentioned here include ME for time series prediction \citep{ZeeviTS1996, Yml2003FinancialTS}, segmentation \citep{Chamroukhi-MRHLP-2013, chamroukhi_et_al_NN2009}, ME for classification of gender and pose of human faces \citep{Gutta2000MixtureOE}, for social network data \citep{Gormley2010AMO}, among others. For an overview of practical and theoretical aspects of ME modeling, the reader is referred to \cite{NguyenChamroukhi-MoE}. The study of ME for functional data analysis (FDA) \citep{RamsayAndSilvermanFDA2005}, is still however less investigated. In a recent study, we introduced in \cite{chamroukhi2022fME} a functional ME (FME) framework for regression and clustering of observed pairs of scalar responses and univariate functional inputs. \vspace{-.6cm} \section{Functional Mixture-of-Experts for classification} In this paper, we extend the FME framework for multiclass classification, derive adapted EM-like algorithms to obtain sparse and interpretable fit of the gating and experts network coefficients functions. Let $\{X_i(t), t \in \mathcal{T}; Y_i\}_{i=1}^n$, be a sample of $n$ i.i.d. data pairs where $Y_i\in \{1,\ldots,G\}$ is the class label of a functional predictor $X_{i}(\cdot)$, $G$ being the number of classes. In this case of functional inputs, a natural choice to model the conditional distribution $\text{Expert}_k(y|x) = \mathbb{P}(Y=y|X_{i}(\cdot))$ in \eqref{eq: FME general} is to use the functional multinomial logistic regression modeling, see e.g., \cite{muller2005GFLM,James2002}, that is { \begin{eqnarray} \label{eq: FME expert} P(y_i|X_i(\cdot);\boldsymbol{\beta}_k) = \prod_{g=1}^G \left[\frac{\exp\left\{\beta_{kg,0} + \int_{\mathcal{T}}X_i(t)\beta_{kg}(t)dt\right\}} {1+\sum_{g^\prime=1}^{G-1}\exp\left\{\beta_{kg^\prime,0} + \int_{\mathcal{T}}X_i(t)\beta_{kg^\prime}(t)dt\right\}}\right]^{y_{ig}}, \end{eqnarray}}whre $\boldsymbol{\beta}_k$ represents the set of coefficient functions $\{\beta_{kg}(t), t \in \mathcal{T}\}$ and intercepts $\{\beta_{k,0}\}$ for $k\in[K]=\{1,\ldots,K\}$ and $g\in[G]$, and $y_{ig}=\mathbb I_{\{y_i=g\}}$. Similarly, a typical choice for the functional gating network $\text{Gate}_k(x) = \mathbb{P}(Z = k, X(\cdot))$ in \eqref{eq: FME general}, where $Z\in[K]$ is a hidden within-class clustering label, acting as weights for potential clusters $\{k\}$ in the heterogeneous functional inputs $X(\cdot)$ and which we denote as $\pi_{k}(X(\cdot))$, is to use a functional softmax function defined by {\begin{eqnarray}\label{eq: FME gating} \pi_{k}(X_i(\cdot);\boldsymbol{\alpha}) =\frac{\exp\{\alpha_{k,0} + \int_{\mathcal{T}}X_i(t)\alpha_k(t)dt\}}{1+\sum_{k^\prime=1}^{K-1}\exp\{\alpha_{k^\prime,0} + \int_{\mathcal{T}}X_i(t)\alpha_{k^\prime}(t)dt\}}, \end{eqnarray}}with $\boldsymbol{\alpha}$ is composed of the set of coefficient functions $\{\alpha_{k}(t), t \in \mathcal{T}\}$ and intercepts $\{\alpha_{k,0}\}$ for $k\in[K]$. Then, from \eqref{eq: FME expert} and \eqref{eq: FME gating} given $X_i(\cdot)$, the probability that $Y_i=y_i$, can be modeled by the following $K$-component FME model for classification { \begin{equation}\label{eq: FMEMR distribution} P(y_i|X_i(\cdot);\boldsymbol{\psi}) = \sum_{k=1}^{K} \pi_{k}(X_i(\cdot);\boldsymbol{\alpha}) P(y_i|X_i(\cdot);\boldsymbol{\beta}_k), \quad \boldsymbol{\psi}=(\boldsymbol{\alpha},\boldsymbol{\beta}_1,\ldots,\boldsymbol{\beta}_K). \end{equation} \vspace{-.5cm} \subsection{Smooth functional representation} In practice, $X_i(\cdot)$ is observed at a finite but large number of points on $\mathcal{T}\subset \mathbb{R}$. In the perspective of parameter estimation, this results in estimating a very large number of coefficients $\beta$ and $\alpha$. In order to handle this high-dimensional problem, we consider a usual approach that projects the predictors and coefficient functions onto a family of reduced number of basis functions. Let $\boldsymbol{b}_r(t) = \left[b_1(t), \ldots, b_r(t)\right]^\top$ be a $r$-dimensional basis (B-spline, Wavelet, ...). Then, with $r,p,q\in\mathbb N$ sufficiently large, one can approximate $X_i(\cdot)$, $\alpha_k(\cdot)$ and $\beta_{kg}(\cdot)$ respectively by { \begin{equation} X_i(t) = \boldsymbol{x}_i^\top \boldsymbol{b}_r(t), \quad \alpha_k(t) = \boldsymbol{\zeta}_k^\top \boldsymbol{b}_p(t), \quad \beta_{kg}(t) = \boldsymbol{\eta}_{kg}^\top \boldsymbol{b}_q(t). \label{eq: projections} \end{equation}}Here, $\boldsymbol{x}_i = ( x_{i1}, \ldots, x_{ir})^\top$, with $x_{ij} = \int_{\mathcal{T}} X_i(t)b_j(t)dt$ for $j\in[r]$, is the vector of coefficients of $X_i(\cdot)$ in the basis $\boldsymbol{b}_r(t)$, $\boldsymbol{\zeta}_k=(\zeta_{k,1},\ldots,\zeta_{k,p})^\top$, and $\boldsymbol{\eta}_{kg}=(\eta_{kg,1},\ldots,\eta_{kg,q})^\top$ are the unknown coefficient vectors associated with the gating coefficient function $\alpha_k(\cdot)$ and the expert coefficient function $\beta_{kg}(\cdot)$ in the corresponding basis. In our case, we used B-spline bases. % Using the approximation of $X_i(\cdot)$ and $\alpha_k(\cdot)$ in \eqref{eq: projections}, the functional softmax gating network \eqref{eq: FME gating} can be represented by { \begin{eqnarray}\label{eq: FME gating projected} \pi_{k}(\mathbf{r}_i;\boldsymbol{\xi}) =\frac{\exp\{\alpha_{k,0} + \mathbf{r}_i^\top \boldsymbol{\zeta}_k\}} {1+\sum_{k^\prime=1}^{K-1}\exp\{\alpha_{k^\prime,0} + \mathbf{r}_i^\top \boldsymbol{\zeta}_{k^\prime} \}}, \end{eqnarray}}where $\mathbf{r}_i=\left[\int_{\mathcal{T}}\boldsymbol{b}_r(t)\boldsymbol{b}_p(t)^\top dt\right]^\top \boldsymbol{x}_i$ is the design vector associated with the gating network and $\boldsymbol{\xi}=((\alpha_{1,0},\boldsymbol{\zeta}_1^\top), \ldots, (\alpha_{K-1,0},\boldsymbol{\zeta}_{K-1}^\top))\allowbreak\in\mathbb{R}^{(p+1)(K-1)}$ is the unknown parameter vector of the gating network, to be estimated. In the same manner, using the approximations of $X_i(\cdot)$ and $\beta_{kg}(\cdot)$ in \eqref{eq: projections}, the expert conditional distribution \eqref{eq: FME expert} can be represented by {\begin{equation}\label{eq: FME expert projected} \textstyle P(y_i|\mathbf{x}_i;\boldsymbol{\theta}_k) = \prod_{g=1}^G \left[\frac{\exp\left\{\beta_{kg,0} + \mathbf{x}_i^\top \boldsymbol{\eta}_{kg} \right\}} {1+\sum_{g^\prime=1}^{G-1}\exp\left\{\beta_{kg^\prime,0} + \mathbf{x}_i^\top\boldsymbol{\eta}_{kg^\prime} \right\}}\right]^{y_{ig}}, \end{equation}}where $\mathbf{x}_i = \left[ \int_{\mathcal{T}}\boldsymbol{b}_r(t)\boldsymbol{b}_q(t)^\top dt \right]^\top\boldsymbol{x}_i$ is the design vector associated with the expert network, and $\boldsymbol{\theta}_k=(\boldsymbol{\theta}_{k1}^\top,\ldots,\boldsymbol{\theta}_{k,G-1}^\top)^\top$, with $\boldsymbol{\theta}_{kg}=(\beta_{kg,0},\boldsymbol{\eta}_{kg}^\top)^\top\in\mathbb{R}^{q+1}$ for $g\in[G-1]$, is the unknown parameter vector to be estimated of the expert distribution $k$. % Finally, combining \eqref{eq: FME gating projected} and \eqref{eq: FME expert projected}, the conditional distribution $P(y_i|X_i(\cdot);\boldsymbol{\psi})$ in \eqref{eq: FMEMR distribution} can be rewritten as \[\label{eq: FMEMR distribution projected} P(y_i|X_i(\cdot);\boldsymbol{\varPsi}) = \sum_{k=1}^{K} \pi_{k}(\mathbf{r}_i;\boldsymbol{\xi}) P(y_i|\mathbf{x}_i;\boldsymbol{\theta}_k), \] where $\boldsymbol{\varPsi}=(\boldsymbol{\xi}^\top,\boldsymbol{\theta}_1^\top,\ldots,\boldsymbol{\theta}_K^\top)^\top$ is the unknown parameter vector of the model. \noindent {\it Parameter estimation:} A maximum likelihood estimate (MLE) $\widehat{\boldsymbol{\varPsi}}$ of $\boldsymbol{\varPsi}$ can be obtained by using the EM algorithm for ME model for classification with vector data as in \cite{Chen1999}. We will refer to this approach as FME-EM. To encourage sparsity in the model parameters $\boldsymbol{\varPsi}$, one can perform penalized MLE by using the EM-Lasso algorithm as in \cite{prEMME-2019}. We refer to this approach as FME-EM-Lasso. \subsection{An interpretable sparse estimation of FME for classification} Although fitting the FME model via EM-Lasso can accommodate sparsity in the parameters, it unfortunately does not ensure the reconstructed coefficient functions $\widehat \alpha_{k}(\cdot)$ and $\widehat \beta_{kg}(\cdot)$ are sparse and enjoy easy interpretable sparsity. To obtain interpretable and sparse fits for the coefficient functions, we simultaneously estimate the model parameters while constraining some targeted derivatives of the coefficient functions to be zero \citep{chamroukhi2022fME}. The construction of the interpretable FME model which we will fit with an adapted EM algorithm, is as follows. First, in order to calculate the derivative of the gating coefficient functions $\alpha_k(\cdot)$, let $\mathbf{A}_p$ be the matrix of approximate $d_1$th and $d_2$th derivative of $\boldsymbol{b}_p(t)$, defined as in \cite{FLIRTI,chamroukhi2022fME} by {\begin{eqnarray*}\label{eq:approx-derivatives-B(t)} \mathbf{A}_p &=& [\mathbf{A}_p^{[d_1]} \mathbf{A}_p^{[d_2]}]^{\top} = \left[D^{d_1} \boldsymbol{b}_p(t_1), \ldots, D^{d_1} \boldsymbol{b}_p(t_p), D^{d_2} \boldsymbol{b}_p(t_1), \ldots, D^{d_2} \boldsymbol{b}_p(t_p)\right]^{\top}, \end{eqnarray*}}where $D^d$ is the $d$th finite difference operator. Here $\mathbf{A}_p^{[d_j]}$ is a square invertible matrix and $\mathbf{A}_p\in\mathbb{R}^{2p\times p}$. Similarly, to calculate the derivatives of the expert coefficient functions $\beta_{kg}(\cdot)$, let $\mathbf{A}_q = [\mathbf{A}_q^{[d_1]} \mathbf{A}_q^{[d_2]}]^{\top} \in \mathbb{R}^{2q\times q}$ be the corresponding matrix defined for the $\boldsymbol{b}_q(t)$'s. Now, if we define $\boldsymbol{\omega}_{k} = \mathbf{A}_p \Bs{\zeta}_{k}$ and denote $\boldsymbol{\omega}_{k}= ({\boldsymbol{\omega}^{[d_1]}_{k}}^\top, {\boldsymbol{\omega}^{[d_2]}_{k}}^\top)^\top$, then $\boldsymbol{\omega}^{[d_1]}_{k}$ and $\boldsymbol{\omega}^{[d_2]}_{k}$ provide approximations to the $d_1$ and the $d_2$ derivatives of the coefficient function $\alpha_{k}(\cdot)$, respectively, which we denote as $\alpha_{k}^{(d_1)}(\cdot)$ and $\alpha_{k}^{(d_2)}(\cdot)$. Therefore, enforcing sparsity in $\boldsymbol{\omega}_{k}$ will constrain $\alpha_{k}^{(d_1)}(\cdot)$ and $\alpha_{k}^{(d_2)}(\cdot)$ to be zero at most of time points. Similarly, if we define $\boldsymbol{\gamma}_{kg} = \mathbf{A}_q \Bs{\zeta}_{k}$ and denote by $\boldsymbol{\gamma}_{kg}= ({\boldsymbol{\gamma}^{[d_1]}_{kg}}^\top, {\boldsymbol{\gamma}^{[d_2]}_{kg}}^\top)^\top$, then we can derive the same regularization for the coefficient functions $\beta_{kg}(\cdot)$. From the definitions of $\boldsymbol{\omega}_{k}$ and $\boldsymbol{\gamma}_{kg}$ we can easily get the following relations: \begin{subequations} \begin{empheq}[left=\empheqlbrace]{alignat=2} \boldsymbol{\zeta}_{k} &= {\mathbf{A}_p^{[d_1]}}^{-1} \boldsymbol{\omega}_{k}^{[d_1]} \text{ and } \boldsymbol{\omega}_{k}^{[d_2]} = \mathbf{A}_p^{[d_2]}{\mathbf{A}_p^{[d_1]}}^{-1} \boldsymbol{\omega}_{k}^{[d_1]} \label{iFME gating constrains} \\ \boldsymbol{\eta}_{kg} &= {\mathbf{A}_q^{[d_1]}}^{-1} \boldsymbol{\gamma}_{kg}^{[d_1]} \text{ and } \boldsymbol{\gamma}_{kg}^{[d_2]} = \mathbf{A}_q^{[d_2]}{\mathbf{A}_q^{[d_1]}}^{-1} \boldsymbol{\gamma}_{kg}^{[d_1]}. \label{iFME experts constrains} \end{empheq} \end{subequations} Plugging the relation \eqref{iFME gating constrains} into \eqref{eq: FME gating projected} one gets the following new representation for $\pi_{k}(\mathbf{r}_i;\boldsymbol{\xi})$ { \begin{equation}\label{eq: iFME gating projected} \textstyle \pi_{k}(\mathbf{s}_i;\mathbf{w}) = \frac{\exp{\{\alpha_{k,0}+ {\mathbf{s}_i^\top \boldsymbol{\omega}_k^{[d_1]}} \}}} {1+\sum_{k^\prime=1}^{K-1}\exp{\{\alpha_{k^\prime,0}+{\mathbf{s}_i^\top\boldsymbol{\omega}^{[d_1]}_{k^\prime}} \}}}, \end{equation}}where $\mathbf{s}_i = ({\mathbf{A}^{[d_1]}_p}^{-1})^\top\mathbf{r}_i$ is now the new design vector and $\mathbf{w}=(\alpha_{1,0},{\boldsymbol{\omega}^{[d_1]}_1}^\top,\ldots,\alpha_{K-1,0},{\boldsymbol{\omega}^{[d_1]}_{K-1}}^\top)^\top$, with $(\alpha_{K,0}, {\boldsymbol{\omega}^{[d_1]}_{K}}^\top)^\top$ a null vector, is the unknown parameter vector of the gating network. Similarly, plugging \eqref{iFME experts constrains} into \eqref{eq: FME expert projected} one obtains the new representation for $P(y_i|\mathbf{x}_i;\boldsymbol{\theta}_k)$: { \begin{equation}\label{eq: iFME expert projected} \textstyle P(y_i|\mathbf{v}_i;\boldsymbol{\Gamma}_k) = \prod_{g=1}^G \left[\frac{\exp\left\{\beta_{kg,0} + {\mathbf{v}_i^\top \boldsymbol{\gamma}_{kg}^{[d_1]}}\right\}} {1+\sum_{g^\prime=1}^{G-1}\exp\left\{\beta_{kg^\prime,0} + {\mathbf{v}_i^\top\boldsymbol{\gamma}_{k^\prime g}^{[d_1]}} \right\}}\right]^{y_{ig}}, \end{equation}}in which, $\mathbf{v}_i = ({\mathbf{A}^{[d_1]}_q}^{-1})^\top\mathbf{x}_i$ is now the new design vector and $\boldsymbol{\Gamma}_k = ( \beta_{kg,0}, {\boldsymbol{\gamma}_{k^\prime g}^{[d_1]}}^\top )^\top$ is the unknown parameter vector of the expert network. Finally, gathering the gating network \eqref{eq: iFME gating projected} and the expert network \eqref{eq: iFME expert projected}, the iFME model for classification is given by $P(y_i|X_i(\cdot);\Bs{\Upsilon}) = \sum_{k=1}^{K} \pi_{k}(\mathbf{s}_i;\mathbf{w}) P(y_i|\mathbf{v}_i;\boldsymbol{\Gamma}_k), $ where $\Bs{\Upsilon}=(\mathbf{w}^\top,\boldsymbol{\Gamma}_1^\top,\ldots,\boldsymbol{\Gamma}_K^\top)^\top$ is the unknown parameter vector to be estimated. We perform penalized MLE by penalizing the ML via a Lasso penalization on the derivative coefficients $\boldsymbol{\omega}_k$'s and $\boldsymbol{\gamma}_{kg}$'s of the form Pen$_{\chi,\lambda}(\Bs{\Upsilon}) = \chi\sum_{k=1}^{K-1}\Vert \boldsymbol{\omega}_k\Vert_1+ \lambda\sum_{k=1}^{K}\sum_{g=1}^{G-1}\Vert \boldsymbol{\gamma}_{kg}\Vert_1$, with $\chi$ and $\lambda$ regularization constants. The estimation is performed by using an adaptation to this classification context of the EM algorithm developed in \cite{chamroukhi2022fME}. The only difference resides in the maximization w.r.t. the expert network parameters $\boldsymbol{\Gamma}_k$. \vspace{-.6cm} \section{Numerical results} We conducted experiments by considering a $G=3$-class classification problem with a $K=2$-component FME model. The simulation protocol will be detailed during the presentation due to lack of space here. The classification results obtained with the described algorithms FME-EM, FME-EM-Lasso and iFME-EM, as well as with functional multinomial logistic regression (FMLR), are given in Table \ref{Table: prediction performance} and show higher classification performance of the iFME-EM approach. {\small \begin{table}[htp!] \centering \def.8{.8} \begin{tabular}{r l l} \specialrule{1pt}{1pt}{1pt} Model & \multicolumn{2}{l}{Correct Classification Rate}\\ \hline & Noise level: $\sigma^2_{\delta}=1$ & Noise level: $\sigma^2_{\delta}=5$ \\ FME-EM & $.8560_{(.0199)}$ & $.8474_{(.0196)}$ \\ FME-EM-Lasso & $.9332_{(.0104)}$ & $.9178_{(.0142)}$ \\ iFME-EM & $\Bs{.9346_{(.0108)}}$ & $\Bs{.9219_{(.0127)}}$ \\ FMLR & $.7951_{(.0249)}$ & $.7922_{(.0270)}$ \\ \specialrule{1pt}{2pt}{1pt} \end{tabular} \caption{Correct classification rates obtained on testing data. The reported values are averages on 100 samples with standard errors in parentheses.}\label{Table: prediction performance} \end{table}} \begin{figure}[h!] \centering \vspace{-0.1cm} {\includegraphics[scale=0.7]{Figures/Phonemes/expert_LASSO.eps}}\\ \vspace{0.2cm} {\includegraphics[scale=0.7]{Figures/Phonemes/expert_FLIRTI.eps}} \caption{Results of (top) FME-EM-Lasso and (bottom) iFME-EM on phoneme data.} \label{fig:phoneme results} \end{figure} We then applied the two algorithms allowing for sparsity (FME-EM-Lasso and iFME-EM) to the well-known phoneme data \citep{Hastie95penalizeddiscriminant}. The data consists of $n=1000$ log-periodogram recordings of length $256$ each, used here as the univariate functional predictors, of five phonemes (the corresponding class labels). % The obtained averaged correct classification rate for the two approaches are more than 0.94 in mean. Figure \ref{fig:phoneme results} shows the estimated coefficient functions for the expert network $\widehat \beta_{kg}(t)$ as functions of sampling time $t$, obtained by FME-EM-Lasso (top) and the iFME-EM (bottom); Here the iFME-EM is fitted with constraints on the zero and the second derivatives of the coefficients functions. The results show clearly sparse and piece-wise-linear gating and experts functions when using the iFME-EM approach. \paragraph{Acknowledgement:} This research is supported by ANR SMILES ANR-18-CE40-0014. \vspace{-.3cm} \bibliographystyle{apalike \setlength{\bibsep}{0pt}
{'timestamp': '2022-03-01T02:55:56', 'yymm': '2202', 'arxiv_id': '2202.13934', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13934'}
arxiv
\subsubsection*{References}} \usepackage{mathtools} \usepackage{booktabs} \usepackage{hyperref} \usepackage{caption} \usepackage{subcaption} \usepackage{bbm} \usepackage{xifthen} \usepackage{graphicx} \usepackage{adjustbox} \usepackage{standalone} \usepackage[dvipsnames]{xcolor} \usepackage{tikz} \usetikzlibrary{positioning} \usetikzlibrary{arrows} \usetikzlibrary{calc,fit} \usetikzlibrary{shapes.geometric} \usetikzlibrary{shapes.misc} \usetikzlibrary{decorations.pathmorphing} \usetikzlibrary{decorations.pathreplacing} \usetikzlibrary{snakes} \usepackage{pgfplots} \usepgfplotslibrary{groupplots} \pgfplotsset{compat=1.16} \usepgfplotslibrary{statistics} \usepackage{amsmath} \usepackage{amssymb} \usepackage{mathtools} \usepackage{amsthm} \definecolor{darkblue}{rgb}{0.0, 0.0, 0.55} \hypersetup{ pdftitle={Bayesian Structure Learning with Generative Flow Networks}, pdfkeywords={}, pdfborder=0 0 0, pdfpagemode=UseNone, colorlinks=true, linkcolor=darkblue, citecolor=darkblue, filecolor=darkblue, urlcolor=darkblue, pdfview=FitH, pdfauthor={Anonymous} } \usepackage[capitalize,noabbrev]{cleveref} \theoremstyle{plain} \newtheorem{theorem}{Theorem}[section] \newtheorem{proposition}[theorem]{Proposition} \newtheorem{lemma}[theorem]{Lemma} \newtheorem{corollary}[theorem]{Corollary} \theoremstyle{definition} \newtheorem{definition}[theorem]{Definition} \newtheorem{assumption}[theorem]{Assumption} \theoremstyle{remark} \newtheorem{remark}[theorem]{Remark} \input{math_commands.tex} \crefformat{section}{#2Section~#1#3} \crefformat{appendix}{#2Appendix~#1#3} \crefformat{equation}{(#2#1#3)} \crefmultiformat{equation}{#2Equations~#1#3}% { \&~#2#1#3}{, #2#1#3}{, \&~#2#1#3} \crefformat{table}{#2Table~#1#3} \crefformat{figure}{#2Figure~#1#3} \crefformat{theorem}{#2Theorem~#1#3} \crefmultiformat{theorem}{#2Theorems~#1#3}% { \&~#2#1#3}{, #2#1#3}{, and~(#2#1#3)} \crefformat{lemma}{#2Lemma~#1#3} \crefformat{proposition}{#2Proposition~#1#3} \crefmultiformat{proposition}{#2Propositions~#1#3}% { \&~#2#1#3}{, #2#1#3}{, and~(#2#1#3)} \crefformat{algorithm}{#2Algorithm~#1#3} \crefmultiformat{algorithm}{#2Algorithms~#1#3}% { \&~#2#1#3}{, #2#1#3}{, and~(#2#1#3)} \crefformat{corollary}{#2Corollary~#1#3} \crefformat{definition}{#2Definition~#1#3} \crefformat{assumption}{#2Assumption~#1#3} \crefmultiformat{assumption}{#2Assumptions~#1#3}% { \&~#2#1#3}{, #2#1#3}{, and~(#2#1#3)} \newcommand{\mathrm{Ch}}{\mathrm{Ch}} \newcommand{\mathrm{Pa}}{\mathrm{Pa}} \title{Bayesian Structure Learning with Generative Flow Networks} \renewcommand{\Authsep}{\hspace{2em}} \renewcommand{\Authand}{\hspace{2em}} \renewcommand{\Authands}{\leading{18pt}\hspace{2em}} \makeatletter \def\thanks#1{\protected@xdef\@thanks{\@thanks\protect\footnotetext{#1}}} \makeatother \makeatletter \renewcommand\AB@affilsepx{\hspace{1em}\protect\Affilfont} \makeatother \author[1]{Tristan~Deleu\thanks{Correspondence to: Tristan Deleu <\href{mailto:[email protected]}{[email protected]}>}} \author[1]{Ant\'{o}nio~G\'{o}is} \author[2,*]{Chris~Emezue\thanks{\textsuperscript{*}Work done during an internship at Mila}} \author[1]{Mansi~Rankawat} \author[1,4]{\authorcr{Simon~Lacoste-Julien}} \author[3,5]{Stefan~Bauer} \author[1,4,6]{Yoshua~Bengio} \affil[1]{Mila, Universit\'{e} de Montr\'{e}al} \affil[2]{Technical University of Munich} \affil[3]{KTH Stockholm\protect\\[0.5em]} \affil[4]{CIFAR AI Chair} \affil[5]{CIFAR Azrieli Global Scholar} \affil[6]{CIFAR Senior Fellow} \begin{document} \maketitle \begin{abstract} In Bayesian structure learning, we are interested in inferring a distribution over the directed acyclic graph (DAG) structure of Bayesian networks, from data. Defining such a distribution is very challenging, due to the combinatorially large sample space, and approximations based on MCMC are often required. Recently, a novel class of probabilistic models, called Generative Flow Networks (GFlowNets), have been introduced as a general framework for generative modeling of discrete and composite objects, such as graphs. In this work, we propose to use a GFlowNet as an alternative to MCMC for approximating the posterior distribution over the structure of Bayesian networks, given a dataset of observations. Generating a sample DAG from this approximate distribution is viewed as a sequential decision problem, where the graph is constructed one edge at a time, based on learned transition probabilities. Through evaluation on both simulated and real data, we show that our approach, called DAG-GFlowNet, provides an accurate approximation of the posterior over DAGs, and it compares favorably against other methods based on MCMC or variational inference. \end{abstract} \section{Introduction} \label{sec:introduction} Bayesian networks \citep{pearl1988bayesiannetworks} are a popular framework of choice for representing uncertainty about the world in multiple scientific domains, including medical diagnosis \citep{lauritzen1988munin,heckerman1992pathfinder}, molecular biology \citep{friedman2004cellular,sebastiani2005genetic}, and ecological modeling \citep{varis1999environmental,marcot2006guidelinesecological}. For many applications, the structure of the Bayesian network, represented as a directed acyclic graph (DAG) and encoding the statistical dependencies between the variables of interest, is assumed to be known based on knowledge from domain experts. However, when this graph is unknown, we can learn the DAG structure of the Bayesian network from data alone in order to discover these statistical (or possibly causal) relationships. This may form the basis of novel scientific theories. Given a dataset of observations, most of the existing algorithms for structure learning return a single DAG (or a single equivalence class; \citealp{chickering2002ges}), and in practice those may lead to poorly calibrated predictions \citep{madigan1994enhancing}. Instead of learning a single graph candidate, we can view the problem of structure learning from a Bayesian perspective and infer the posterior over graphs $P(G\mid {\mathcal{D}})$, given a dataset of observations ${\mathcal{D}}$. Except in limited settings \citep{koivisto2006exact,meilua2006tree}, characterizing a whole distribution over DAGs remains intractable because of its combinatorially large sample space and the complex acyclicity constraint. Therefore, we must often resort to approximations of this posterior distribution, e.g. based on MCMC or, more recently, variational~inference. In this paper, we propose to use a novel class of probabilistic models called \emph{Generative Flow Networks} \citep[GFlowNets;][]{bengio2021gflownet,bengio2021gflownetfoundations} to approximate this posterior distribution over DAGs. A GFlowNet is a generative model over discrete and composite objects that treats the generation of a sample as a sequential decision problem. This makes it particularly appealing for modeling a distribution over graphs, where sample graphs are constructed sequentially, starting from the empty graph, by adding one edge at a time. In the context of Bayesian structure learning, we also introduce improvements over the original GFlowNet framework, including a novel flow-matching condition and corresponding loss function, a hierarchical probabilistic model for forward transitions, and using additional tools from the literature on Reinforcement Learning (RL). We call our method \emph{DAG-GFlowNet}, to emphasize that the support of the distribution induced by the GFlowNet is exactly the space of DAGs, unlike some variational approaches that may sample cyclic graphs \citep{annadani2021vcn,lorch2021dibs}. Compared to MCMC, which operates through local moves in the sample space (here, adding or removing edges of a graph) and is therefore subject to slow mixing \citep{friedman2003ordermcmc}, DAG-GFlowNet yields a sampling process that samples iid. DAGs, each of them constructed from scratch. We evaluate DAG-GFlowNet on various problems with simulated and real data, on both discrete and linear-Gaussian Bayesian networks. Furthermore, we show that DAG-GFlowNet can be applied on both observational and interventional data, by modifying standard Bayesian scores \citep{cooper1999interventional}. On smaller graphs, we also show that it is capable of learning an accurate approximation of the exact posterior distribution. \vspace*{-1em} \section{Related Work} \label{sec:related-work} \paragraph{Markov chain Monte Carlo} Methods based on MCMC have been particularly popular in Bayesian structure learning to approximate the posterior distribution. Structure MCMC \citep[MC\textsuperscript{3};][]{madigan1995structuremcmc} simulates a Markov chain in the space of DAGs, through local moves (e.g. adding or removing an edge). Working directly with DAGs leads to slow mixing though; to improve mixing, \citet{friedman2003ordermcmc} proposed a sampler in the space of node orders, that introduced a bias \citep{ellis2008bias}. This was further refined by either modifying the underlying space of the Markov chain \citep{kuipers2017partitionmcmc,niinimaki2016partialordermcmc}, or its local moves \citep{mansinghka2006gibbs,eaton2007bayesian,kuipers2021efficient}. Recently, \citet{viinikka2020gadget} incorporated many of these advances into an efficient MCMC sampler called \textit{Gadget}. \vspace*{-0.5em} \paragraph{Variational Inference} In the context of structure learning, applying the recent advances in approximate inference based on gradient methods can be difficult due to the discrete nature of the problem \citep{lorch2021dibs}. \citet{cundy2021bcdnets} decomposed the adjacency matrix of a DAG into a triangular matrix and a permutation, and used a continuous relaxation to parametrize a distribution over permutations. Other methods \citep{annadani2021vcn,lorch2021dibs} encode the acyclicity constraint into a soft prior $P(G)$, based on continuous characterizations of acyclicity \citep{zheng2018notears}. While the effect of this prior can be made arbitrarily strong, this does not guarantee that the graphs sampled from the resulting distribution are acyclic. By contrast, our approach guarantees by construction that the support of the posterior approximation is exactly the space of DAGs. \vspace*{-0.5em} \paragraph{Sequential decisions} In this work, we treat the construction of a sample graph from the posterior as a sequential decision problem, starting from the empty graph and adding one edge at a time. \citet{li2018gengraphs} use a similar process for creating a generative model over graphs with a fixed ordering over nodes. Similarly, although they do not consider a distribution over graphs, \citet{buesing2020approximate} use a variant of Monte Carlo Tree Search to approximate a distribution over a pre-specified ordering of discrete random variables. Our method, based on Generative Flow Networks, does not make any assumption on the order in which the edges are added, and multiple edge insertion sequences may lead to the same DAG. \citet{zhu2020causaldiscoveryrl} learn a single high-scoring structure using RL; however, unlike our approach, the creation of this graph does not involve sequential decisions. \section{Background} \label{sec:background} A \emph{Bayesian network} is a probabilistic model over $d$ random variables $\{X_{1}, \ldots, X_{d}\}$, whose joint distribution factorizes according to a DAG $G$ as \begin{equation} P(X_{1}, \ldots, X_{d}) = \prod_{k=1}^{d}P\big(X_{k} \mid \mathrm{Pa}_{G}(X_{k})\big), \end{equation} where $\mathrm{Pa}_{G}(X)$ is the set of parents of node $X$ in $G$. Similarly, we denote by $\mathrm{Ch}_{G}(X)$ the children of $X$; when the context is clear, we may drop the explicit dependency on $G$. \subsection{Generative Flow Networks} \label{sec:generative-flow-networks} Originally introduced to encourage the discovery of diverse modes of an unnormalized distribution \citep{bengio2021gflownet}, \emph{Generative Flow Networks} \citep[GFlowNets;][]{bengio2021gflownetfoundations} are a class of generative models over a discrete and structured sample space ${\mathcal{X}}$. The structure of a GFlowNet is defined by a DAG over some states $s \in {\mathcal{S}}$; in general, the sample space over which we wish to define a distribution is only a subset of the overall state space of the GFlowNet: ${\mathcal{X}} \subseteq {\mathcal{S}}$. Samples $s \in {\mathcal{X}}$ are constructed sequentially by following the edges of the DAG, starting from a fixed initial state $s_{0}$. We also define a special absorbing state $s_{f}$, called the terminal state, indicating when the sequential construction terminates; some of the states $s \in {\mathcal{X}}$ are connected to $s_{f}$, and we call them \emph{complete states}.\footnote{``Complete'' here means that the state is a valid sample from the distribution induced by the GFlowNet. This must not be confused with a ``complete graph'', where all the nodes are connected to one another, when the states are DAGs (see \cref{sec:gflownet-over-dags}).} For example, \citet{bengio2021gflownet} use a GFlowNet to define a distribution over molecules, where ${\mathcal{X}}$ would correspond to the space of all (complete) molecules, which are constructed piece by piece by attaching a new block to an atom in a possibly partially constructed molecule (i.e. a state in ${\mathcal{S}} \backslash {\mathcal{X}}$). Another example of a GFlowNet structure is given in Fig.~\ref{fig:gflownet-dags}, illustrating the sequential process of constructing a DAG. A GFlowNet is structurally equivalent to a Markov Decision Process \citep[MDP;][]{puterman1994mdp} with deterministic dynamics, or a Markov Reward Process \citep{howard1971mrp}. In addition to the DAG structure over states, every complete state $s \in {\mathcal{X}}$ is associated with a \emph{reward} $R(s) \geq 0$, indicating a notion of ``preference'' for certain states. By convention, $R(s) = 0$ for any incomplete state $s \in {\mathcal{S}} \backslash {\mathcal{X}}$. The goal of a GFlowNet is to find a \emph{flow} that satisfies, for all states $s' \in {\mathcal{S}}$, the following \emph{flow-matching condition}: \begin{equation} \sum_{\mathclap{s \in \mathrm{Pa}(s')}}\;F_{\theta}(s \rightarrow s') -\;\sum_{\mathclap{s'' \in \mathrm{Ch}(s')}}\;F_{\theta}(s' \rightarrow s'') = R(s'), \label{eq:flow-matching-condition} \end{equation} where $F_{\theta}(s \rightarrow s') \geq 0$ is a scalar representing the flow from state $s$ to $s'$, typically parametrized by a neural network. Putting it in words, the overall flow going into $s'$ is equal to the flow going out of $s'$, plus some residual $R(s')$. To learn the parameters $\theta$ of the flow with SGD, we can turn \cref{eq:flow-matching-condition} into a regression problem, e.g. using a least squares objective over sampled states. If the conditions in \cref{eq:flow-matching-condition} are satisfied for all states $s'$, a GFlowNet induces a generative process to sample complete states $s \in {\mathcal{X}}$ with probability proportional to $R(s)$. Starting from the initial state $s_{0}$, if we sample a complete trajectory $(s_{0}, s_{1}, \ldots, s_{T}, s, s_{f})$ using the transition probability defined as the normalized outgoing flow \begin{equation} P(s_{t+1} \mid s_{t}) \propto F_{\theta}(s_{t} \rightarrow s_{t+1}), \label{eq:forward-transition-probability} \end{equation} with the conventions $s_{T+1} = s$ and $s_{T+2} = s_{f}$, then $s$ is sampled with probability $P(s) \propto R(s)$. Note that the linear system in \cref{eq:flow-matching-condition} is in general underdetermined, and therefore it may admit many solutions $F_{\theta}(s \rightarrow s')$ that all induce the same distribution $\propto R(s)$. Unlike MCMC, each sample $s \in {\mathcal{X}}$ is constructed from scratch, starting at the initial state $s_{0}$, instead of traversing ${\mathcal{X}}$ from sample to sample. Therefore, the underlying Markov process of the GFlowNet does not have to be irreducible, which is typically necessary in MCMC, but merely requires all the complete states to be reachable from the initial state. Finally, although GFlowNets borrow terminology from RL and control theory (e.g. MDPs, rewards, trajectories), their objective is different from the typical RL training objective: the latter seeks to maximize a function of the rewards, while the goal of GFlowNets is to model the whole distribution proportional to the rewards. \vspace*{-0.5em} \subsection{Detailed-balance condition} \label{sec:detailed-balance-condition} \vspace*{-0.5em} Since the flows are added together, one of the downsides of the flow-matching condition is that flows tend to be orders of magnitude larger the closer we are of the initial state \citep{bengio2021gflownet}, making it challenging to parametrize $F_{\theta}$. \citet{bengio2021gflownetfoundations} proposed an alternative characterization of GFlowNets inspired by the detailed-balance equations from the literature on Markov chains \citep{grimmett2020probability}. Instead of working with flows, this condition uses a parametrization of the forward transition probability $P_{\theta}(s_{t+1} \mid s_{t})$ directly, together with a backward transition probability $P_{B}(s_{t} \mid s_{t+1})$ to enforce reversibility. As opposed to $P_{\theta}(s_{t+1} \mid s_{t})$, which is a distribution over the children of $s_{t}$, $P_{B}(s_{t} \mid s_{t+1})$ is a distribution over the parents of $s_{t+1}$ in the structure of the GFlowNet. If all the states of the GFlowNet are complete (except the terminal state $s_{f}$), which will be the case here for generating DAGs, then we show in \cref{app:detailed-balance-condition} that we can write the \emph{detailed-balance condition} for all transitions $s \rightarrow s'$ as follows: \begin{equation*} R(s')P_{B}(s\mid s')P_{\theta}(s_{f}\mid s) = R(s)P_{\theta}(s'\mid s)P_{\theta}(s_{f}\mid s'). \label{eq:detailed-balance-condition} \end{equation*} Similar to \cref{sec:generative-flow-networks}, finding $P_{\theta}$ and $P_{B}$ that satisfy this condition for all the transitions $s \rightarrow s'$ of the GFlowNet also yields a sampling process of complete states $s$ with probability proportional to $R(s)$, based on the forward transition probability $P_{\theta}(s_{t+1}\mid s_{t})$. Because this system of equations also admits many solutions, similar to \cref{eq:flow-matching-condition}, we can set the backward transition probability $P_{B}$ to some fixed distribution (e.g. the uniform distribution over the parent states) to reduce the search space, making $P_{\theta}$ the only quantity to learn and, with enough capacity (to satisfy the constraints), there is a unique solution $P_{\theta}$ \citep{bengio2021gflownetfoundations}. To fit the parameters $\theta$ of the forward transition probability, we can minimize the following non-linear least squares objective for all the transitions $s \rightarrow s'$ of the GFlowNet, called the \emph{detailed-balance loss}: \begin{equation} {\mathcal{L}}(\theta) = \sum_{s \rightarrow s'}\bigg[\log \frac{R(s')P_{B}(s\mid s')P_{\theta}(s_{f}\mid s)}{R(s)P_{\theta}(s'\mid s)P_{\theta}(s_{f}\mid s')}\bigg]^{2}. \label{eq:detailed-balance-loss} \end{equation} Alternatively, we can minimize this loss in expectation, using a distribution $\pi(s \rightarrow s')$ with full support over transitions (i.e. for all transitions $s \rightarrow s'$ in the GFlowNet, we have $\pi(s \rightarrow s') > 0$; see \cref{sec:off-policy-learning}). \section{GFlowNet over Directed Acyclic Graphs} \label{sec:gflownet-over-dags} \begin{figure}[t!] \centering \includestandalone[width=\linewidth]{figures/gflownet-dags} \vspace*{-1.5em} \caption{Structure of a GFlowNet over DAGs. The states of the GFlowNet correspond to DAGs, with the initial state $G_{0}$ being the completely disconnected graph. Each state $G$ is complete (i.e. connected to the terminal state $s_{f}$, represented by blue arrows for brevity) and associated to a reward $R(G)$. Transitioning from one state to another corresponds to adding an edge to the graph. The state in red is invalid since the graph includes a cycle.} \label{fig:gflownet-dags} \end{figure} Our objective in this paper is to construct a distribution over DAGs. This is a challenging problem in general, as the space of DAGs is discrete and combinatorially large. We propose to use a GFlowNet to model such a distribution; this is particularly appropriate here since graphs are composite objects, and the acyclicity constraint can be obtained by constraining the allowed actions in each state (as in \cref{fig:gflownet-dags}). Note that the DAGs in this section and thereafter represent the states of the GFlowNet, and they must not be confused with the DAG structure of the GFlowNet itself. \subsection{Structure of the GFlowNet} \label{sec:structure-gflownet} We consider a GFlowNet where the states are DAGs over $d$ (labeled) nodes. Since the states of the GFlowNet are graphs, we will use the notation $G$ to denote a state, in favour of $s$ as in \cref{sec:generative-flow-networks}, except for the terminal state $s_{f}$. A transition $G \rightarrow G'$ in this GFlowNet corresponds to adding an edge to $G$ to obtain the graph $G'$; in other words, the graphs are constructed one edge at a time, starting from the initial state $G_{0}$, which is the fully disconnected graph over $d$ nodes. Since we assume that all the states $G$ of the GFlowNet are valid DAGs, they are all complete (i.e. connected to the terminal state $s_{f}$) with a corresponding reward $R(G)$. \cref{fig:gflownet-dags} shows an illustration of the structure of such a GFlowNet, where the states are DAGs over $d=3$ nodes. This application to graphs highlights the importance of the DAG structure of the GFlowNet, since there can be multiple paths leading to the same state: for any graph $G$ with $k$ edges, there are $k!$ possible paths from $G_{0}$ leading to $G$, because the edges of $G$ may have been added in any order. To guarantee the integrity of the GFlowNet, we have to ensure that adding a new edge to some state $G$ also yields a valid DAG, meaning that this edge (1) must not be already present in $G$, and (2) must not introduce a cycle. Fortunately, we can filter out invalid actions using some mask ${\bm{m}}$ associated to the graph, built from the adjacency matrix of $G$ and the transitive closure of its transpose, and that can be updated efficiently after the addition an edge \citep{giudici2003improvingmcmc}. A description of this update is given in \cref{app:mask} for completeness. \subsection{Forward transition probabilities} \label{sec:forward-transition-probabilities} Following \cref{sec:detailed-balance-condition}, the GFlowNet may be parametrized only by the forward transition probabilities $P_{\theta}(G_{t+1} \mid G_{t})$; here, $G_{t+1}$ might be the terminal state $s_{f}$ by abuse of notation. To make sure that the detailed-balance conditions can be satisfied, we need to define these transition probabilities using a sufficiently expressive function, such as a neural network. We use a hierarchical model, where the forward transition probabilities are defined using two neural networks: (1) a network modeling the probability of terminating $P_{\theta}(s_{f} \mid G)$, and (2) another giving the probability $P_{\theta}(G' \mid G, \neg s_{f})$ of transitioning to a new graph $G'$, given that we do not terminate. The probability of taking a transition $G \rightarrow G'$ is then given by \begin{equation} P_{\theta}(G' \mid G) = \big(1 - P_{\theta}(s_{f} \mid G)\big) P_{\theta}(G' \mid G, \neg s_{f}). \label{eq:transition-proba-hierarchical} \end{equation} In practice, as $G'$ is the result of adding an edge to the DAG $G$, we can model $P_{\theta}(G' \mid G, \neg s_{f})$ as a probability distribution over the $d^{2}$ possible edges one could add to $G$---this includes self-loops, for simplicity, even though these actions are guaranteed to be invalid. We can use the mask ${\bm{m}}$ introduced in \cref{sec:structure-gflownet} to filter out actions that would not lead to a valid DAG $G'$ and set $P_{\theta}(G' \mid G, \neg s_{f}) = 0$ for any invalid action (as well as normalize $P_{\theta}$ accordingly). \subsection{Parametrization with Linear Transformers} \label{sec:parametrization-linear-transformers} \begin{figure*}[t!] \centering \includestandalone[width=0.95\linewidth]{figures/transformer-architecture} \vspace*{-0.5em} \caption{Neural network architecture of the forward transition probabilities $P_{\theta}(G_{t+1} \mid G_{t})$. The input graph $G$ is encoded as a set of $d^{2}$ possible edges (including self-loops). Each directed edge is embedded using the embeddings of its source and target, with an additional vector indicating whether the edge is present in $G$. These embeddings are fed into a Linear Transformer \citep{katharopoulos2020lineartransformers}, with two separate output heads. The first head (above) gives the probability to add a new edge $P_{\theta}(G' \mid G, \neg s_{f})$, using the mask ${\bm{m}}$ associated to $G$ to filter out invalid actions; here, the only valid actions are either adding $B \rightarrow C$, or $C \rightarrow B$. The second head (below) gives the probability to terminate the trajectory $P_{\theta}(s_{f}\mid G)$.} \label{fig:transformer-architecture} \end{figure*} Beyond having enough capacity to satisfy as well as possible the detailed-balance condition at all states, we choose to parametrize the forward transition probabilities with neural networks to benefit from their capacity to generalize to states not encountered during training. In practice, instead of defining two separate networks to parametrize $P_{\theta}(s_{f} \mid G)$ and $P_{\theta}(G' \mid G, \neg s_{f})$, we use a single neural network with a common backbone and two separate heads, to benefit from parameter sharing. The full architecture is given in \cref{fig:transformer-architecture}. Our choice of neural network architecture is motivated by multiple factors: we want an architecture (1) that is invariant to the order of the inputs, since $G$ is represented as a set of edges, (2) that transforms a set of input edges into a set of output probabilities for each edge to be added, in order to define $P_{\theta}(G'\mid G, \neg s_{f})$, and (3) whose parameters $\theta$ do not scale too much with $d$. A natural option would be to use a Transformer \citep{vaswani2017transformer}; however, because the size of our inputs is $d^{2}$, the self-attention layers would scale as $d^{4}$, and this would severely limit our ability to apply our method to model a distribution over larger DAGs. We opted for a Linear Transformer \citep{katharopoulos2020lineartransformers} instead, which has the advantage to not suffer from this quadratic scaling in the input size. This architecture relies on a linearized attention mechanism, defined as \begin{align} Q = {\bm{x}} W_{Q} \qquad K = {\bm{x}} W_{K} \qquad V = {\bm{x}} W_{V}\nonumber\\ \mathrm{LinAttn}_{k}({\bm{x}}) = \frac{\sum_{j=1}^{J}\big(\phi(Q_{k})^{\top}\phi(K_{j})\big)V_{j}}{\sum_{j=1}^{J}\phi(Q_{k})^{\top}\phi(K_{j})}, \end{align} where ${\bm{x}}$ is the input of the linearized attention layer, $\phi(\cdot)$ is a non-linear feature map, $J$ is the size of the input ${\bm{x}}$ (in our case, $J = d^{2}$), and $Q$, $K$, and $V$ are linear transformations of ${\bm{x}}$ corresponding to the queries, keys, and values respectively, as is standard with Transformers. \section{Application to Bayesian Structure Learning} \label{sec:application-bayesian-structure-learning} We are given a dataset ${\mathcal{D}} = \{{\bm{x}}^{(1)}, \ldots, {\bm{x}}^{(N)}\}$ of $N$ observations ${\bm{x}}^{(j)}$, each consisting of $d$ elements. We consider the task of characterizing the posterior distribution $P(G \mid {\mathcal{D}})$ over Bayesian networks that model these observations. We assume that the samples in ${\mathcal{D}}$ are iid. and fully-observed. As an alternative to MCMC \citep{madigan1995structuremcmc} or variational inference \citep{lorch2021dibs}, we approximate the posterior distribution over DAGs using a GFlowNet, as described in the previous section. For any DAG $G$, we will define its reward as the joint probability \begin{equation} R(G) = P(G)P({\mathcal{D}} \mid G), \label{eq:gflownet-reward} \end{equation} where $P(G)$ is a prior over DAGs \citep{eggeling2019structureprior}, and $P({\mathcal{D}} \mid G)$ is the marginal likelihood. In Sec.~\ref{sec:detailed-balance-condition}, we saw that if the detailed-balance conditions are satisfied for all the states of the GFlowNet, then this yields a sampling process with probability proportional to $R(G)$. Therefore, by Bayes' theorem, a GFlowNet with the specific reward function in \cref{eq:gflownet-reward} approximates the posterior distribution $P(G\mid {\mathcal{D}}) \propto R(G)$. We call our method \emph{DAG-GFlowNet}. \vspace*{-0.5em} \subsection{Modularity \& computational efficiency} \label{sec:modularity-computational-efficiency} \vspace*{-0.5em} Following prior works on Bayesian structure learning, we assume that both the priors over parameters $P(\phi \mid G)$ of the Bayesian network (required to compute the marginal likelihood) and over structures $P(G)$ are \emph{modular} \citep{heckerman1995bde,chickering1995learning}. As a consequence the reward $R(G)$ is also modular, and its logarithm can be written as a sum of local scores that only depend on individual variables and their parents in $G$: \begin{equation} \log R(G) = \sum_{j=1}^{d}\mathrm{LocalScore}\big(X_{j}\mid \mathrm{Pa}_{G}(X_{j})\big). \label{eq:log-reward-modular} \end{equation} Note that with our choice of reward, $\log R(G)$ corresponds to the Bayesian score \citep{koller2009pgm}. Examples of modular scores include the BDe score \citep{heckerman1995bde} and the BGe score \citep{geiger1994bge,kuipers2014bgeaddendum}. In order to fit the parameters $\theta$ of the GFlowNet, we will use the detailed-balance loss in \cref{eq:detailed-balance-loss}. We can observe that this loss function only involves the difference in log-rewards $\log R(G') - \log R(G)$ between two consecutive states, where $G'$ is the result of adding some edge $X_{i} \rightarrow X_{j}$ to the DAG $G$. Using our assumption of modularity, we can therefore compute this difference efficiently, as the terms in \cref{eq:log-reward-modular} remain unchanged for $j' \neq j$: \begin{align} &\log R(G') - \log R(G) = \mathrm{LocalScore}\big(X_{j}\mid \mathrm{Pa}_{G}(X_{j}) \cup \{i\}\big)\nonumber\\ &\qquad \qquad - \mathrm{LocalScore}\big(X_{j} \mid \mathrm{Pa}_{G}(X_{j})\big). \label{eq:delta-score} \end{align} This difference in local scores is sometimes called the \emph{delta score}, or the \emph{incremental value} \citep{friedman2003ordermcmc}, and has been employed in the literature to improve the efficiency of search algorithms \citep{chickering2002ges,koller2009pgm}. \vspace*{-0.5em} \subsection{Off-policy learning} \label{sec:off-policy-learning} \vspace*{-0.5em} \begin{figure*}[t!] \centering \includestandalone[width=0.9\linewidth]{figures/small-graphs/all_features} \caption{Comparison between the exact posterior distribution and the posterior approximation from DAG-GFlowNet, for different structural features: (a) edge features $X_{i} \rightarrow X_{j}$, (b) path features $X_{i} \rightsquigarrow X_{j}$, (c) Markov features $X_{i} \sim_{M} X_{j}$. Each point corresponds to a feature computed for specific variables $X_{i}$ and $X_{j}$ in a graph over $d = 5$ nodes, either based on the exact posterior (x-axis), or the posterior approximation found with the GFlowNet (y-axis). We repeated this experiment with $20$ different (ground-truth) DAGs. The Pearson correlation coefficient $r$ is included in the bottom-right corner of each~plot.} \label{fig:posterior-comparison} \end{figure*} As the number of states in DAG-GFlowNet is super-exponential in $d$, the number of nodes in each DAG $G$, it would be impractical to minimize the detailed-balance loss for all possible transitions $G \rightarrow G'$. Alternatively, we can minimize this loss in expectation using a distribution $\pi(G \rightarrow G')$ with full support over transitions: \begin{equation} {\mathcal{L}}(\theta) = \mathbb{E}_{\pi}\Bigg[\bigg[\log \frac{R(G')P_{B}(G \mid G')P_{\theta}(s_{f}\mid G)}{R(G)P_{\theta}(G'\mid G)P_{\theta}(s_{f}\mid G')}\bigg]^{2}\Bigg]. \label{eq:expected-detailed-balance-loss} \end{equation} This distribution $\pi(G \rightarrow G')$ can be arbitrary; for example, we can use $P_{\theta}(G' \mid G)$ directly and learn it \emph{on-policy} \citep{rummery1994sarsa}, as long as it assigns non-zero probability to any next state $G'$. Taking inspiration from Deep Q-learning \citep{mnih2015dqn}, we instead learn $P_{\theta}$ using \emph{off-policy} data. Transitions $G \rightarrow G'$ are collected based on $P_{\theta}(G'\mid G)$, along with their corresponding delta score (\cref{eq:delta-score}), and they are stored in a replay buffer. We can also sample some transitions uniformly at random, with probability $\varepsilon$, to encourage exploration. To estimate ${\mathcal{L}}(\theta)$ and update the parameters $\theta$, we can then sample a mini-batch of transitions randomly from the replay buffer. Moreover, again inspired by Deep Q-learning \citep{van2018deadlytriad}, we found it advantageous to evaluate $P_{\bar{\theta}}(s_{f} \mid G')$ in \cref{eq:expected-detailed-balance-loss} with a separate target network---where the parameters $\bar{\theta}$ are updated periodically. \vspace*{-0.5em} \section{Experimental results} \label{sec:experimental-reults} \vspace*{-0.5em} We compared DAG-GFlowNet against 3 broad classes of Bayesian structure learning algorithms: MCMC, non-parametric DAG Bootstrapping \citep{friedman1999bootstrap}, and variational inference. We used Structure MCMC \citep[MC\textsuperscript{3};][]{madigan1995structuremcmc} and the recent Gadget \citep{viinikka2020gadget} samplers as two representative methods based on MCMC. Following \citet{lorch2021dibs}, we used two variants of Bootstrapping based on the score-based algorithm GES \citep[Bootstrap GES;][]{chickering2002ges}, and the constraint-based algorithm PC \citep[Bootstrap PC;][]{spirtes2000pc}, as the internal structure learning routines. Finally for methods based on variational inference, we used DiBS \citep{lorch2021dibs} and BCD Nets \citep{cundy2021bcdnets}. Throughout this section, we used the BGe score for continuous data, and the BDe score for discrete data, to compute $\log p({\mathcal{D}} \mid G)$. \vspace*{-0.5em} \subsection{Comparison with the exact posterior} \vspace*{-0.5em} \label{sec:comparison-exact-posterior} \begin{figure*}[t!] \centering \includestandalone[width=\linewidth]{figures/lingauss20} \caption{Bayesian structure learning of linear-Gaussian Bayesian networks with $d = 20$ nodes. Results for $\mathbb{E}$-SHD \& AUROC are aggregated over 25 randomly generated datasets ${\mathcal{D}}$, sampled from different (ground-truth) Bayesian networks. Results for $\log P(G, {\mathcal{D}}' \mid {\mathcal{D}})$ are given for a single dataset ${\mathcal{D}}$; the dashed line corresponds to the log-likelihood of the ground truth graph $G^{\star}$. For $\mathbb{E}$-SHD lower is better, and for AUROC and $\log P(G, {\mathcal{D}}' \mid {\mathcal{D}})$ higher is better. Labels: B-PC = Bootstrap-PC, B-GES = Bootstrap-GES, BCD = BCD Nets, GFN = DAG-GFlowNet.} \label{fig:lingauss20} \end{figure*} In order to measure the quality of the posterior approximation returned by DAG-GFlowNet, we want to compare it with the exact posterior distribution $P(G\mid {\mathcal{D}})$. However, the latter requires an exhaustive enumeration of all possible DAGs, which is only feasible for graphs with no more than $5$ nodes. Therefore, we sampled $N=100$ datapoints from a randomly generated (under an Erd\H{o}s-R\'{e}nyi model; \citealp{erdos1960ergraphs}) linear-Gaussian Bayesian network over $d=5$ variables. We used the BGe score to compute the reward $R(G) = P(G)P({\mathcal{D}} \mid G)$. The exact posterior distribution $P(G\mid {\mathcal{D}})$ is obtained by enumerating all $29,\!281$ possible DAGs over $5$ nodes and computing their respective rewards $R(G)$ (normalized to sum to $1$). We evaluated the quality of the approximation based on the probability of various structural features. For example, using samples $\{G_{1}, G_{2}, \ldots, G_{n}\}$ from the posterior approximation, the marginal probability of an \emph{edge feature} $X_{i} \rightarrow X_{j}$ can be estimated with \begin{equation} P_{\theta}(X_{i} \rightarrow X_{j}\mid {\mathcal{D}}) \approx \frac{1}{n}\sum_{k=1}^{n} \mathbf{1}(X_{i} \rightarrow X_{j} \in G_{k}), \label{eq:edge-features} \end{equation} where $\mathbf{1}(\cdot)$ is the indicator function. For the exact posterior, we can obtain the posterior probability of the edge feature by simply marginalizing over $P(G\mid {\mathcal{D}})$. Similarly, we compute (or estimate) the marginal probability of a \emph{path feature} ${X_{i} \rightsquigarrow X_{j}}$, i.e. of a (directed) path existing from $X_{i}$ to $X_{j}$, and the probability of a \emph{Markov feature} ${X_{i} \sim_{M} X_{j}}$, i.e. of $X_{i}$ being in the Markov blanket of $X_{j}$ \citep{friedman2003ordermcmc}. These features are computed for all variables $X_{i}$ and $X_{j}$ in the Bayesian network. In \cref{fig:posterior-comparison}, we compare the probabilities of these features for both the exact posterior and the distribution induced by DAG-GFlowNet, where we repeated the experiment above with $20$ different (ground-truth) Bayesian networks. We observe that the probabilities of all structural features estimated by the GFlowNet are strongly correlated with the exact marginal probabilities. This shows that DAG-GFlowNet is capable of learning a very accurate approximation of the posterior distribution over graphs $P(G\mid {\mathcal{D}})$. \vspace*{-1em} \subsection{Simulated data} \label{sec:simulated-data} We follow the experimental setup of \citet{zheng2018notears} \& \citet{lorch2021dibs}, and sample synthetic data from linear-Gaussian Bayesian networks with randomly generated structures. To show that DAG-GFlowNet can effectively approximate the posterior distribution over larger graphs, we experiment with Bayesian networks of size $d = 20$ (and $d = 50$, see \cref{app:simulated-data-lingauss50}). Similar to \cref{sec:comparison-exact-posterior}, the ground-truth graphs are sampled according to an Erd\H{o}s-R\'{e}nyi model, with $2d$ edges in expectation---a setting sometimes referred to as ER2 \citep{cundy2021bcdnets}. For each experiment, we sampled a dataset ${\mathcal{D}}$ of $N = 100$ observations, and we used the BGe score to compute $R(G)$. Since we have access to the ground-truth graph $G^{\star}$ that generated ${\mathcal{D}}$, we evaluate the performance of each algorithm with the \emph{expected structural Hamming distance} ($\mathbb{E}$-SHD) to $G^{\star}$ over the posterior approximation; a detailed definition is available in \cref{app:details-metrics}. We also compute the \emph{area under the ROC curve} \citep[AUROC;][]{husmeier2003auroc} for the edge features as defined in \cref{eq:edge-features}, compared to the edges of $G^{\star}$. Finally, we compute the joint log-likelihood $\log P(G, {\mathcal{D}}'\mid {\mathcal{D}})$ on a held-out dataset ${\mathcal{D}}'$; we chose this metric over the log-predictive likelihood $\log P({\mathcal{D}}'\mid {\mathcal{D}})$, as proposed by \citet{eaton2007bayesian}, to study the effect of the posterior approximation $P(G \mid {\mathcal{D}})$. The results on graphs with $d = 20$ nodes are shown in \cref{fig:lingauss20}. We observe that both in terms of $\mathbb{E}$-SHD \& AUROC, DAG-GFlowNet, is competitive against all other methods, in particular those based on MCMC, and this does not come at a cost in terms of its predictive capacity on held-out data. In particular, we can see that the distribution induced by DAG-GFlowNet yields a predictive log-likelihood concentrated near the log-likelihood of the ground-truth DAG $G^{\star}$. \subsection{Application: Flow Cytometry Data} \label{sec:application-flow-cytometry-data} We also evaluated DAG-GFlowNet on real-world flow cytometry data \citep{sachs2005causal} to learn protein signaling pathways. The data consists of continuous measurements of $d = 11$ phosphoproteins in individual T-cells. Out of all the measurements, we selected the $N = 853$ observations corresponding to the first experimental condition of \citet{sachs2005causal} as our dataset ${\mathcal{D}}$. Following prior work on structure learning, we used the DAG inferred by \citet{sachs2005causal}, containing $d = 11$ nodes and $17$ edges, as our graph of reference (ground-truth). However, it should be noted that this ``consensus graph'' may not represent a realistic and complete description of the system being modeled here \citep{mooij2020jci}. We standardized the data, and used the BGe score to compute $R(G)$. \begin{table}[ht] \centering \caption{Learning protein signaling pathways from flow cytometry data \citep{sachs2005causal}. All results include a $95\%$ confidence interval estimated with bootstrap resampling.} \label{tab:sachs-continuous} \begin{adjustbox}{center, scale=0.9} \begin{tabular}{lccc} \toprule & $\mathbb{E}$-\#~Edges & $\mathbb{E}$-SHD & AUROC \\ \midrule MC\textsuperscript{3} & $10.96 \pm 0.09$ & $22.66 \pm 0.11$ & $0.508$ \\ Gadget & $10.59 \pm 0.09$ & $21.77 \pm 0.10$ & $0.479$ \\ Bootstrap GES & $11.11 \pm 0.09$ & $23.07 \pm 0.11$ & $\mathbf{0.548}$ \\ Bootstrap PC & $\phantom{1}7.83 \pm 0.04$ & $20.65 \pm 0.06$ & $0.520$ \\ DiBS & $12.62 \pm 0.16$ & $23.32 \pm 0.14$ & $0.518$ \\ BCD Nets & $\phantom{1}4.14 \pm 0.09$ & $\mathbf{18.14 \pm 0.09}$ & $0.510$ \\ \midrule DAG-GFlowNet & $11.25 \pm 0.09$ & $22.88 \pm 0.10$ & $0.541$ \\ \bottomrule \end{tabular} \end{adjustbox} \end{table} In \cref{tab:sachs-continuous}, we compare the expected SHD and the AUROC obtained with DAG-GFlowNet and other approaches. While BCD Nets and Bootstrap PC have a smaller $\mathbb{E}$-SHD, suggesting that the distribution is concentrated closer to the consensus graph, in reality they tend to be more conservative and sample graphs with fewer edges. Overall, DAG-GFlowNet offers a good trade-off between performance (as measured by the $\mathbb{E}$-SHD and the AUROC), and getting a distribution that assigns higher probability to DAGs with more edges. We also observed that $1.50\%$ of the graphs sampled with DiBS contained a cycle. Beyond these metrics, we would like to test if the advantages of Bayesian structure learning are also reflected in the distribution induced by DAG-GFlowNet. In particular, we want to study (1) if this distribution covers multiple high-scoring DAGs, instead of being peaked at a single most likely graph, and (2) if the GFlowNet can sample a variety of DAGs from the same Markov equivalence class (MEC), showing the inherent uncertainty over equivalent graphs. In \cref{fig:sachs-comparison-mcmc}, we visualize the MECs of the graphs sampled with DAG-GFlowNet, and two methods based on MCMC (MC\textsuperscript{3} and Gadget); other baselines were excluded for clarity. The size of each point represents the number of unique DAGs in the corresponding MEC. We observe that DAG-GFlowNet largely follows the behavior of MCMC: the distribution does not collapse to a single most-likely DAG, and covers multiple MECs. Moreover, the GFlowNet is also capable of sampling different equivalent DAGs (corresponding to larger points), showing again that the distribution does not collapse to a single representative of the MECs with higher marginal probability. We also observe that the maximum a posteriori MEC found by DAG-GFlowNet reaches a higher score than the one found with Gadget, but a lower score than MC\textsuperscript{3}; as a point of reference, the score of the best MEC obtained with GES \citep{chickering2002ges} is $-10,\!716.12$. \subsection{Application: Interventional data} \label{sec:application-interventional-data} \begin{figure}[t!] \centering \includestandalone[width=\linewidth]{figures/sachs-comparison/comparison_mcmc} \caption{Coverage of the posterior approximations learned on flow cytometry data \citep{sachs2005causal}. Each point corresponds to a sampled Markov equivalence class, and its size represents the number of different DAGs (in the equivalence class) sampled from the posterior approximation.} \label{fig:sachs-comparison-mcmc} \end{figure} In addition to the observational data we used in \cref{sec:application-flow-cytometry-data}, \citet{sachs2005causal} also provided flow cytometry data under different experimental conditions, where the T-cells were perturbed with some reagents; this effectively corresponds to interventional data \citep{pearl2009causality}. Although a molecular intervention may be imperfect and affect multiple proteins \citep{eaton2007belief}, we assume here that these interventions are perfect, and the intervention targets are known. We used a discretized dataset of $N = 5,\!400$ samples from $9$ experimental conditions---of which $6$ are interventions. We modified the BDe score to handle this mixture of observational and interventional data \citep{cooper1999interventional}. \begin{table}[ht] \centering \caption{Combining discrete interventional and observational flow cytometry data \citep{sachs2005causal}. ${}^{\star}$Result reported in~\citet{eaton2007belief}.} \label{tab:sachs-interventional} \begin{adjustbox}{center, scale=0.9} \begin{tabular}{lccc} \toprule & $\mathbb{E}$-\#~Edges & $\mathbb{E}$-SHD & AUROC \\ \midrule Exact posterior${}^{\star}$ & --- & --- & $\mathbf{0.816}$ \\ MC\textsuperscript{3} & $25.97 \pm 0.01$ & $\mathbf{25.08 \pm 0.02}$ & $0.665$ \\ \midrule DAG-GFlowNet & $30.66 \pm 0.04$ & $27.77 \pm 0.03$ & $0.700$ \\ \bottomrule \end{tabular} \end{adjustbox} \end{table} In \cref{tab:sachs-interventional}, we compare with \citet{eaton2007belief}, which compute the AUROC of the exact posterior using dynamic programming, therefore working as an upper bound for what a posterior approximation can achieve. They achieve this at the expense of computing only edge marginals, without providing access to a distribution over DAGs. We also use the modified BDe score with MC\textsuperscript{3}, which predicts sparser graphs with higher SHD than DAG-GFlowNet, but lower AUROC. Note that this setup is different from previous works which use continuous data instead \citep{brouillard2020differentiable,faria2022differentiable}. \section{Conclusion} \label{sec:conclusion} We have proposed a new method for Bayesian structure learning, based on a novel class of probabilistic models called GFlowNets, where the generation of a sample graph is treated as a sequential decision problem. We introduced a number of enhancements to the standard framework of GFlowNets, specifically designed for approximating a distribution over DAGs. In cases where the data is limited and measuring the epistemic uncertainty is critical, DAG-GFlowNet offers an effective solution to approximate the posterior distribution over DAGs $P(G \mid {\mathcal{D}})$. However, we also observed that in its current state, DAG-GFlowNet may suffer from some limitations, notably as the size of the dataset ${\mathcal{D}}$ increases; see \cref{app:limitations} for a discussion. While DAG-GFlownet operates on the space of DAGs directly, the structure of the GFlowNet may eventually be adapted to work with alternative representations of statistical dependencies in Bayesian networks, such as essential graphs for MECs \citep{chickering2002ges}. Moreover, although we have already shown that DAG-GFlowNet can approximate the posterior using a mixture of observational and interventional data, we will continue to study in future work its applications to causal discovery, especially in the context of learning the structure of models with latent variables. \makeatletter \ifUAI@accepted \makeatother \section*{Acknowledgements} \label{sec:acknowledgements} We would like to thank Emmanuel Bengio, Paul Bertin, and Valentin Thomas for the useful discussions about the project, and Dinghuai Zhang, Kolya Malkin, and Xu Ji for their valuable feedback on the paper. This research was partially supported by the Canada CIFAR AI Chair Program and by Samsung Electronics Co., Ldt. Simon Lacoste-Julien is a CIFAR Associate Fellow in the Learning in Machines \& Brains program, Yoshua Bengio is a CIFAR Senior Fellow and Stefan Bauer is a CIFAR Azrieli Global Scholar. \fi
{'timestamp': '2022-03-01T02:53:07', 'yymm': '2202', 'arxiv_id': '2202.13903', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13903'}
arxiv
\section{Introduction} A \emph{cut} is a partition of the vertex set of a graph into two disjoint parts, and the \emph{maximum cut problem} (denoted by \textsc{MaxCut}, for short) aims to determine a cut with the maximum number of edges for which each endpoint is in a distinct part. The decision problem \textsc{MaxCut} is known to be NP-complete since the seventies~\cite{GJS76}, and only recently its restriction to interval graphs has been announced to be hard by Adhikary, Bose, Mukherjee, and Roy~\cite{ABMR20}. This settles a long-standing open problem from the {\it Ongoing Guide to NP-completeness} by David S. Johnson~\cite{J85}. In his column, David S. Johnson presented a two-page summary table, with a column for each of the ten most famous NP-complete graph problems, and a row for each of thirty selected graph class. Among those graph classes, special emphasis was given to subclasses of perfect graphs and of intersection graphs having broad algorithmic significance. The emphasis was on the restrictions themselves and how they affect the complexity of the considered NP-hard problems. The discussion had focus on the particularly fertile domain of graph theory, where the central open problem at that time was the recognition of perfect graphs. Many important graph classes are defined or can be characterized by a geometric intersection model. Two particularly well-studied examples are subclasses of perfect graphs: the classes of interval graphs and of permutation graphs~\cite{FIS85,10.5555/984029,Spinrad:1380920}. In their respective models, the intersecting objects are line segments in the plane, with different restrictions imposed on their positions. In interval graphs, each line segment must have its endpoints on a single line, while in permutation graphs, their endpoints must lie on two distinct parallel lines. Besides selecting the recognition of perfect graphs as the famous open problem, in his column, David S. Johnson selected only two others as open and may well be hard problems: Hamiltonian circuit restricted to permutation graphs and edge-coloring restricted to planar graphs. Today, we know that recognition of perfect graphs and Hamiltonian circuit restricted to permutation graphs can both be solved in polynomial time. On the other hand, edge-coloring restricted to planar graphs remains a challenging open problem. Please, refer to~\cite{FMSSarxiv} for an updated summary table. Surprisingly, after 35 years, the only new resolved entry for permutation graphs is Hamiltonian circuit. The present paper settles a long-standing open problem proposed by Johnson, by providing the first entry of Johnson's table for permutation graphs resolved as NP-complete. \begin{theorem}\label{theo:maxcut_permutation} {\sc MaxCut} is NP-complete on permutation graphs. \end{theorem} Our proof is based on Adhikary et al.'s construction used to prove the NP-completeness of {\sc MaxCut} on interval graphs~\cite{ABMR20}. It is interesting to notice that, among the problems selected by Johnson, \textsc{MaxCut} is the only one classified as NP-complete for interval graphs and for permutation graphs. Despite that, the interval graph constructed by Adhikary et al. is not a permutation graph, and our constructed permutation graph is not an interval graph. Thus, we leave as an open question the complexity of \textsc{MaxCut} on permutation interval graphs. Our paper is organized as follows. In Section~\ref{sec:preliminaries}, we present the basic concepts and notations. In Section~\ref{sec:grained}, we present the main gadget in the reduction of Adhikary et al.~\cite{ABMR20}, which also plays an important role in our reduction. In Section~\ref{sec:Adhikary}, we present the construction of Adhikary et al.~\cite{ABMR20} and show that it does not lead to a permutation graph. The presentation of their construction is also useful in Section~\ref{sec:proof}, where we finally present the proof of Theorem~\ref{theo:maxcut_permutation}. In Section~\ref{sec:conclusion}, we prove that our constructed permutation graph is not an interval graph, and propose the complexity of \textsc{MaxCut} on permutation interval graphs as an open problem. \subsection{Preliminaries}\label{sec:preliminaries} In this work, all graphs considered are simple. For missing definitions and notation of graph theory, we refer to~\cite{BM2008}. Let $G$ be a graph. We say that a subset $K\subseteq V(G)$ is a \emph{clique} if every two distinct vertices in $K$ are adjacent, and that a subset $S\subseteq V(G)$ is a \emph{stable set} if no two vertices in $S$ are adjacent. Let $X$ and $Y$ be two disjoint subsets of $V(G)$. We say that $X$ is \emph{complete} to $Y$ if every vertex in $X$ is adjacent to every vertex in $Y$, and that $X$ is \emph{anti-complete} to $Y$ if there are no edges between $X$ and $Y$. We let $E_G(X,Y)$ be the subset of $E(G)$ with an endpoint in $X$ and the other endpoint in $Y$. A \emph{cut} of $G$ is a partition of $V(G)$ into two parts $A, B \subseteq V(G)$, denoted by $[A, B]$; the edge set $E_G(A,B)$ is called the \emph{cut-set} of $G$ associated with $[A,B]$. For each two vertices $u,v \in V(G)$, we say that $u$ and $v$ \emph{are in a same part of $[A,B]$} if either $\{u,v\} \subseteq A$ or $\{u,v\} \subseteq B$; otherwise, we say that $u$ and $v$ \emph{are in opposite parts of $[A,B]$}. Denote by $\mathsf{mc}(G)$ the maximum size of a cut-set of $G$. The \textsc{MaxCut} problem has as input a graph $G$ and a positive integer $k$, and it asks whether $\mathsf{mc}(G) \geq k$. Let $\pi$ and $\pi'$ be two permutations of a same set, say $V$. A graph $G$ is called the \emph{intersection graph related to $\{\pi,\pi'\}$} if $V(G) = V$ and, for each two vertices $u, v \in V(G)$, $uv\in E(G)$ if and only if $u <_{\pi} v$ and $v <_{\pi'} u$. In this case, we also say that $\{\pi, \pi'\}$ is a \emph{permutation model} of $G$. A graph is a \emph{permutation graph} if it is the intersection graph related to a permutation model. Given two permutations $\pi$ and $\gamma$ of disjoint subsets $X$ and $Y$, respectively, we write $\pi\gamma$ to denote the permutation of $X\cup Y$ given by the \emph{concatenation} of $\pi$ with $\gamma$. Also, we write $\overleftarrow{\pi}$ to denote the reverse of the permutation $\pi$, that is, if $\pi = (v_1,\ldots,v_i)$, then $\overleftarrow{\pi} = (v_i,\ldots,v_1)$. In order to simplify the notation, given a set $Z$, we sometimes use the same symbol, $Z$, to denote also a chosen permutation of the elements of $Z$; in such cases, $\overleftarrow{Z}$ represents the reverse of the chosen permutation for $Z$. An \emph{interval model} is a finite multiset ${\cal M}$ of closed intervals of the real line. Let $G$ be a graph and ${\cal M}$ be an interval model. An \emph{${\cal M}$-representation} of $G$ is a bijection $\phi \colon V(G) \rightarrow {\cal M}$ such that, for every two distinct vertices $u, v \in V(G)$, we have that $uv \in E(G)$ if and only if $\phi(u) \cap \phi(v) \neq \emptyset$. If such an ${\cal M}$-representation exists, we say that ${\cal M}$ is an \emph{interval model of $G$} and that $G$ is an \emph{interval graph}. We write $i\in [n]$ to mean $i\in \{1, \ldots, n\}$. \section{Grained gadget}\label{sec:grained} In this section, we present the notion of \emph{grained gadgets}, which was defined in~\cite{FMOS21} as a generalization of the so-called \emph{$V$-gadgets} and \emph{$E$-gadgets}, these latter introduced by Adhikary et al.~\cite{ABMR20} in order to prove the NP-completeness of {\sc MaxCut} on interval graphs. Let $x$ and $y$ be positive integers. An \emph{$(x, y)$-grained gadget} is a split graph $H$ formed by a clique $K'\cup K''$ of size $2y$ and a stable set $S'\cup S''$ of size $2x$ with $K'$ being complete to $S'$, $K''$ being complete to $S''$, and satisfying $|K'| = |K''| = y$ and $|S'| = |S''| = x$. Figure~\ref{fig:interval_grained} depicts an interval representation of an $(x,y)$-grained gadget. One can readily verify that the intersection graph related to the pair of permutations $\{K'S'S''K'', S'\overleftarrow{K''}\overleftarrow{K'}S''\}$ (see Figure~\ref{fig:grained_permutations}) is an $(x,y)$-grained gadget. Thus, grained gadgets are interval graphs and permutation graphs. \begin{figure}[ht]\centering \includegraphics[scale=3.5]{grained_gadget_interval.pdf} \caption{Interval representation of an $(x,y)$-grained gadget~c.f.\cite{FMOS21}.}\label{fig:interval_grained} \end{figure} \begin{figure}[ht]\centering\captionsetup[subfigure]{justification=centering} \includegraphics[scale = 1.0]{perm_vertices.pdf} \caption{A permutation model of a grained gadget.}\label{fig:grained_permutations} \end{figure} Let $H$ be an $(x,y)$-grained gadget and $G$ be a supergraph of $H$. For each vertex $u \in V(G)\setminus V(H)$, we say that (see Figure~\ref{fig:intersection_types}): $u$ \emph{covers} $H$ if $V(H) \subseteq N_{G}(u)$; $u$ \emph{weakly intersects} $H$ if either $N_{G}(u) \cap V(H) = K'$ or $N_{G}(u) \cap V(H) = K''$; and that $u$ \emph{strongly intersects} $H$ if either $N_{G}(u) \cap V(H) = K' \cup S'$ or $N_{G}(u) \cap V(H) = K'' \cup S''$. Moreover, we say that $G$ \emph{respects the structure} of $H$ if, for each vertex $u \in V(G)\setminus V(H)$, either $N_{G}(u) \cap V(H) = \emptyset$ or $u$ satisfies one of the previous conditions. \begin{figure}[ht]\centering \begin{subfigure}[t]{0.19\textwidth}\centering \includegraphics[scale = 0.8]{l-covering.pdf} \caption{Covering intersection}\label{subfig:covering} \end{subfigure} \begin{subfigure}[t]{0.38\textwidth}\centering \includegraphics[scale = 0.8]{l-weakly1.pdf} \hspace{2.0ex} \includegraphics[scale = 0.8]{l-weakly2.pdf} \caption{Weak intersection}\label{subfig:weakly} \end{subfigure} \begin{subfigure}[t]{0.38\textwidth}\centering \includegraphics[scale = 0.8]{l-strongly1.pdf} \hspace{2.0ex} \includegraphics[scale = 0.8]{l-strongly2.pdf} \caption{Strong intersection}\label{subfig:strongly} \end{subfigure} \caption{Vertex $u \in V(G)\setminus V(H)$ (\protect\subref{subfig:covering}) covering $H$, (\protect\subref{subfig:weakly}) weakly intersecting $H$, and (\protect\subref{subfig:strongly}) strongly intersecting $H$. The set $K'\cup K''$ is a clique and the set $S'\cup S''$ is a stable set. A line between sets, or between $u$ and some set, means that all the edges occur. } \label{fig:intersection_types} \end{figure} The next lemma establishes the key property of grained gadgets with respect to the {\sc MaxCut} problem. Intuitively, it states that, for suitable values of $x$ and $y$, if $G$ is a supergraph that respects the structure of an $(x,y)$-grained gadget, then, in any maximum cut $[A, B]$ of $G$, the vertices belonging to $K' \cup S''$ are placed in a same part of $[A, B]$, opposite to the part containing the vertices belonging to $K'' \cup S'$. \begin{lemma}[\cite{FMOS20}]Let $x$ and $y$ be positive integers, $H$ be an $(x,y)$-grained gadget and $G$ be a supergraph that respects the structure of $H$. Also, let $[A, B]$ be a maximum cut of $G$, $t$ be the number of vertices in $V(G)\setminus V(H)$ adjacent to some vertex of $H$, $\ell$ be the number of vertices of $G$ adjacent to some vertex in $S'$, and $r$ be the number of vertices of $G$ adjacent to some vertex in $S''$. If $\ell$ and $r$ are odd, $y > 2t$ and $x > t + 2y$, then each of the following holds: \begin{enumerate} \item $S' \subseteq A$ and $K' \subseteq B$, or vice versa; \item $S'' \subseteq A$ and $K'' \subseteq B$, or vice versa; \item $K' \subseteq A$ and $K'' \subseteq B$, or vice versa. \end{enumerate} \label{lem:grainedGadgets} \end{lemma} In the remainder of the text, when a grained gadget $H$ is not clear in the context, we write $S'(H)$, $S''(H)$, $K'(H)$ and $K''(H)$ to denote the stable sets $S'$ and $S''$ and the cliques $K'$ and $K''$ of $H$, respectively. \section{Adhikary et al.'s reduction}\label{sec:Adhikary} In this section, we present the construction given by Adhikary et al.~\cite{ABMR20} of an interval graph that proves NP-completeness of {\sc MaxCut} in this class. As we see in Section~\ref{sec:proof}, the general idea behind their construction can also be used to obtain a permutation graph instead. Nevertheless, the question of whether their construction is also permutation might arise. We prove here that this is not the case. Given a cubic graph $G$, let $\pi_{V} = (v_1,v_2,\ldots,v_n)$ and $\pi_{E} = (e_1,e_2,\ldots,e_m)$ be arbitrary orderings of $V(G)$ and $E(G)$, respectively. Define the values: $q = 200n^3 + 1$, $p = 2q + 7n$, $q' = 10n^2 + 1$, and $p' = 2q' + 7n$. An interval graph $G'$ is defined through the construction of one of its interval models ${\cal M}$, described as follows (observe Figure~\ref{fig:intervalModel} to follow the construction): \begin{enumerate} \item Add to ${\cal M}$ a $(p,q)$-grained gadget ${\cal H}_i$ for each vertex $v_i \in V(G)$. These gadgets should be pairwise disjoint, with ${\cal H}_i$ appearing completely to the left of ${\cal H}_{i+1}$ for every $i\in [n-1]$; \item Add to ${\cal M}$ a $(p',q')$-grained gadget ${\cal E}_j$ for each edge $e_j \in E(G)$. Likewise, these gadgets should be pairwise disjoint, with ${\cal E}_j$ appearing completely to the left of ${\cal E}_{j+1}$ for every $j\in [m-1]$. Additionally, ${\cal E}_1$ appears completely to the right of ${\cal H}_n$, without intersecting it; \item Finally, for each edge $e_j = v_iv_{i'} \in E(G)$, with $i < i'$, add four intervals $L^1_{i,j}, L^2_{i,j}, L^1_{i',j}, L^2_{i',j}$, called \emph{link} intervals, such that: \begin{itemize} \item $L^1_{i,j}$ and $L^2_{i,j}$ (resp. $L^1_{i',j}$ and $L^2_{i',j}$) weakly intersect ${\cal H}_i$ (resp. ${\cal H}_{i'}$) to the right of ${\cal H}_i$ (resp. ${\cal H}_{i'}$); \item $L^1_{i,j}$ and $L^2_{i,j}$ (resp. $L^1_{i',j}$ and $L^2_{i',j}$) weakly intersect (resp. strongly intersect) ${\cal E}_j$ to the left of ${\cal E}_j$. \end{itemize} \end{enumerate} \begin{figure}[ht] \includegraphics[scale=1.0]{IntervalModel2.pdf}\centering \caption{Adhikary et al.'s interval model $\mathcal{M}$, with $e_1=v_1v_2$, $e_2=v_1v_n$, and $e_m=v_2v_n$.}\label{fig:intervalModel} \end{figure} As claimed, we show that the constructed graph $G'$ is not a permutation graph. This is because $G'$ contains the graph $\overline{X}_{34}$ depicted in Figure~\ref{subfig:forbidden_subgraph} as an induced subgraph, and such a graph is a forbidden subgraph for comparability graphs cf.~\cite{Gallai1967, ISGCI}, in turn a known superclass of permutation graphs. To see that this claim holds, observe Figure~\ref{subfig:forbidden_adhkary}. Given an edge $e_j = v_iv_{i'}\in E(G)$, with $i < i'$, it shows the intervals in the grained gadgets of $v_i$, $v_{i'}$ and $e_j$, as well as some link intervals related to $e_j$. The adjacencies can be easily checked to be as in the graph of Figure~\ref{subfig:forbidden_subgraph}. \begin{figure}[ht]\centering\captionsetup[subfigure]{justification=centering} \begin{subfigure}[t]{0.32\textwidth}\centering \includegraphics[scale = 1.0]{forbidden_comparability.pdf} \caption{}\label{subfig:forbidden_subgraph} \end{subfigure} \hspace{2.0ex} \begin{subfigure}[t]{0.55\textwidth}\centering \includegraphics[scale = 1.0]{forbidden_adhkary.pdf} \caption{}\label{subfig:forbidden_adhkary} \end{subfigure} \caption{\protect(\subref{subfig:forbidden_subgraph})~Forbidden induced subgraph $\overline{X}_{34}$ for comparability graphs~cf.\cite{ISGCI}. \protect(\subref{subfig:forbidden_adhkary})~$\overline{X}_{34}$ as an induced subgraph in Adhikary et al.'s construction.}\label{fig:forbidden} \end{figure} In the next section, we show that a modification of Adhikary et al.'s construction gives us the desired permutation graph. \section{Our reduction} \label{sec:proof} Consider a cubic graph $G$, and orders on its vertex and edge sets, $\pi_{V} = (v_1,v_2,\ldots,v_n)$ and $\pi_{E} = (e_1,e_2,\ldots,e_m)$, respectively. The values of $p,q,p',q'$ are not the same as in Section~\ref{sec:Adhikary} and are presented later. Again, for each vertex $v_i$, create a $(p,q)$-grained gadget, ${\cal H}_i$, and for each edge $e_j$, create a $(p',q')$-grained gadget ${\cal E}_j$. For simplicity, denote the sets $S'({\cal H}_i)$, $S''({\cal H}_i)$, $K'({\cal H}_i)$ and $K''({\cal H}_i)$ by $S'_i,S''_i,K'_i,K''_i$, respectively. Similarly, denote the sets $S'({\cal E}_j)$, $S''({\cal E}_j)$, $K'({\cal E}_j)$ and $K''({\cal E}_j)$ by $S^{'e}_j,S^{''e}_j,K^{'e}_j,K^{''e}_j$, respectively. Recall that for each $i \in [n]$, the permutation model of ${\cal H}_i$ consists of the pair of permutations $\{\pi^1_i, \pi^2_i\}$ where $\pi^1_i = K_i' S_i' S_i'' K_i''$ and $\pi^2_i = S'_i \overleftarrow{K''_i} \overleftarrow{K'_i} S''_i$. Analogously, for each $j \in [m]$, the permutation model of ${\cal E}_j$ consists of the pair of permutations $\{\gamma^1_j, \gamma^2_j\}$ where $\gamma^1_j = K^{'e}_j S^{'e}_j S^{''e}_j K^{''e}_j$ and $\gamma^2_j = S^{'e}_j \overleftarrow{K^{''e}_j} \overleftarrow{K^{'e}_j} S^{''e}_j$. Now, for each edge $e_j = v_iv_{i'}$, with $i < i'$, add four new vertices $L^1_{i,j}, L^2_{i,j}, L^1_{i',j}, L^2_{i',j}$, called \emph{link} vertices. In what follows, we modify some of the grained gadget permutations in order to make $L^1_{i,j},L^2_{i,j}$ (resp. $L^1_{i',j},L^2_{i',j}$) weakly intersect ${\cal H}_i$ (resp. ${\cal H}_{i'}$) and strongly intersect (resp. weakly intersect) ${\cal E}_j$. If $v_i$ is incident to edges $j_1,j_2,j_3$, with $j_1<j_2<j_3$, then modify one of the permutations defining ${\cal H}_i$ to include the link vertices related to $v_i$ as follows: \[\pi^1_i = K'_iS'_iS''_iC_iK''_i,\] where $C_i$ denotes the permutation $L^1_{i,j_1}L^2_{i,j_1}L^1_{i,j_2}L^2_{i,j_2}L^1_{i,j_3}L^2_{i,j_3}$. Similarly, for each edge $e_j = v_iv_{i'}$, $i<i'$, we modify one of the permutations defining ${\cal E}_j$ to include the link vertices related to $e_j$ as follows: \[\gamma^1_j = K^{'e}_jL^2_{i',j}L^1_{i',j}S^{'e}_jL^2_{i,j}L^1_{i,j}S^{''e}_jK^{''e}_j.\] We do not modify $\pi^2_i$ and $\gamma^2_j$, and keep denoting by $\pi^2_i$ the permutation $S'_i\overleftarrow{K''}_i\overleftarrow{K'}_iS''_i$, and by $\gamma^2_j$ the permutation $S^{'e}_j\overleftarrow{K^{''e}}_j\overleftarrow{K^{'e}}_jS^{''e}_j$. Finally, let $G'$ be the permutation graph related to $\{\Pi,\Pi'\}$, where: \[\Pi = \pi^1_1\ldots\pi^1_n\gamma^2_1,\ldots,\gamma^2_m\mbox{, and }\] \[\Pi' = \pi^2_1\ldots\pi^2_n\gamma^1_1,\ldots,\gamma^1_m.\] Figure~\ref{fig:permutation_model} illustrates our permutation model $\{\Pi,\Pi'\}$, focusing on the vertex grained gadgets $\mathcal{H}_{i}$ and $\mathcal{H}_{i'}$, the edge grained gadget $\mathcal{E}_{j}$, and the link vertices $L_{i,j}^{1}, L_{i,j}^{2}$ and $L_{i',j}^{1}, L_{i',j}^{2}$ related to an edge $e_j = v_{i}v_{i'}$, with $i < i'$. \begin{figure}[htb]\centering \includegraphics[scale=0.75]{permutationModel3.pdf} \caption{Vertex and edge grained gadgets, and link vertices related to an edge $e_j = v_{i}v_{i'}$, with $i < i'$, in our permutation model $\{\Pi,\Pi'\}$.}\label{fig:permutation_model} \end{figure} We remark that the main difference of our permutation graph from the Adhikary et al.'s interval graph is the fact that, in Adhikary et al.'s interval graph, the link vertices form a clique, whereas, as we show in Section~\ref{sec:conclusion}, some link vertices are not adjacent in our permutation graph. Additionally, for an edge $e_j = v_iv_{i'} \in E(G)$, with $i < i'$, the link vertices $L_{i,j}^{1}, L_{i,j}^{2}$ (resp. $L_{i',j}^{1}, L_{i' ,j}^{2}$) weakly intersect (resp. strongly intersect) $\mathcal{E}_j$ in Adhikary et al.'s interval graph, whereas in our permutation graph the link vertices $L_{i,j}^{1}, L_{i,j}^{2}$ (resp. $L_{i',j}^{1}, L_{i' ,j}^{2}$) strongly intersect (resp. weakly intersect) $\mathcal{E}_j$. Before our proof, we make some observations about the constructed graph in order to improve the proof's readability. Note that, for each link vertex $L$ and grained gadget $H$, either the relative order between $L$ and $V(H)$ in $\Pi$ is the reverse of their relative order in $\Pi'$, in which case $L$ is complete to $V(H)$, or the relative order is the same in both $\Pi$ and $\Pi'$, in which case $L$ is anti-complete to $V(H)$, or $L$ is related to $H$ according to one of the ways described below. \begin{itemize} \item $L \in \{L^1_{i,j},L^2_{i,j}\}$ and $H = {\cal H}_i$: in this case only the relative orders between $L$ and $K''_i$ are reversed in $\Pi$ and $\Pi'$, i.e., $L$ is complete to $K''_i$ and anti-complete to $V({\cal H}_i)\setminus K''_i$; \item $L\in \{L^1_{i,j},L^2_{i,j}\}$ and $H = {\cal E}_j$, with $e_j = v_iv_{i'}$, $i<i'$: in this case the relative orders between $L$ and $K^{'e}_j\cup S^{'e}_j$ are reversed in $\Pi$ and $\Pi'$, i.e., $L$ is complete to $K^{'e}_j\cup S^{'e}_j$ and anti-complete to $V({\cal E}_j)\setminus (K^{'e}_j\cup S^{'e}_j)$; or \item $L\in \{L^1_{i',j},L^2_{i',j}\}$ and $H = {\cal E}_j$, with $e_j = v_iv_{i'}$, $i<i'$: in this case only the relative orders between $L$ and $K^{'e}_j$ are reversed in $\Pi$ and $\Pi'$, i.e., $L$ is complete to $K^{'e}_j$ and anti-complete to $V({\cal E}_j)\setminus K^{'e}_j$. \end{itemize} \begin{proof}[\bf Proof of Theorem~\ref{theo:maxcut_permutation}] Consider the reduction graph $G'$ and its permutation model $\{\Pi,\Pi'\}$ as previously defined. For each $e_j = v_iv_{i'} \in E(G)$, let $$L(e_j) = \{L^1_{i,j}, L^2_{i,j},L^1_{i',j},L^2_{i',j}\}\text{;}$$ and for each $v_i\in V(G)$, let $$L(v_i) = \{L^1_{i,j},L^2_{i,j}\mid e_j\mbox{ is incident to }v_i\}\text{.}$$ Also, denote the set of link vertices by ${\cal L}$, i.e. ${\cal L} = \bigcup_{j=1}^m L(e_j)$. We postpone the assignment of the actual values for $p,q,p',q'$ and, in addition to the conditions necessary for the application of Lemma~\ref{lem:grainedGadgets}, we also ask that $q>6n+p'$ and $p'>2q'>9n^2$. In what follows, we prove that there exists a bijective relation $f$ between the maximum cuts of the input graph $G$ and the maximum cuts of our permutation graph $G'$. Then, we prove that, for each maximum cut $[X,Y]$ of $G$, $$|E_G(X,Y)|\ge k \;\text{ if and only if }\; |E_{G'}(A,B)|\ge \phi(n,m,k)\text{,}$$ where $[A,B] = f(X,Y)$ and $\phi$ is a well-defined function. Theorem~\ref{theo:maxcut_permutation} immediately follows. Let $[A,B]$ be a maximum cut of $G'$. In order to define $f$, we first prove some properties relating the partitioning of vertex and edge grained gadgets of $G'$ in $[A,B]$ with the partitioning of the link vertices of $G'$ in $[A,B]$. More specifically, we prove that the two following properties hold: \begin{enumerate} \item For each vertex $v_i \in V(G)$, if $K''_{i} \subseteq A$, then $\{L_{i,j}^{1}, L_{i,j}^{2}\} \subseteq B$ for each edge $e_j \in E(G)$, with $e_j = v_iv_{i'}$ and $i < i'$;\label{item:first_property} \item For each edge $e_j \in E(G)$, with $e_j = v_iv_{i'}$ and $i < i'$, if $\{L_{i,j}^{1}, L_{i,j}^{2}\} \subseteq B$, then $S^{'e}_{j} \subseteq A$.\label{item:second_property} \end{enumerate} \emph{Proof of Property \ref{item:first_property}}. Let $v_i\in V(G)$ and suppose that $K''_{i} \subseteq A$. For the sake of contradiction, suppose that there exists a link vertex $L\in L(v_i)\cap A$. Then, let $[A',B']$ be the cut obtained from $[A,B]$ by setting $A' = A\setminus\{L\}$ and $B' = B\cup\{L\}$. Observe that there is a loss of at most $\lvert{\cal L}\rvert+\max\{p',q'\} = \lvert{\cal L}\rvert+p'$ edges between $L$ and ${\cal L}$, and between $L$ and the vertices of the edge grained gadget related to $L$, say $\mathcal{E}_j$, since $K^{'e}_{j}$ and $S^{'e}_{j}$ are always in opposite parts of the cut. On the other hand we gain all the edges between $L$ and the vertices in $K''_i$. Therefore, we get an increase of the cut-set of at least $q$ edges, and a decrease of less than $|{\cal L}| + \max\{p',q'\} = 6n+p'$ edges. It follows from the hypothesis $q > 6n + p'$ that $|E_{G'}(A',B')|$ is bigger than $|E_{G'}(A,B)|$, contradicting the maximality of $[A,B]$. \emph{Proof of Property \ref{item:second_property}}. Consider an edge $e_j\in E(G)$, with $e_j=v_iv_{i'}$ and $i<i'$, and suppose that $\{L_{i,j}^{1}, L_{i,j}^{2}\} \subseteq B$. Observe that, because the relative orders among the edge and vertex grained gadgets themselves are the same in $\Pi$ and $\Pi'$, there are no edges between ${\cal E}_j$ and any other grained gadgets of $G'$, i.e., the only vertices outside of ${\cal E}_j$ that can be adjacent to the vertices of ${\cal E}_j$ are those in ${\cal L}$. Moreover, Lemma~\ref{lem:grainedGadgets} tells us that the vertices belonging to $K^{'e}_{j} \cup S^{''e}_{j}$ are placed in a same part of $[A,B]$, opposite to the part containing the vertices belonging to $K^{''e}_{j} \cup S^{'e}_{j}$. More formally, either $K^{'e}_{j}\cup S^{''e}_{j}\subseteq B$ and $K^{''e}_{j}\cup S^{'e}_{j}\subseteq A$, or $K^{'e}_{j}\cup S^{''e}_{j}\subseteq A$ and $K^{''e}_{j}\cup S^{'e}_{j}\subseteq B$. As a result, switching the vertices of ${\cal E}_j$ of part of the cut does not change, and therefore cannot decrease, the number of edges between the vertices of ${\cal E}_j$ and the vertices belonging to ${\cal L}\setminus L(e_j)$ in the cut-set. Consequently, if $S^{'e}_{j} \subseteq A$, then we obtain that there are at least $2p'$ edges in the cut-set that are incident to vertices of $\mathcal{E}_j$; these are the edges between $L^1_{i,j},L^2_{i,j}$ and the vertices belonging to $S^{'e}_j$. On the other hand, if $S^{'e}_{j} \subseteq B$, then we obtain that there are at most $4q'$ edges in the cut-set that are incident to vertices of $\mathcal{E}_j$; these are the edges between the vertices belonging to $L(e_j)$ and the vertices belonging to $K^{'e}_j$. Therefore, since $p'>2q'$, we get that $S^{'e}_{j} \subseteq A$ as we wanted to prove. \vspace{2.0ex} We are now ready to prove the existence of the bijective relation $f$. For each maximum cut $[X,Y]$ of $G$, let $f(X,Y)$ be the cut $[A,B]$ of $G'$ defined as follows: \begin{itemize} \item For each vertex $v_i\in V(G)$, if $v_i\in X$, then add $K'_i\cup S''_i\cup L(v_i)$ to $A$ and $K''_i\cup S'_i$ to $B$; do the opposite otherwise. \item For each $e_j\in E(G)$, with $e_{j} = v_iv_{i'}$ and $i<i'$, if $L^1_{i,j}\in A$, then add $K^{'e}_j\cup S^{''e}_j$ to $A$ and $K^{''e}_j\cup S^{'e}_j$ to $B$; and do the opposite otherwise. \end{itemize} Based on Properties~\ref{item:first_property} and~\ref{item:second_property}, one can readily verify that $f$ is well-defined and is a bijective relation, as desired. \vspace{2.0ex} Now, we count the number of edges in $E_{G'}(A,B)$ as a function of $n$, $m$, $p$, $q$, $p'$, $q'$ and of the size of the cut-set $E_G(X,Y)$. First, consider $v_i\in V(G)$. By construction, we know that there are $2pq+q^2$ edges in the cut-set between the vertices of ${\cal H}_i$. Additionally, there are exactly $6$ link vertices weakly intersecting ${\cal H}_i$, while all other link vertices are either complete or anti-complete to $V({\cal H}_i)$. Observe also that the number of link vertices complete to $V({\cal H}_i)$ is exactly equal to $6(i-1)$; these are the link vertices related to $\{v_1,\ldots,v_{i-1}\}$. This gives us a total of $6[q+(i-1)(p+q)]$ edges between the vertices of ${\cal H}_i$ and the vertices belonging to ${\cal L}$ in the cut-set. Summing up these values for every $v_{i} \in V(G)$, we get a total of \[\alpha_1 = n[2pq+q^2+6q] + 6\sum_{i=1}^{n}\left((i-1)(p+q)\right) = n[2pq+q^2 + 6q + 3(p+q)(n-1)]\] edges in the cut-set $E_{G'}(A,B)$ incident to vertex grained gadgets. Now, let $e_j \in E(G)$, with $e_j = v_iv_{i'}$ and $i<i'$. By construction, we know that there are $2p'q'+(q')^2$ edges of the cut-set between vertices of ${\cal E}_j$, and $2p'$ edges of the cut-set between $L^1_{i,j},L^2_{i,j}$ and the vertices of ${\cal E}_j$. Additionally, note that there are exactly $4(m-j)$ link vertices that cover and, therefore, are complete to ${\cal E}_j$; these are the link vertices related to $\{e_{j+1}, \ldots, e_{m}\}$. This gives us a total of $4(m-j)(p'+q')$ edges between the vertices of ${\cal E}_j$ and the vertices belonging to ${\cal L}\setminus L(e_j)$. Finally, suppose without loss of generality that $L^1_{i,j}\in A$ (the count is analogous if it is in $B$). If $v_{i'}\in X$, then we know that $\{L^1_{i',j},L^2_{i',j}\}\subseteq A$ and hence there are no edges in the cut-set between vertices $L^1_{i',j},L^2_{i',j}$ and the vertices of ${\cal E}_j$. Otherwise, observe that it follows that $e_j\in E_{G}(X,Y)$ and $\{L^1_{i',j},L^2_{i',j}\}\subseteq B$, and hence we get additional $2q'$ edges in the cut-set; these additional edges are between the link vertices $L^1_{i',j},L^2_{i',j}$ and the vertices belonging to $K^{'e}_{j}$. Summing up these values for every $e_j \in E(G)$, we get a total of $\alpha_2+2q'|E(A,B)|$ edges in the cut-set $E_{G'}(A,B)$ incident to edge grained gadgets, where \[\begin{array}{rl}\alpha_2 & = m[2p'q'+(q')^2+2p'] + \sum_{j=1}^m \left(4(m-j)(p'+q')\right)\\ & = m[2p'q'+(q')^2 + 2p' + 2(p'+q')(m-1)].\end{array}\] Finally, observe that there are at most $|A\cap {\cal L}|\cdot |B\cap {\cal L}|$ edges of the cut-set between link vertices. Note also that $|A\cap {\cal L}| = 6|X|$ since each vertex in $X$ is related to 6 link vertices, which are all placed in $A$. Similarly, we have $|B\cap {\cal L}| = 6|Y|$. This gives us at most $36|X|\cdot|Y|\le 9n^2$ edges in the cut-set between link vertices. Putting everything together, we get: \[\alpha_1+\alpha_2+2q'|E_{G}(X,Y)| \le |E_{G'}(A,B)|\le \alpha_1+\alpha_2+2q'|E_{G}(X,Y)|+9n^2.\] By setting $\phi(n,m,k)$ to $\alpha_1+\alpha_2+2q'k$, and knowing that $p,q,p',q'$ will be chosen as functions of $n$ and $m$, we want to prove, as stated in the beginning, that $|E_{G}(X,Y)|\ge k$ if and only if $|E_{G'}(A,B)|\ge \phi(n,m,k)$. If $|E_{G}(X,Y)|\ge k$, then the first inequality gives us that $|E_{G'}(X,Y)|\ge \alpha_1+\alpha_2+2q'k = \phi(n,m,k)$. On the other hand, if $|E_{G'}(A,B)| \ge \phi(n,m,k) = \alpha_1+\alpha_2+2q'k$, then the second inequality gives us that $|E_{G}(X,Y)|\ge k - 9n^2/2q'$. Because we assume that $2q'>9n^2$, it follows that $k - 9n^2/2q' > k-1$ and hence $|E_{G}(X,Y)|\ge k$. It only remains to set the values of $p,q,p',q'$. Observe that: \begin{itemize} \item For every grained gadget $H$, the total number of vertices in $V(G')\setminus H$ adjacent to $H$ is at most $6n$ (these are exactly the link vertices). \item For every vertex grained gadget $H$, the total number of vertices adjacent to some vertex $u\in S'(H)$ is exactly $q+2h$, for some positive integer $h$ (this is because the number of link vertices adjacent to the vertices in $S'(H)$ is always even). The same holds for the number of vertices adjacent to the vertices in $S''(H)$. We then get that the parity of $\ell$ and $r$ in the conditions of Lemma~\ref{lem:grainedGadgets} applied to $H$ depends only on the parity of $q$. \item Similarly, if $H$ is an edge grained gadget, then the parity of the total number of vertices adjacent to some $u\in S'(H)\cup S''(H)$ is equal to the parity of $q'$. \end{itemize} Therefore, the necessary conditions of Lemma~\ref{lem:grainedGadgets} translate to: $q > 6n$ and $q' > 6n$; $p > 2q + 6n$ and $p' > 2q' + 6n$; and $q$ and $q'$ are odd. Additionally, we need to ensure: $q>6n+p'$ and $p'>2q'>9n^2$. Hence, consider: \begin{itemize} \item $q'=5n^2+1$; \item $p' = 11n^2+6n$; \item $q = 12n^2+12n +1$; \item $p = 25n^2 + 30n$. \end{itemize} Since $n \geq 4$, one can verify that the values described above satisfy all the required conditions. This, therefore, concludes the proof of Theorem~\ref{theo:maxcut_permutation}. \end{proof} \section{\textsc{MaxCut} on permutation interval graphs is an open problem}\label{sec:conclusion} In this paper, we have presented a proof of NP-completeness for the \textsc{MaxCut} problem when constrained to permutation graphs. Surprisingly enough, we found that the main gadget in the reduction recently presented by Adhikary et al.~\cite{ABMR20} for interval graphs is also a permutation graph. Additionally, in Section~\ref{sec:Adhikary}, we have seen that being permutation is not a property that holds for the full construction of Adhikary et al.~\cite{ABMR20}. On the other hand, since the grained gadgets play an important role in our reduction too, one could wonder whether our construction instead is in the intersection between interval and permutation graphs. The answer to that is no as we argue next. Let $G$ be a cubic graph, and consider arbitrary orderings of $V(G)$ and $E(G)$, $(v_1,\ldots, v_n)$ and $(e_1,\ldots, e_m)$, respectively. Let $j_1,j_2,j_3$ be the indices of the edges incident to $v_1$, with $j_1 < j_2 < j_3$. Also, let $v_i$ be the other endpoint of $e_{j_2}$. We present a $C_4$ in $G'$, the graph constructed in Section~\ref{sec:proof}; it thus follows that $G'$ is not chordal, and hence also not interval~\cite{10.5555/984029}. Observe Figure~\ref{fig:c4} to follow our argument. Let $a$ be equal to $L^1_{1,j_1}$, $b$ be any vertex in $K''_i$, $c$ be equal to $L^1_{i,j_2}$, and $d$ be any vertex in $K^{'e}_{j_1}$. Since $j_1 < j_2$ and $1 < i$, we know that the relative order between $a$ and $c$ in $\Pi$ is the same as in $\Pi'$; hence $ac\notin E(G')$. Also, the relative order in $\Pi$ between $a$ and any vertex of ${\cal H}_i$ is reversed in $\Pi'$, the same holds between $c$ and any vertex belonging to $K''_i$; hence $\{ab,bc\}\subseteq E(G')$. Similarly, the relative order between $a$ and any vertex belonging to $K^{'e}_{j_1}$ in $\Pi$ is reversed in $\Pi'$, and the same holds between $c$ and any vertex of ${\cal E}_{j_1}$; hence $\{ad,cd\}\subseteq E(G')$. Finally, since $j_1 < j_2$, the relative order between $b$ and $d$ in $\Pi$ is the same as in $\Pi'$, and therefore $bd\notin E(G')$, thus finishing our argument. \begin{figure}[ht]\centering \includegraphics[scale=1.0]{permutationWithC4.pdf} \caption{Existence of a $C_4=(a,b,c,d)$ as an induced subgraph in our permutation graph.}\label{fig:c4} \end{figure} The previous paragraph tells us that for any chosen orderings of $V(G)$ and $E(G)$, the graph constructed in Section~\ref{sec:proof} contains a $C_4$. Since it is known that the class of $C_4$-free co-comparability graphs is precisely the class of interval graphs~\cite{Gilmore1964}, and that the class of permutation graphs is equal to the class of comparability co-comparability graphs~\cite{Pnueli1971TransitiveOO}, we get that interval permutation graphs are exactly the class of $C_4$-free permutation graphs. A good question is whether there is a construction that produces a permutation graph that is also $C_4$-free (and hence interval). Up to our knowledge, the largest class in the intersection of permutation and interval graphs for which the complexity is known is the class of the threshold graphs, on which \textsc{MaxCut} is polynomial-time solvable thanks to the algorithm given for cographs, a subclass of permutation graphs that is a superclass of threshold graphs~\cite{bodlaender1994}. \bibliographystyle{abbrv}
{'timestamp': '2022-03-01T02:57:12', 'yymm': '2202', 'arxiv_id': '2202.13955', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13955'}
arxiv
\section{Acknowledgments} \label{sec:acknowledgments} \section{Appendix} \label{sec:appendix} \begin{figure*}[htb!] \centering \centering \includegraphics[width=0.49\linewidth]{figs/clf_results_good_and_bad.pdf} \vspace{-0.02\textwidth} \caption{Examples of Image+AD model's disease classification predictions (Pred) compared with the known disease (GT) for NO, EM, HZ, and TC.} \label{fig:model_clf_examples} \end{figure*} \begin{figure}[tb] \centering \begin{subfigure}{0.49\textwidth} \includegraphics[width=\linewidth, trim=0cm 0.18cm 0cm 0cm, clip]{figs/seg_test_ita_distribution.pdf} \caption{Segmentation} \label{fig:seg_test_ita_distribution} \end{subfigure} \begin{subfigure}{0.49\textwidth} \includegraphics[width=\linewidth, trim=3.8cm 8cm 4.1cm 9.1cm, clip]{figs/clf_test_ita_distribution.pdf} \caption{Classification} \label{fig:clf_test_ita_distribution} \end{subfigure} \caption{Test ITA distributions for the (a) segmentation and (b) classification datasets. Predicted (pred) distributions are indicated in orange and known (GT), where available, are indicated in green.} \label{fig:dataset_ita_distributions} \vspace{-0.2in} \end{figure} \begin{equation} CAI_{\alpha} = \alpha (acc_{gap}^b - acc_{gap}^d) + (1 - \alpha) (acc^d - acc^b). \end{equation} $CAI_{\alpha}: $ Accuracy fairness metric from~\cite{paul2020TARA}. $\alpha:$ Hyperparameter to balance the importance of a reduction in the accuracy gap and an improvement in accuracy between the baseline $acc^b$ and debiased $acc^d$ methods. $acc_{gap}^b := \lvert acc_{ls}^b - acc_{ds}^b \rvert:$ Baseline accuracy gap between accuracy on ls and ds samples. $acc_{gap}^d := \lvert acc_{ls}^d - acc_{ds}^d \rvert:$ Debiased accuracy gap between accuracy on ls and ds samples. \begin{equation} CAUCI_{\alpha} = \alpha (AUC_{gap}^b - AUC_{gap}^d) + (1 - \alpha) (AUC^d - AUC^b). \end{equation} $CAUCI_{\alpha}:$ AUC fairness metric from~\cite{paul2020TARA}. $\alpha:$ Hyperparameter to balance the importance of a reduction in the AUC gap and an improvement in AUC between the baseline $AUC^b$ and debiased $AUC^d$ methods. $AUC_{gap}^b := \lvert AUC_{ls}^b - AUC_{ds}^b \rvert$ Baseline AUC gap between AUC on ls and ds samples. $AUC_{gap}^d := \lvert AUC_{ls}^d - AUC_{ds}^d \rvert:$ Debiased AUC gap between AUC on ls and ds samples. \section{Conclusion} \label{sec:conclusion} We present a study to identify, quantify, and mitigate bias of skin image classification and segmentation models trained from two datasets collected in our study. Specifically, we propose \sys, a novel data preprocessing method that utilizes edge detection to isolate skin lesions. \sys outperforms the previous SOTA (81.58\%) by 1.86\% accuracy and other debiasing methods with a $\mathtt{CAI}_{0.5}$ of 4.6650. We adapt \sys for the task of skin lesion segmentation on our new dataset and surpass the baseline method by 0.0544 in $\mathtt{Jaccard}$ score and reduce the $\mathtt{Jaccard}$ gap ($\mathtt{J}_\mathtt{gap}$) in performance between the light and dark skin subpopulations by 0.0387. \sys is an effective approach that achieves fair performance across subpopulations with respect to skintone. \section{Datasets} \label{sec:datasets} We collect, annotate, and then present two datasets for skin disease segmentation and classification which we will publicly release upon publication. First, we collect skin images either from publicly available sources or from clinicians with patient informed consent. Second, a medical technician and a clinician in our team manually annotate each image. Data annotation follow the specific task/dataset as indicated below: \begin{icompact} \item {\bf Segmentation:} We annotate skin images into three classes: background (black), skin (yellow), and lesion (blue), see Fig.~\ref{fig:segmask_examples}. The lesion area contains three types of disease/lesions: Tinea Corporis (TC), Herpes Zoster (HZ), and Erythema Migrans (EM). \item {\bf Classification:} We annotate skin images by classifying them into four classes: No Disease (NO), TC, HZ, and EM. \end{icompact} Table~\ref{tbl:segsplits} shows the characteristics of these two datasets broken down by the disease type and skin tone, as calculated by the Individual Typology Angle (ITA)~\cite{wilkes2015fitzpatrick}. Specifically, we consider tan2, tan1, and dark as dark skin (ds) and others as light skin (ls). One prominent observation is that ls images are more abundant than ds images due to a disparity in the availability of ds imagery found from either public sources or from clinicians with patient consent. This disparity motivates the design of \sys in improving model fairness in diagnosing skin diseases. \begin{table}[!t] \renewcommand{\arraystretch}{0.8} \setlength{\tabcolsep}{2.8pt} \caption{Annotated segmentation and classification dataset Characteristics, broken down by ITA-based skin tones (ls: light skin and ds: dark skin) and disease types (EM: Erythema Migrans, HZ: Herpes Zoster, TC: Tinea Corporis, and NO: No disease).} \label{tbl:segsplits} \centering \begin{tabular}{cccccccccccccccccccc} \toprule \multirow{4}{*}{Split} & \multicolumn{9}{c}{Segmentation Dataset} & \multicolumn{10}{c}{Classification dataset} \cr \cmidrule(lr){2-10} \cmidrule(lr){11-20} & NO & \multicolumn{2}{c}{EM} & \multicolumn{2}{c}{HZ} &\multicolumn{2}{c}{TC} & \multicolumn{2}{c}{Total} & \multicolumn{2}{c}{NO} & \multicolumn{2}{c}{EM} & \multicolumn{2}{c}{HZ} & \multicolumn{2}{c}{TC} & \multicolumn{2}{c}{Total} \cr \cmidrule(lr){2-2} \cmidrule(lr){3-4} \cmidrule(lr){5-6} \cmidrule(lr){7-8} \cmidrule(lr){9-10} \cmidrule(lr){11-12} \cmidrule(lr){13-14} \cmidrule(lr){15-16} \cmidrule(lr){17-18} \cmidrule(lr){19-20} & ls/ds & ls & ds & ls & ds & ls & ds & ls & ds & ls & ds & ls & ds & ls & ds & ls & ds & ls & ds \cr \midrule Train & 0 & 35 & 3 & 34 & 4 & 28 & 9 & 97 & 16 & 700 & 57 & 578 & 41 & 522 & 75 & 517 & 84 & 2,317 & 257 \cr Val & 0 & 5 & 5 & 5 & 5 & 5 & 5 & 15 & 15 & 36 & 2 & 31 & 10 & 35 & 6 & 26 & 5 & 128 & 23 \cr Test & 0 & 7 & 7 & 7 & 7 & 7 & 7 & 21 & 21 & 86 & 4 & 73 & 7 & 51 & 9 & 66 & 6 & 276 & 26 \cr \bottomrule \end{tabular} \end{table} \section{Results} \label{sec:discussion} In this section, we present results on on the task of lesion segmentation and skin disease classification. We also evaluate the performance and fairness of \sys compared with adversarial debiasing (AD), synthesized masking (Mask) in terms of fairness improvement and both (Mask+AD). Note, our code will be released upon publication. {\bf Skin Lesion Segmentation:} Table~\ref{tbl:SegBias} shows the performance of \sys and a baseline U-Net on our segmentation dataset. We compare predicted masks with the manually-annotated ground truth by calculating the $\mathtt{Jaccard}$ and $\mathtt{Dice}$ scores, and computing the gap for each of the two scores for subpopulations with ls and ds (based on ITA). The results present two clear findings. First, \sys, as a data preprocessing method, improves the utility of lesion segmentation in terms of $\mathtt{Jaccard}$ and $\mathtt{Dice}$. A possible reason is that \sys clearly preserves key skin lesion information, thus improving the segmentation quality, while attenuating markers for protected factors. Likewise, \sys also improves the fairness of the segmentation task by lowering the gap of the $\mathtt{Jaccard}$ and $\mathtt{Dice}$ scores between people with ls and ds. As a result, \sys demonstrates consistency in improving both utility as well as fairness in term of the utilized metrics. \begin{table*}[!t] \caption{Segmentation Test Results: Performance and Fairness} \scriptsize \begin{center} \ra{1.3} \begin{tabular}{@{} l C C C C C @{}} \toprule Method & $\mathtt{Jaccard}$ & $\mathtt{J}_\mathtt{gap}$ & $\mathtt{Dice}$ & $\mathtt{D}_\mathtt{gap}$\\ \midrule U-Net (Baseline) & 0.7053 (0.0035) & 0.0809 (0.0001) & 0.8225 (0.0029) & 0.0743 (0.0002) \\ {\bf \sys} & \textbf{0.7597 (0.0033)} & \textbf{0.0422 (0.0001)} & \textbf{0.8609 (0.0026)} & \textbf{0.0295 (0.0001)} \\ \bottomrule \end{tabular} \end{center} \label{tbl:SegBias} \vspace{-0.2in} \end{table*} {\bf Skin Disease Classification:} Table~\ref{tbl:ClassificationResults} shows utility performance ( $\mathtt{acc}$ and $\mathtt{AUC}$) and fairness results (gaps of $\mathtt{acc}$ and $\mathtt{AUC}$ between ls and ds subpopulations). Note that we list the margin of error of each number in the parenthesis. Clearly, \sys outperforms SOTA approaches in balancing the model's performance and fairness, i.e., the $\mathtt{CAI}_{\alpha}$ and $\mathtt{CAUCI}_{\alpha}$ values of \sys are the highest compared with the vanilla ResNet34 and other baselines. Next, we examine the different metrics separately. First, the $\mathtt{acc}$ value of \sys is the second largest, which is only second to the baseline ResNet34, but higher than all other competing debiasing methods. While a decrease in utility often arises for debiasing, our results show that \sys is effective in largely preserving the model's utility. The $\mathtt{acc}_\mathtt{gap}$ is also the second smallest, which is only second to the Mask approach (i.e., applying a segmentation mask to disease images). Note that the $\mathtt{acc}$ value of the Mask approach is a mere 73.84\%, suggesting utility was substantially sacrificed to maximize fairness. Next, the $\mathtt{acc}_\mathtt{min, ds}$ of \sys is the highest among all approaches, meaning that \sys is superior at improving classification performance for underrepresented ds subgroups. Second, the $\mathtt{AUC}$ value of \sys is only around 1\% smaller than of the baseline ResNet34 model, highlighting \sys's strong performance in disease classification. At the same time, the $\mathtt{AUC}_\mathtt{gap}$ is the smallest among all approaches, while $\mathtt{AUC}_\mathtt{min, ds}$ is the largest. This showcases that \sys has the best characteristics in terms of fairness, as well as addressing the overall fairness/utility criterion; thus, improving the overall system performance. \begin{table*}[!t] \scriptsize \caption{Skin disease classification and associated bias. Sample types include normal skin (NO) and diseased skin: EM, HZ, and TC. Samples contain skin tones as a protected factor.}\vspace{-0.1in} \label{tbl:ClassificationResults} \begin{center} \ra{1.3} \begin{tabular}{@{}lcccccc@{}} \toprule \multirow{2}{*}{Metrics}& \multirow{2}{*}{ResNet34} & \multicolumn{4}{c}{Baselines} & \multirow{2}{*}{\bf EdgeMixup} \\ \cmidrule(lr){3-6} & & AD & Mask & Mask+AD & DexiNed-avg & \\ \midrule $\mathtt{acc}$ & \textbf{85.10 (4.02)} & 81.79 (4.35) & 73.84 (4.96) & 72.52 (5.04) & 69.87 (5.17) & 83.44 (4.19)\\ $\mathtt{acc}_\mathtt{gap}$ & 13.15 (12.98) & 5.33 (11.69) & \textbf{0.83 (11.87)} & 4.82 (10.91) & 19.79 (13.52) &2.16 (10.28) \\ $\mathtt{acc}_\mathtt{min, ds}$ & 73.08 & 76.92 & 73.08 & 72.10 & 51.85 & \textbf{81.48} \\ $\mathtt{CAI}_{0.5}$ & - & 2.2550 & 0.5300 & -2.1250 & -10.9350 &\textbf{4.6650} \\ $\mathtt{CAI}_{0.75}$ & - & 5.0375 & 6.4250 & 3.1025 & -8.7875 &\textbf{7.8275} \\ \midrule $\mathtt{AUC}$ & \textbf{0.9725 (0.0185)} & 0.9555 (0.0233) & 0.9072 (0.0327) & 0.9053 (0.0330) & 0.8892 (0.0354) &0.9623 (0.0215)\\ $\mathtt{AUC}_\mathtt{gap}$ & 0.0331 (0.0714) & 0.0094 (0.0469) & 0.0275 (0.0618) & 0.0414 (0.0536) & 0.0898 (0.1129) &\textbf{0.0076 (0.0554) } \\ $\mathtt{AUC}_\mathtt{min, ds}$ & 0.9420 & 0.9548 & 0.9050 & 0.9023 & 0.8069 &\textbf{0.9556 } \\ $\mathtt{CAUCI}_{0.5}$ & - & 0.0034 & -0.0299 & -0.0378 & -0.070000&\textbf{0.007650} \\ $\mathtt{CAUCI}_{0.75}$ & - & 0.0135 & -0.0121 & -0.0230 & -0.063350 &\textbf{0.016575} \\ \bottomrule \end{tabular} \end{center} \vspace{-0.3in} \end{table*} \section{Discussion} Our study, performed under IRB approval (and to be publicly released), demonstrates for the first time the possible presence of bias when addressing Lyme disease, and other important conditions that act as confusers to Lyme (HZ and TC) when using a vanilla classifier. A fact, never reported before and also in contrast to other skin diagnostic studies. This observation highlights the importance of studying skin disease bias with datasets that have much larger exemplar cardinality for Lyme, HZ, and TC when compared to the other prevalent datasets, such as SD-198, that may not focus as much on those diseases. We also present a simple, yet highly effective, method to debias models, and show how the method produces a censoring/masking effect, vis-a-vis protected attributes markers, without a debilitating effect on utility. \section{Experimental Setup} \subsection{Lesion Segmentation} Our evaluation baseline is a U-Net trained to segment images of skin lesions into three categories: background, skin, and lesion. Our evaluation metrics include metrics for utility and fairness, since often (but not always) these two may tradeoff. Utility is measured using a $\mathtt{Jaccard}$ score~\cite{Jaccard} and $\mathtt{Dice}$ coefficient~\cite{Dice}, which measure the similarity between a predicted mask and the manually annotated ground truth. Higher similarity results in higher the model performance. Fairness is evaluated by the gap of the $\mathtt{Jaccard}$ score and $\mathtt{Dice}$ coefficient between ls and ds images, notated as $\mathtt{J}_\mathtt{gap}$ and $\mathtt{D}_\mathtt{gap}$ respectively. The smaller the gap is, the more fair the model. \subsection{Disease Classification} \subsubsection{Baselines:} We select ResNet34 as a baseline model, with ImageNet pretrained weights, early stopping, and a learning rate of 1e-3 trained for 100 epochs. Our evaluation for classification debiasing involves the following competing debiasing approaches: \begin{icompact} \item Adversarial Debiasing (AD). \hspace{0.05in} An in-processing method~\cite{zhang2018mitigating} using adversarial debiasing, where a separate classifier/player is tasked to predict the protected factor using the true class and the task prediction classifier's internal representation of a given input image. \item Mask. \hspace{0.05in} A mask-based debiasing approach leveraging a synthesized mask from a segmentation network to mask out skintone in images input to the classifier. \item Mask+AD. \hspace{0.05in} A combination of Mask and AD aimed at masking skintone information both in image and embedded space. \item DexiNed-avg. \hspace{0.05in} DexiNed-avg entails the use of the average version of DexiNed~\cite{dexined} as an edge detector used by \sys. \end{icompact} \subsubsection{Evaluation Metrics:} We use the following disease classification evaluation metrics. \begin{icompact} \item Accuracy based metrics: We measure accuracy to characterize utility. To measure fairness we use accuracy gap between ls and ds subpopulations, and the (Rawlsian) minimum accuracy across subpopulations. To characterize the tradeoff between utility and and fairness we use the joint metric from~\cite{paul2020TARA}: \begin{equation} \mathtt{CAI}_{\alpha} = \alpha (\mathtt{acc}_\mathtt{gap}^\mathtt{baseline} - \mathtt{acc}_\mathtt{gap}^\mathtt{debiased}) + (1 - \alpha) (\mathtt{acc}^\mathtt{debiased} - \mathtt{acc}^\mathtt{baseline}). \end{equation} \item AUC (Area under the receiver operating characteristic curve): Similarly, we also measure utility with AUC, and fairness via AUC gap and minimum AUC. Likewise, following prior work~\cite{paul2020TARA} we also calculate the AUC-based joint utility/fairness metric defined as: \begin{equation} \mathtt{CAUCI}_{\alpha} = \alpha (\mathtt{AUC}_\mathtt{gap}^\mathtt{baseline} - \mathtt{AUC}_\mathtt{gap}^\mathtt{debiased}) + (1 - \alpha) (\mathtt{AUC}^\mathtt{debiased} - \mathtt{AUC}^\mathtt{baseline}). \end{equation} \end{icompact} \section{Introduction} \label{sec:introduction} Early detection of skin lesions can aid in identifying a range of infectious diseases. We consider Lyme disease~\cite{LymeHinckley,kuehn2013cdc}--- which affects nearly 476,000 cases per annum during 2010-2018~\cite{kugeler2021estimating}. Lyme disease is caused by the bacterium \textit{Borrelia burgdorferi}, which manifests via a red concentric lesion, called Erythema Migrans (EM), at the site of a tick bite~\cite{NADELMAN2015211}. While the EM pattern may appear simple to recognize, its diagnosis can be challenging for those with or without a medical background alike, as only 20\% of United States patients have the stereotypical bull's eye lesion~\cite{emTibbles}. When skin lesions are atypical they can be mistaken for other diseases such as Tinea Corporis (TC) or Herpes Zoster (HZ)~\cite{mazori2015vesicular}, two other diseases acting a confusers for Lyme, considered herein. This has increased interest in medical applications of deep learning (DL), and using deep convolutional neural networks (CNNs), to assist clinicians in timely and accurate diagnosis of conditions including Lyme disease, TC and HZ~\cite{fujisawa2019deep,gu2019progressive,burlina2020ai}. A major challenge in diagnosing skin diseases with CNNs is that they have been shown to learn and exhibit bias inherent in training data~\cite{hermann2020origins}. For example, the diagnostics accuracy of people with light skin is often higher than those with dark skin because a) the training may not have sufficient samples of dark skin with the condition, or b) there may exists an inherent correlation between image markers of protected factors and disease. In response, the AI community has been investigating bias mitigation strategies such as data generation for underrepresented subpopulations~\cite{paul2020TARA} or adversarial debiasing~\cite{zhang2018mitigating}. However, while applying CNNs to dermatology is of growing interest, insufficient attention has been directed towards identifying or reducing the prevalence of bias in CNN prediction for skin disease classification and segmentation. Existing bias mitigation strategies often perform poorly on skin diseases, especially for segmenting and classifying Erythema Migrans (EM), because they tend to remove important information on the lesion area or important image markers after debiasing. We propose a novel data preprocessing and alteration method, called \sys, to improve fairness in skin disease classification and segmentation. The key insight of this approach is to alter a skin image with a linear combination of the source image and a detected edge mask so that the lesion structure is preserved while minimizing skin tone information, which is done by altering the color composition in HSV space, thereby minimizing the ability of the model to infer information about the protected factor. This combined preprocessing approach, while simple, is shown to be significantly more effective than competing methods such as adversarial approaches which are also aimed at masking markers or protected factors. We evaluate \sys with fairness metrics for skin disease segmentation and classification tasks. First, for the segmentation task, we construct a dataset composed of 185 publicly available diseased skin images with annotations for three regions: background, skin and lesion, conducted under clinician supervision and Institutional Review Boards (IRB) approval. Next, we demonstrate the existence of segmentation model bias on our annotated dataset. Our results show that \sys is able to reduce bias to improve fairness and increase utility (as measured via $\mathtt{Jaccard}$ and $\mathtt{Dice}$). Second, for the classification task, we collect and have a clinician supervise annotation for a skin disease dataset with 2,712 (publicly-available) skin images classified into four classes, i.e., No Disease (NO), TC, HZ, and EM. We perform evaluation on the classification task using a traditional ResNet34 baseline and demonstrate the existence of significant bias. We show that \sys substantially improves model fairness compared to the baseline and also significantly outperforms state-of-the-art (SOTA) debiasing methods in improving performance on joint fairness-utility metrics. Our contributions are: \begin{icompact} \item We collect, annotate, and present two novel skin disease datasets with emphasis on Lyme disease, Tinea Corporis, and Herpes Zoster, for studying segmentation, classification, and addressing fairness, which we will publicly release upon publication. \item We demonstrate for the {\it first} time that a segmentation model may exhibit bias for these important diseases. \item We propose \sys, a novel data preprocessing method that jointly addresses utility and fairness for the tasks of classification and segmentation of skin diseases. \item We evaluate \sys on skin lesion classification and segmentation, showing that it improves utility and fairness for segmentation and their tradeoff for classification, which also outperforms the SOTA approach. \end{icompact} % \section{Method} \label{sec:methods} We present our core method in reducing skin tone bias for segmentation and classification CNNs. We start by describing the design of \sys, and then present how we apply \sys for the tasks of segmentation and classification. \subsection{EdgeMixup data preprocessing} \begin{figure}[tb]\captionsetup{font=footnotesize} \centering \begin{subfigure}{0.19\textwidth} \includegraphics[width=\linewidth]{figs/Edge_detection/1108_original.jpg} \caption{Original Image}\label{fig:diff_operator-1} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\linewidth]{figs/Edge_detection/1108_canny.jpg} \caption{Canny}\label{fig:diff_operator-2} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\linewidth]{figs/Edge_detection/1108_fused.jpg} \caption{DexiNed-fused} \label{fig:diff_operator-3} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\linewidth]{figs/Edge_detection/1108_avg.jpg} \caption{DexiNed-avg} \label{fig:diff_operator-4} \end{subfigure} \begin{subfigure}{0.19\textwidth} \includegraphics[width=\linewidth]{figs/Edge_detection/1108_EdgeMixup.jpg} \caption{EdgeMixup} \label{fig:diff_operator-5} \end{subfigure} \caption{A motivating example to compare different edge detection methods} \label{fig:diff_operator}\vspace{-0.1in} \end{figure} The key insight of \sys is to ``mix-up'' a detected edge image with the original skin image for data preprocessing via a linear combination. Intuitively, such preprocessing not only highlights the skin lesion, via an edge image, but also suppresses the skin tone. While this idea is intuitively simple, the edge detection is challenging due to color similarity causing ambiguous edges between skin and lesions. We start with a motivating example to illustrate this challenge. {\bf Motivating example:} Fig.~\ref{fig:diff_operator-1} shows a skin disease image with atypical EM, in which the lesion has no clear boundary with the skin, making the edge detection challenging. We test two different edge detectors on this scenario: the Canny operator~\cite{canny_operator} and the SOTA DL-based edge detector DexiNed~\cite{dexined} (trained on BIPED~\cite{BIPED}). DexiNed includes two version: fused ( concatenation and fusion of all predictions from the neural network) and avg (an average of all predictions). Fig.~\ref{fig:diff_operator-2}--\ref{fig:diff_operator-4} shows the edge detection result. Clearly, Canny fails to even detect a basic human silhouette; DexiNed-fused detects some of the human body's edge, but not the lesion's. DexiNet-avg is better at detecting some parts of the lesion, but not its edge. As a comparison, we also depict the edge detection of \sys in Fig.~\ref{fig:diff_operator-5}, which clearly shows the lesion boundary. \begin{figure}[!t] \centering \includegraphics[width=\textwidth]{figs/Edge_detection/process.pdf} \caption{EdgeMixup Process} \label{fig:fig_process} \vspace{-0.2in} \end{figure} {\bf Approach:} Fig.~\ref{fig:fig_process} summarizes the overall process of \sys's data preprocessing into four steps. First, \sys converts a given image to the Hue-Saturation-Value (HSV) color space. Then, \sys applies a red mask in the HSV color space to zero-out the red and blue channels and maximize the green color to 255. The image from this step is called contrast augmented. Second, \sys selects the value (V), or lightness, channel of the contrast augmented image from the previous step to produce a gray-scale image. Third, \sys applies a Canny edge detector to extract edge boundary and generates an edge image. Lastly, \sys combines the edge image and the original sample image linearly, like a mixup, to generate an altered image (called a result image). If not otherwise specified, the default weight for edge image in the linear combination is 0.3. \subsection{Application of \sys on different diagnostics-related tasks:} The purpose of \sys is to improve fairness in diagnostics models via data alteration and pre-processing. Next, we apply \sys to two types of DL-based diagnostics tasks with the aim of improving fairness. {\bf Lesion Segmentation:} Lesion segmentation aims to separate a skin lesion from regular skin to assist clinicians in the examination and diagnosis of EM by simplifying time-series clinical comparisons. \sys preprocesses training images before feeding them into a segmentation model (both at training and inference time), e.g. U-Net~\cite{ronneberger2015u}, which then segments the images into three regions: background, skin, and lesion. {\bf Disease Classification:} Disease classification aims to prescreen and diagnose, principally, EM (for Lyme Disease), and also classify possible Lyme confusers including: Tinea Corporis (TC), Herpes Zoster (HZ), and no disease (NO). Again, \sys alters the original training images prior to training a classification model, such as a ResNet34~\cite{resnet}. \section{Metrics} \label{sec:metrics} The fairness of both classification and segmentation models are evaluated using a series of joint utility functions that balance the performance of said models and the gap between subpopulations of the protected factor. This joint utility function was first introduced by~\cite{paul2020TARA} for the case of classification accuracy, expressed as follows: \begin{equation} CAI_{\alpha} = \alpha (acc_{gap}^b - acc_{gap}^d) + (1 - \alpha) (acc^d - acc^b). \end{equation} The $CAI_{\alpha}$ metric uses $\alpha$ to balance the importance of a reduction in the accuracy gap and an improvement in accuracy between the baseline $acc^b$ and debiased $acc^d$ methods. Where the accuracy gap of the baseline $acc_{gap}^b$ and debiased $acc_{gap}^d$ methods are computed as the difference between the accuracy of the subpopulations of $S$, which in this case is binary: light skin tone and dark skin tone. Moreover,~\cite{paul2020TARA} also introduced a variation of the fairness utility based on area under the curve $AUC$ metric, as illustrated below: \begin{equation} CAUCI_{\alpha} = \alpha (AUC_{gap}^b - AUC_{gap}^d) + (1 - \alpha) (AUC^d - AUC^b). \end{equation} $CAUCI_{\alpha}$ operates in a similar manner to $CAI_{\alpha}$ where AUC gap ($AUC_{gap}^b$ and $AUC_{gap}^d$) reduction importance is balanced with an increase in the change of AUC ($AUC^d$ - $AUC^b$) for the baseline $b$ and debiased $d$ methods. \section{Related Work} \label{sec:related_work} We provide an overview of prior work in skin disease classification and segmentation, as well as bias mitigation methods in the domain of medical imaging. {\bf Skin Disease Classification and Segmentation:} Deep CNNs have gained popularity for automated melanoma skin lesion segmentation due to disease relevance and model performance, despite the prevalence of fuzzy borders, inconsistent lighting conditions, and image artifacts~\cite{bi2017dermoscopic,zhang2019automatic}. Individual Topology Angle (ITA) has been used as a proxy for skin tone labels in medical imagery for segmentation and classification tasks. Little bias was found in skin disease segmentation and classification models using the SD-136~\cite{sun2016benchmark} and ISIC2018~\cite{codella2019skin} datasets~\cite{kinyanjui2020fairness}, which differ from the diseases this study focuses on. In this work, we reach the opposite conclusion for segmentation and classification of specific skin diseases and their lesions, including Lyme, EM, TC, and HZ. This also motivates the design of \sys in improving the fairness of skin lesion segmentation and classification. {\bf Bias Mitigation:} Addressing bias in deep learning models can be categorized into three categories~\cite{caton2020fairness}: (1) {\it preprocessing}, such as augmentation and re-weighting; (2) {\it in-processing}, like adversarial debiasing; and (3) {\it post-processing}, such as thresholding. First, masking sensitive factors in imagery is shown to improve fairness in object detection and action recognition~\cite{Wang_2019_ICCV}. Second, adversarial debiasing operates on the principle of simultaneously training two networks with different objectives~\cite{goodfellow2014generative,madry2017towards,shafahi2019adversarial}. The competing two-player optimization paradigm is applied to maximizing equality of opportunity in~\cite{beutel2017data}. This technique has shown success for tabular data~\cite{zhang2018mitigating}, word embeddings~\cite{bolukbasi2016man}, and imagery~\cite{zhang2020towards}. Lastly, Hardt el al.~\cite{hardt2016equality} adjust model outputs using thresholds to mitigate discrimination against a specified sensitive attribute. By contrast, we propose \sys a much less complex but also more effective preprocessing approach to debiasing when applied to skin disease, and particularly Lyme-focused, classification and segmentation tasks.
{'timestamp': '2022-03-01T02:52:22', 'yymm': '2202', 'arxiv_id': '2202.13883', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13883'}
arxiv
\section{Introduction} In recent developments in individual mobility % we see increasingly automated driver assistance functions. While drivers are relieved by higher degrees of automation, the requirements for functional safety increase. Assistance systems focused on longitudinal vehicle control, such as adaptive cruise control, overtaking assistants, and emergency braking systems, have proven to be advantageous for road safety~\cite{jeong2017evaluating}. However, there are no appropriate substitutes for these radar-based systems in urban areas, where cars share traffic space with vulnerable road users (VRUs)~\cite{yannis2020vulnerable}, such as pedestrians and bicyclists because humans may be difficult to detect by radar~\cite{sun2020mimo}. Vision-based systems have the potential to overcome some disadvantages of LIDAR or radar systems. They have low costs and increasing capabilities due to advances in artificial intelligence (e.g., deep learning). Still, VRUs remain a~major challenge also for camera-based autonomous driving~\cite{sun2019challenges}. Accident blackspots are found where paths of different road users cross, such as crosswalks and intersections in urban areas~\cite{nguyen2016approach}. We propose a~new approach to predict the behavior of VRUs in urban traffic. Intuitively, the line of sight (or even eye contact) between a~driver and a~pedestrian standing at the side of the road is important and can provide information about whether a~person is about to enter the road. We study how this implicit knowledge can possibly be exploited. Using image data, we train artificial neural networks (ANNs) to predict positions and trajectories of pedestrians in the near future. Key to our concept is that we develop agent models of pedestrian behavior using the pedestrian's actual perspective and field of view. We believe that with today's technology the pedestrian's perspective can be derived from the data available to the autonomous car. A~vehicle's surrounding can already be captured by 360-degree cameras today, and advances in pose recognition~\cite{cao2019openpose} of pedestrians allow to reconstruct their perspective at least partially. In this preliminary study, we present our results for the toolchain that works on the pedestrian's view exclusively. Initially we focus on pedestrians crossing streets at crosswalks, but our approach is easily extended to address also other VRUs, such as bicyclists and scooter riders. We present our results based on synthetic data obtained using the CARLA simulation environment~\cite{Dosovitskiy17}. We have developed scenarios that correspond to central European road traffic situations, in particular intersections and crosswalks, as these are the accident blackspots in urban traffic of cars and pedestrians~\cite{nguyen2016approach}. We have extended CARLA's semantic segmentation of the simulated camera image to recognize crosswalks as a~separate category. For the simulation of pedestrians, we have developed detailed motion sequences and animations including head movements before entering the road (left and right or shoulder check). From these pedestrian crossing situations we collect synthetic data and train ANNs, i.e., variational autoencoder (VAE) and long short-term memory (LSTM) network, that can then be used to predict pedestrian behavior. For these simulated scenarios, we are able to predict the behavior of a~pedestrian for the immediate future. Our main contribution is the toolchain processing pedestrian perspective vision data and outputting a~pedestrian model with predictive power. In future work, we plan to apply this toolchain to real-world data and to derive pedestrian perspective images from the autonomous car's 360-degree camera data. Our vision is to use these pedestrian models to inform autonomous driving systems about probable dangerous VRU situations with enough look-ahead to initiate a~safe brake actuation. \section{Related work} VRU detection and behavior prediction is an active topic of research for autonomous vehicles~\cite{mannion2019vulnerable}. A~lot of work on VRU detection and behavior prediction focuses on the interaction between vehicles and pedestrians~\cite{rasouli2019autonomous}, but mostly from the perspective of the car~\cite{ahmed2019pedestrian}. Many approaches for pedestrian trajectory prediction are trained and validated on datasets that provide not only images of pedestrians but also action and environmental priors~\cite{kotseruba2016joint, % robicquet2016learning, rasouli2019pie}. Priors provide additional context % about tracked agents and environments % to account for % feature relevance and improving prediction performance. % Most % approaches consider the problem of pedestrian behavior prediction from the perspective of a~vehicle and generally use monocular RGB images as input. Autoencoders are often used to convert data to a~lower-dimensional representation~\cite{bank2020autoencoders}, which helps to process complex data efficiently. % Ho, Keuper, and Keuper describe another tracking system based on an autoencoder~\cite{ho2020unsupervised}. They use the latent space representation of their visual tracking cues to make their system robust to spatial or temporal changes. Another autoencoder-based technique is variational recurrent neural networks~(VRNN)~\cite{chung2015recurrent}, which include high-level random variables in the latent space of a~% VAE~\cite{kingma2013auto}. Hoy et al.~\cite{hoy2018learning} use a~VRNN to perform object tracking on the Daimler Pedestrian Path Prediction Dataset~\cite{schneider2013pedestrian}. This tracking is used to generate a~binary crossing/stopping classification of each pedestrian. Poibrenski et al.~\cite{poibrenski2020m2p3, poibrenski2021multimodal} present a~multimodal approach to trajectory prediction that feeds past trajectories and scales of pedestrians into a~conditional autoencoder with RNN decoder-encoder architecture. Kooij et al.~\cite{kooij2019context} model pedestrian and cyclist trajectories as a~switching linear dynamical system multiple linear models approximate complex nonlinear data dependencies. % Using a~stereo camera, their approach switches prediction states based on both, the observed static and dynamic environment as well as % agent's actions. Saadatnejad et al.~\cite{saadatnejad2019pedestrian} deal with generating an invariant, canonical representation of pedestrians in traffic. The authors use OpenPose~\cite{cao2019openpose} and a~generator-discriminator architecture similar to generative adversarial networks (GANs)~\cite{goodfellow2014generative}. A~canonical representation of pedestrians is invariant to different poses, occlusions, transformations and lighting changes. It is useful for recognizing and tracking pedestrians that are occluded from the camera for a~long time. % Rasouli et al.~\cite{rasouli2017they} introduce the use of behavioral and contextual information to improve pedestrian behavior prediction. Makansi et al. use mixture density networks to predict the movement and emergence of pedestrians in traffic~\cite{makansi2020multimodal}. They calculate a~reliability prior using semantic segmentation data to determine all possible future positions for a~given object class. Based on this data, the ego-vehicle's motion is compensated, and future pedestrian positions are predicted. Mangalam et al. divide the task of pedestrian motion and pose prediction into local and global motion components~\cite{mangalam2020disentangling}. These subproblems are solved using an RNN with a~recurrent encoder-decoder architecture. Cao et al.~\cite{cao2020long} predict sequences of human poses in 3D using a~3-stage hierarchical approach. In the first stage, the authors utilize a~single RGB frame and a~history of 2D poses to generate target positions. In the second stage, the paths to these target positions are calculated. Finally, the human poses are estimated. Another approach using an encoder-decoder architecture was proposed by Yin et al.~\cite{yin2021multimodal}. Using a~transformer network, they integrate ego-vehicle speed, optical flow and past pedestrian trajectories to predict trajectories. They compensate for the ego-vehicle's motion by % separate center and pedestrian patches. Other approaches on pedestrian behavior prediction are not bound to the ego perspective of a~vehicle but use infrastructure-based sensors. % Zhao et al.~\cite{zhao2019trajectory} present a~pedestrian tracking system that uses LIDAR data fed into a~deep autoencoder neural network. Sun et al.~\cite{sun20183dof} focus on SLAM data. They propose the T-Pose-LSTM, which provides real-time 2D pedestrian trajectory predictions. Another solution is to use 2D map data % as training data is readily available~\cite{brvsvcic2013person}. Zhang et al.~\cite{zhang2020prediction} predict if pedestrians jaywalk using a~standard LSTM. They use video data captured by a~camera installed at the crosswalk. Using a~perspective transformation, the authors map pedestrian positions from the video data to a~2D map representation. The LSTM uses location, traffic light state, and several social factors % to predict if a~given pedestrian will jaywalk. % Vasquez et al.~\cite{vasquez2014inverse} use Inverse Reinforcement Learning (IRL) to safely navigate a~mobile robot through crowds of pedestrians. Fahad et al.~\cite{fahad2018learning} use IRL as well % to generate realistic pedestrian trajectories with social interactions on a~2D navigation grid. Employing social affinity maps extracted from human motion trajectories, they train a~deep neural network (DNN), which generates trajectories. The authors focus on the social interactions between pedestrians. Especially the \textit{social forces} technique~\cite{helbing1995social} has proven as a~valid approach for pedestrian trajectory estimation that also takes into account social interactions~\cite{ferrer2013robot}. % Alahi et al.~\cite{alahi2016social} model the social dependencies in crowds of pedestrians using their Social LSTM, which can model multiple pedestrian trajectories in parallel and thus understand their interactions. Improving on that, Cheng et al.~\cite{cheng2018pedestrian} use a~Grid LSTM and social pooling to model pedestrian interactions. Chou et al.~\cite{chou2020predicting} use motion features and a~map-based rasterization approach to generate pedestrian trajectories using a~convolutional neural network (CNN) architecture based on MobileNetv2~\cite{sandler2018mobilenetv2}. Ivanovic et al.~\cite{ivanovic2020multimodal} use a~conditional % VAE to predict pedestrian behavior. Their data-driven approach considers not only the social interactions between pedestrians, but also the movement of vehicles on the road. Many of these approaches see pedestrians as black boxes and reduce their interactions with the environment to features that immediately concern their navigation. In this paper, we predict the pedestrian's perspective and consider the pedestrian as an agent with sensory inputs and outputs, providing a~stochastic causal link between the pedestrian's environment and their actions. % We model such sensory inputs for our prediction model, providing a~world representation for an individual pedestrian. \section{Methods} We generate a~realistic pedestrian vision model in the autonomous driving simulator CARLA~\cite{Dosovitskiy17}. A~considered pedestrian (in the following called ego-pedestrian) is controlled by hand-coded state machines to create realistic pedestrian trajectories and head movements. We use this pedestrian agent to collect image (view of the pedestrian) and movement data (executed movement actions of the pedestrian) in simulations. % For this study, we restrict ourselves to simple street crossing behaviors. The ego-pedestrian approaches a~street crossing, waits if vehicles are approaching, % and crosses to the opposite sidewalk. With this data, we train a~VAE~\cite{kingma2013auto} and an LSTM~\cite{hochreiter1997long} (see Secs.~\ref{sec:visualEncDec} and~\ref{sec:predictionModel}). We take images from the pedestrian's point of view that are immediately semantically segmented by the simulation environment CARLA. The LSTM is provided with input of a~latent vector of a~VAE that encodes the semantically segmented vision. % First, the collected images are used to train the VAE. Second, the respective latent vectors and sequence of pedestrian actions as movement labels are used to train the LSTM. Code can be found on our Git repository\footnote{\url{https://gitlab.iti.uni-luebeck.de/petzold/pedestrian_perception}} and supplementary materials on Zenodo~\cite{petzold2021predictingpedestrians}. \subsection{CARLA and image segmentation} \label{section:segmentation} We developed a~pedestrian behavior model for use in virtual 3D traffic environments as in CARLA which is an % autonomous driving simulator based on Unreal Engine~4.\footnote{\url{https://www.unrealengine.com}} CARLA uses a~state-of-the-art 3D engine and provides support for detailed pedestrian animations. We created a~small custom map that features a~street that loops in on itself, a~four-way intersection and a~pedestrian crossing. The map is designed to resemble a~central European town, so we use corresponding road signage and right-hand traffic. Using the CARLA API's hierarchical walker skeleton, we control leg, arm, and head joint parameters independently to generate realistic movements. We collect image data from the perspective of the controlled ego-pedestrian. % We attach a~virtual camera to the ego-pedestrian's head joint, making the camera pose dependent on the ego-pedestrian's % pose. % The head joint is subject to a~chain of 6 kinematic transformations. % CARLA defines these transformations as \emph{base}, \emph{root} and \emph{hips} transformations, followed by two spine transformations (\emph{spine} and \emph{spine01}) and a~\emph{neck} transformation. % CARLA uses a~fixed time step % for agent control and % sensor data collection that we set to 60~ms. We collect data using the semantic segmentation camera provided by CARLA, which guarantees an error-free segmentation, as the data is generated based on the built-in object classes. To CARLA's 23 object classes, we have added a~class for pedestrian crossings, as they are crucial for our scenario. In addition to image data, we collect movement information of the ego-pedestrian % including flags if the pedestrian has moved this time step, their body's angle parallel to the ground (yaw) in the world coordinate system, and separately their head's rotation parallel to the ground (yaw) in the body's base coordinate system. \begin{figure} \centering \includegraphics[width=8.5cm,trim={0 0 13.7cm 0},clip]{./fig/topdown_overlay} \caption{\label{fig:topdown}The crosswalk scenario after 5~s have passed, shown from a~top-down perspective. Several pedestrians approach and leave the crosswalk, as well as cars on both lanes. Directly below the crosswalk the ego-pedestrian (teal) follows the path (red) defined by the FSM in Fig.~\ref{fig:fsm}. Agent detectors placed on the car lanes are marked in blue (dotted boxes). Since the cars are inside at least one detector area, the ego-pedestrian waits in front of the crosswalk in this scenario. The area with green striped borders is the ego-pedestrian's view cone and represents the part of the environment the ego-pedestrian sees.} \end{figure} Due to its critical safety, we focus on the ego-pedestrian crossing the street using a~pedestrian crossing. For each scenario, we generate random numbers of other pedestrians (uniform distribution unif$\{0, 50\}$, in addition to the ego-pedestrian) and vehicles (unif$\{0, 20\}$). % The pedestrian and vehicle models are randomly drawn from the blueprint library provided by CARLA. The library provides a~diverse set of models representing adults % and children for pedestrians and vehicles of different shapes and sizes, including bicycles and motor bikes. Starting locations and destinations for all pedestrians except the ego-pedestrian are randomly drawn from all traversable sidewalk locations. % Vehicles spawn from manually placed, but random spawn points on the street. % Agent movement is controlled by CARLA's simple AI controllers. % The ego-pedestrian's behavior is implemented using timing-based finite state machines (FSMs). The FSMs realize a~pedestrian trajectory traversing the pedestrian crossing. % The first FSM controls the ego-pedestrian's two head movements. After $3.6$~s the pedestrian looks to the left for $2.4$~s. After $1.8$~s, the pedestrian looks to the right for $4.2$~s and then looks ahead for the remainder of the scenario. The second FSM (see Fig.~\ref{fig:fsm}) manages the movement of the pedestrian's body. Initially, the ego-pedestrian is spawned on the sidewalk in the \emph{walk} state. % Following this, the pedestrian goes through the \emph{turn}$_r$, \emph{look}, \emph{walk}, \emph{rest}, \emph{turn}$_l$ and \emph{walk} states, before finishing the scenario in the \emph{end} state. State transition conditions are mostly based on timing cues chosen based on the ego-pedestrian's walking speed. The only exemption from this is the \emph{wait for clear} transition between \emph{look} and \emph{walk}. It depends on a~timer and on the passing of all cars approaching the crossing inside a~detector area stretching $21$~m along the road for each lane. See Fig.~\ref{fig:fsm} for all details of the second FSM and a~top-down view of our scenario is shown in Fig.~\ref{fig:topdown}. \begin{figure} \centering \includegraphics[width=8.5cm]{./fig/fsm_alttext} \caption{\label{fig:fsm}The ego-pedestrian's behavior, described by a~finite state machine. The walk states are functionally identical and only separated for better readability. Each state transition is labeled with both the waiting time the FSM's transition is based on and a~behavioral description what the ego-pedestrian does during that waiting time. The flag $c$ between the states \emph{look} and \emph{walk} is set when the street in front of the pedestrian crossing is free of approaching cars. The ego-pedestrian's path described by this FSM can be seen in Fig.~\ref{fig:topdown}.} \end{figure} \subsection{Visual encoder/decoder} \label{sec:visualEncDec} We run 1,000 episodes of our simulated pedestrian crossing scenario. At each time step~$t$, we record a~visual representation of the environment~$f_t$ from the pedestrian's perspective, together with its planned action~$a_t$. This totals in a~dataset $\mathbf{\Psi}$ % of size $\sim805$k frames that we use to train a~convolutional VAE (ConvVAE) with TensorFlow~\cite{abadi2016tensorflow}. % The dataset frames were resized to $45\times85$ pixels and modified to be represented in 24~channels (i.e., semantic classes of CARLA plus ours, see Sec.~\ref{section:segmentation}). The ConvVAE is required to learn nondeterministic abstract encoded representation~$z$ for each of these input frames, which serve as an input for our prediction model together with action~$a$ (see Fig.~\ref{fig:model}). This is achieved by sampling from a~probability distribution over all semantic classes for each pixel. % Note that we allow the overlapping of classes, enabling a~smooth visual transition between segmented objects. Accordingly, the ConvVAE has a~$45\times85\times24$ input tensor and typical encoder/decoder architecture. On the one hand, the encoder consists of four chained convolutional layers. The output from these layers is flattened before it is pushed to two separate branching fully connected layers forming the subnetworks, which generate and dense the mean~$\mu$ and logarithmic variance~$\log\sigma^2$ vectors for 50~features. The~$\mu$ and $\log\sigma^2$ vectors % are used to sample a~latent vector~$z$. On the other hand, the decoder is a~transpose of the encoder, and it is trained to decode a~latent vector~$z$ back into the $45\times85\times24$ pixel representation. The output deconvolutional layer uses a~sigmoid function to output normalized pixel values between zero and one, while all other layers use a~Rectified Linear Activation (ReLU) function. We use the Kullback–Leibler divergence loss function \begin{equation} \label{equation:KL_loss} \sum_{x \in X} P_{\text{true}}(x) \log\left(\frac{P_{\text{true}}(x)}{P_{\text{decoded}}(x)}\right)\; \end{equation} to evaluate the network's performance by assessing the difference between the original ($P_{\text{true}}$) and decoded ($P_{\text{decoded}}$) distributions. % We split the dataset~$\mathbf{\Psi}$ into training (90\%) and validation (10\%) and train the ConvVAE for 80 epochs on batches of size~$1,610$ (i.e., two episodes). To prevent overfitting, we pick the network with minimum validation loss at epoch~62. We use the trained ConvVAE to sort the data~$\mathbf{\Psi}$ by time steps, % to prepare it for LSTM network training. Now, a~vector $\mathbf{\psi}_t$ at time step~$t$ is composed of 100 dimensions representing the current encoded frame's~$\mu_t$ and~$\log\sigma_t^2$ for each feature in latent vector~$z_t$, three dimensions % for ego-pedestrian action~$a_t$, and 100 dimensions for~$\mu_{t+1}$ and~$\log\sigma_{t+1}^2$ for each feature at the next time step~$t+1$. \subsection{Prediction model} \label{sec:predictionModel} As a~traffic situation prediction model, we train an LSTM network using TensorFlow and the reformatted dataset~$\mathbf{\Psi}$. With such a~prediction model, we aim to predict the future pedestrians' surrounding conditions given their current encoded visual perspective and sequence of actions in a~traffic scenario (see Fig.~\ref{fig:model}). Here, we split % the data into training (86\%) and validation (14\%) subsets. % The LSTM network has 53 inputs% , 512 hidden units, and a~mixture density network~\cite{10.5555/525960} as an output layer (see~\cite{46008} for full architecture information). Inspired by Ha et al.~\cite{46008, Ha:2018:RWM:3327144.3327171}, we train the LSTM to output a~probability density function~$p(z)$ % as a~mixture of Gaussian distribution, instead of deterministic predictions. We can control the randomness level by adjusting the temperature parameter~$\tau$ value between zero and one. We obtain deterministic predictions if~$\tau \rightarrow 0$ and increased randomness with higher values. This enables us to introduce uncertainty and variability, while predicting future surrounding conditions, which is typical in regular traffic situations. The LSTM receives a~sampled % encoded frame~$z_t$ and pedestrian action~$a_t$ as input at each time step~$t$ and outputs~$p(z_{t+1})$, from which the next encoded frame~$z_{t+1}$ is sampled (see~\cite{46008} for more details). We train the LSTM in % batches of size~$1,610$ for $4 \times 10^6$ steps. To prevent overfitting, we use time step $3.8 \times 10^6$ with minimum validation loss. \begin{figure} \centering \includegraphics[width=8.9cm]{./fig/model} \caption{\label{fig:model}Flow diagram showing how, at time step $t$, the VAE encodes the pedestrian perspective of the simulated CARLA agent into a~latent vector $z_t$, which is then input to the prediction model together with the pedestrian's action $a_t$. In turn, the prediction model outputs the next encoded frame $z_{t+1}$, which can be looped back to predict further frames.} \end{figure} \begin{figure*}[t] \centering \includegraphics[width=18cm]{./fig/dream_screenshot2} \caption{\label{fig:dream}Different modalities of the ego-pedestrian's vision. You see CARLA's RGB representation of our pedestrian's perception (\emph{RGB}); our model's input, the semantically segmented image out of CARLA, at time step $t$ (\emph{original}); the encoded and once again decoded VAE output (\emph{en/decoded}); % a~frame decoded from predicted sample $z_{\hat{t}+8}$ with $\hat{t} = t-8$ (\emph{predict 8}); a~frame decoded from predicted sample $z_{\hat{t}+16}$ with $\hat{t} = t-16$ (\emph{predict 16}); our pedestrian's world model (\emph{dream}). The shown predictions for $t$ are based on data captured at previous time steps $\hat{t}$ % to allow for direct comparison between all images. } \end{figure*} \section{Results and Discussion} Using the VAE and LSTM described in Sections~\ref{sec:predictionModel} and~\ref{sec:visualEncDec}, we have built a~sensory prediction model, and by extension a~world model~\cite{wellmer2021dropout, Ha:2018:RWM:3327144.3327171}, for our pedestrian crossing the street. One prediction time step corresponds to 60~ms, that is the same time horizon as the simulation time step. % We have evaluated these models in four different experiments, all based on the same scenario set up as described in Sec.~\ref{section:segmentation}. These experiments can be found in our video.\footnote{\url{https://vimeo.com/656754927}\label{fn:repeat}} The first experiment is a~quantitative evaluation of the LSTM's capabilities to predict one time step ahead (see error graph Fig.~\ref{fig:mu_error}, % graph $r=1$). We generate the one-time-step prediction $\hat{\mu}^{1}_{t}$ (and its corresponding $\log\sigma_{t}^2$) for time step~$t$ based on data from time step $t-1$ by feeding the VAE's encoded frame~$z_{t-1}$ and action~$a_{t-1}$ into our LSTM. The error $e^r_t = ||\hat{\mu}_t^r - \mu_{t}||_2$ for look-ahead $r\in\{1,8,16\}$ is the Euclidean distance between prediction~$\hat{\mu}_t^r$ and the ego-pedestrian's actual recorded data~$\mu_{t}$. $e^r_t$~for $r\in\{8,16\}$ are discussed in the second and third experiment. As seen in Fig.~\ref{fig:mu_error}, the error graph for $r = 1$ has multiple peaks. There are three kinds of peaks. Some peaks are sudden, without the prediction error increasing significantly before or slowly decreasing after. These high peaks are caused by hard-to-predict movements, often rotations. Large parts of the image are in motion and many pixels % change classes, resulting in high errors. % Such errors occurs at $t=60$, when the ego-pedestrian turns their body to the right and their head to the left, or at~$t=85$, when the ego-pedestrian turns their head back to the right (other occurrences: $t\in\{110, 143, 220 \}$). At time steps~$163$ and~$173$ the ego-pedestrian walks while looking to the side, causing some jitter in the movement and peaks in the error graph. For another type of peak the error rises slowly beforehand. This type is caused by pedestrians or cars appearing in the distance and passing by the ego-pedestrian. Based on the distance and manner of passing, the resulting spike is larger or smaller. This happens at $t = 55$, when a~pedestrian laterally crosses in front of the ego-pedestrian, or at time steps $580, 728$ and $738$, when pedestrians approach frontally. These peaks are rather high, as the pedestrians pass close by the camera. % At $t = 460$ and $t = 695$, a~pedestrian on the opposite sidewalk and a~car approach. As they are further away, % their error peaks are lower. The last kind of error peak appears suddenly and then slowly degrades. This is caused by pedestrians and cars entering the frame directly next to the ego-pedestrian and then moving away from them, e.g., at $t = 265$ and $t=370$. As the sudden appearance of a~car or pedestrian is not predictable, this causes a~high error. Time steps~$265$ to~$330$ show a~constant low error without peaks. This happens because the ego-pedestrian does not turn and there are no other traffic participants in their field of view, as they face a~wall. The second and third experiments evaluate our model's ability to generate valid inputs for larger prediction horizons (Fig.~\ref{fig:mu_error}, % graphs $r = 8$ and $r = 16$). In the second experiment we generate prediction $\hat{\mu}^{8}_{t}$ by applying our model 8~times. The first application of our model uses an encoded frame~$z_{t-8}$ and action~$a_{t-8}$ as inputs, further iterations use the previous output frames and corresponding actions. This corresponds to a~prediction 8~time steps ahead and a~prediction horizon of~$\sim 0.5~s$. In the third experiment, the same thing is done 16~times, generating a~prediction 16~time steps ahead and a~prediction horizon of~$\sim 1~s$. Sampled and decoded outputs of these experiments can be seen in Fig.~\ref{fig:dream} and in our video.\footref{fn:repeat} Both experiments show a~generally higher prediction error than the first experiment % as they accumulate uncertainty and noise caused by the repeated application of our prediction model (higher errors for~$\hat{\mu}^{16}_{t}$ than~$\hat{\mu}^{8}_{t}$). % Still, their error plots are qualitatively similar to~$\hat{\mu}^{1}_{t}$. Spikes in errors are mostly consistent across all three experiments. As the error for~$\hat{\mu}^{1}_{t}$ only depends on data from the previous time step, difficult-to-predict movements of the ego-pedestrian only affect one prediction time step. For~$\hat{\mu}^{8}_{t}$ and~$\hat{\mu}^{16}_{t}$, these errors cause a~`tail' in the error graph, as the prediction model continues to operate on visual input data captured before the sudden movement. Thus, the prediction error is propagated longer for higher prediction horizons. In our video\footref{fn:repeat}, you can find predictions sampled from $\hat{\mu}^{8}_{t}$ and~$\hat{\mu}^{16}_{t}$ and their corresponding predicted $\log\sigma_{t}^2$. These videos show the stochasticity of the predictions introduced by the sampling process, as the locations of the other pedestrians and cars jump forward and backward along their respective paths. For example, when the pedestrian ahead of the ego-pedestrian exits the crosswalk, % the 16-time-step prediction (\emph{predict16}) show the pedestrian's position jumping laterally from frame to frame. We interpret that as an inherent uncertainty learned by our model (pedestrians may turn left or right at the end of the crosswalk). Since our pedestrian's world model is capable of predicting the future and given its inherent stochasticity, it can be used to produce new reasonable traffic scenarios of its own. Here, we present an initial approach to investigating this, given a~predefined sequence of actions to recreate the ego-pedestrian's behavior in the crossing scenario described in Sec.~\ref{section:segmentation}. We loop back the predicted frames into the prediction model (see Fig.~\ref{fig:dream}) and obtain very innovative new crossing scenarios. We chose a~relatively high temperature parameter value $\tau = 0.4$, which still outputs scenarios with reasonable randomness. Low temperature values would result in less innovative, more deterministic scenarios, i.e., the world model would devise fewer pedestrians and vehicles into the scene because they are the main cause of randomness. At $\tau = 0$, the world model doesn't include any pedestrian or vehicle in the output scenarios. In the example output scenario video\footref{fn:repeat}, although the model receives the same original first image and action sequence from the scenario mentioned above, it produces a~significantly different scenario. For example, the ego-pedestrian finds a~vehicle passing from the left side at the crossing, that doesnt exist in the original scenario (see Fig.~\ref{fig:dream}). \begin{figure} \centering \includegraphics[width=8.5cm,trim={1cm 0.3cm 1cm 1.4cm},clip]{./fig/error_mu_euclidean} \caption{\label{fig:mu_error}Prediction error for one scenario of the pedestrian crossing the street at different prediction horizons $r \in \{1, 8, 16\}$, given as error per time step. The error is the Euclidean distance between $\mu_{t}$ generated by the VAE at $t$ and prediction $\hat{\mu}^{r}_{t}$ for time step $t$ generated by the LSTM at time step $t-r$.} \end{figure} \section{Conclusion} We have presented our toolchain for (a)~acquiring synthetic data of pedestrians in urban environments, (b)~training a~combination of VAE and LSTM networks, (c)~predicting a~pedestrian's future perception, and (d)~using these networks as simplified simulators of a~pedestrian's environment. % As we provide only limited information to % our models during training, the task of predicting other road users' directions of motion may be of increased difficulty. Since the LSTM gets only one% ~$z_t$ as an input, it may not be able to detect the direction of movement of pedestrians, if they are only represented as a~blob without movement-defining features. By exploiting the inherent stochastic models encoded in the LSTM networks, we can easily generate an ensemble of varied pedestrian behaviors. Similarly, qualitatively different behaviors can be generated by adding more hand-coded finite state machines. The scenarios (pedestrian crossing, streets, types and numbers of road users, etc.) can easily be varied. % We will train % a simple neural network as a~pedestrian agent exploring our world model. This agent will feed our LSTM with movement commands based on the (predicted) latent vector as input. % This pedestrian agent's behavior might help to provide more relevant traffic situations to source more training data and improve the world model. Using this toolchain, we can numerically obtain statistical predictions of future pedestrian positions. This statistical data can then be used to guide the decision making of an autonomous vehicle. As future work, we plan to implement the required geometric calculations to derive the considered pedestrian's view based on the autonomous vehicle's perspective. As there will usually be occlusions and hence unknown areas within the pedestrian's visual view, we plan to use machine learning also to realistically fill these gaps~\cite{yu2019free}. In future work, we will acquire real-world videos of pedestrian perspectives and expand our approach to translate to the real world. We are confident that this completed toolchain can be applied in autonomous driving for the advantage of vulnerable road users. Since the complexity of actively developing traffic scenarios is high, VAE and LSTM might not be suitable modeling tools anymore. Therefore, we will look at transformers~\cite{liu2020convtransformer} to replace both components, encoding and prediction of traffic. % % % % % \bibliographystyle{unsrt}
{'timestamp': '2022-03-23T01:23:38', 'yymm': '2202', 'arxiv_id': '2202.13981', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13981'}
arxiv
\section*{Introduction} Since the coronavirus disease 2019 (COVID-19) was initially detected in December 2019, a novel coronavirus designated as the severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2) has rapidly spread across the world and led to a global pandemic \cite{world2020statement}. Despite increasingly more people getting vaccinated every single day, the world is still struggling to combat the emerging more contagious COVID-19 variants and has witnessed wave after wave of the epidemic here and there. As of 22 February 2022, a total number of 426,624,859 confirmed cases and 5,899,578 deaths due to the virus have been reported in 228 countries or territories globally according to the World Health Organization (WHO) \cite{WHOCovid19}. To contain the coronavirus outbreak, non-pharmaceutical interventions (NPIs) have been used widely as key weapons in some countries that were impacted heavily early on with satisfying effects \cite{flaxman2020estimating}. For instance, the world’s first stringent COVID lockdown sparked in Wuhan, the original epicenter of the pandemic. Specifically, China enacted travel bans to and from the city for 76 days and launched nationally coordinated efforts to mitigate the impact of the epidemic until it was eventually under control \cite{prem2020effect}. Similarly, in Italy, one of the European countries hardest hit by COVID-19, the national quarantine enforced on March 8, 2020, showed immediate effects on daily new infections within around two weeks \cite{CNN_2020}. Singapore is another country that adopted aggressive strategies and maintained a low casualty rate (0.15\%) compared to the global average (1.38\%) \cite{WHOCovid19}. Besides making striking achievements in real-world settings, the effectiveness of COVID-19 NPIs has also been extensively studied in the literature. Among them, a large body of research was targeted at the epidemiological implications of NPIs. Utilizing compartmental models, scholars simulated and predicted the effects of NPIs on multiple epidemic indicators, including infections \cite{davies2020effects,prem2020effect,cot2021mining,lai2020effect,flaxman2020estimating,ihme2020modeling,abueg2021modeling,singh2021impacts}, deaths \cite{lai2020effect,ragonnet2021genetic,flaxman2020estimating,ihme2020modeling,abueg2021modeling}, the reproduction number \cite{bo2021effectiveness,prem2020effect,flaxman2020estimating,ihme2020modeling}, and demand for hospital services \cite{davies2020effects,abueg2021modeling}. Touching on similar themes, another line of research focused more on quantifying the effects of NPIs on mobility \cite{hu2021big,askitas2021estimating,levin2021insights} and further explored the relationship between human movements and COVID-19 transmission \cite{cot2021mining,woskie2021early,oh2021mobility,ilin2021public}. Apart from characterizing the unfolding of the COVID-19 pandemic from an epidemiological perspective, there are also studies investigating the impact of NPIs from various angles covering economic contraction \cite{demi2020sooner,sheridan2020social,zaremba2020infected,demi2020sooner}, social issues \cite{zhang2020changes,abuhammad2021violence}, and mental health \cite{sutin2020change,luchetti2020trajectory,alzueta2021covid,sadikovic2020daily}. Some key findings summarized from the current state of knowledge include: (1) the imposition of appropriate NPIs is necessary to curb the spread of the virus \cite{flaxman2020estimating,oh2021mobility,ilin2021public}; (2) the effectiveness of individual intervention alone is usually limited and combined use of multiple NPIs is required \cite{ferguson2020report,lai2020effect} and; (3) fixed strategies of NPIs might be less effective than those with time-varying adjustment mechanisms \cite{nascimento2021reopening}. The encouraging precedents and research basis above demonstrate the role that NPIs can play in controlling the COVID-19 and offer valuable references for other affected regions to handle the spiraling outbreak. However, as time goes by, the situation has now become further complicated and highlighted some limitations of the current literature. First, the emphasis of many previous studies is on the epidemic simulation modeling of COVID-19 for more accurate forecasts without a thorough discussion of the relationships between human mobility and virus transmission that are deeply intertwined. In addition, given the core concern of handling the ongoing pandemic has shifted from containing the spread of the coronavirus only to restoring the social and economic order in the new normal from a long-term perspective, particular attention should be paid to multi-objective thinking in the design of policy strategies. Moreover, most of the above-mentioned successes were achieved by imposing harsh measures before vaccines became available, still comparatively little is known about how to devise policy frameworks that enable authorities to maintain a delicate balance between protecting public health and minimizing socio-economic disruption when the population are partly vaccinated against the COVID-19. To contribute in this direction, we choose the U.S. as the focus in the study due to its decentralized decision-making system, which leads to the implementation and enforcement of control measures highly variable in both time and space across the country with various circumstances for discussion. To get an overall picture of each state government’s NPIs in response to coronavirus, we employed the COVID-19 U.S. state policy Database \cite{raifman2020covid} and considered nine typical policies as listed in Table \ref{tab1:NPIs}. The adoption of these NPIs over time and space in the U.S. is presented in Fig. \ref{fig1:policy_timeline}. We further divide the observation period into two main phases according to when the lockdown restrictions and COVID-19 vaccine distribution started in the country. Some general patterns we find include: (1) most states rolled out the strictest lockdown measures in April 2020 to fight against the first wave and gradually rolled back the restrictions as the curve of infections started to flatten; (2) to control the subsequent waves in late June and mid-November 2020, NPIs were reimplemented, however, the number of states participated is much smaller than previously and; (3) since the COVID-19 vaccines were administered, the NPIs were gradually lifted in most states. \begin{table}[ht] \centering \begin{tabular}{||c|c|c||} \hline \textbf{Label} & \textbf{Policy Name} & \textbf{Description} \\ \hline \hline \textbf{\textbf{P1}}& State of emergency & A state issued any type of emergency declaration \\ \hline \textbf{\textbf{P2}} & Face mask in businesses & Mandate face mask use by employees in public-facing businesses \\ \hline \textbf{\textbf{P3}}& Close child care & A state closed day cares statewide \\ \hline \textbf{\textbf{P4}} & Close restaurants & A state closed restaurants (except for take out) \\ \hline \textbf{\textbf{P5}} & Close movie theaters & A state closed movie theaters statewide \\ \hline \textbf{\textbf{P6}}& Close non-essential businesses & A state closed non-essential businesses statewide \\ \hline \textbf{\textbf{P7}}& Stay at home & A state issued statewide stay at home/shelter in place order \\ \hline \textbf{\textbf{P8}} & Close bars & A state closed bars statewide \\ \hline \textbf{\textbf{P9}} & Close gyms & A state closed indoor gyms/fitness centers \\ \hline \end{tabular} \caption{\label{tab1:NPIs} Summary of typical NPIs considered and corresponding descriptions.} \end{table} \begin{figure*}[h] \centering \includegraphics[width=16cm]{1Fig_Policy_Date.png} \caption{Implementation of anti-contagion policies in response to the COVID-19 over time and space in the United States. (\textbf{a}) Percentage of states with the COVID-19 policies being enacted over time. Two vertical dashed lines represent the start dates of COVID-19 policy deployment and vaccine distribution, respectively. (\textbf{b}) Maps of number of NPIs implemented by the states on three representative dates. April 19, 2020 represents the period with the most stringent lockdowns. December 13, 2020 is the day before COVID-19 vaccines were administered in the U.S.. August 18, 2021 is the last day of the observation period.} \label{fig1:policy_timeline} \end{figure*} Using the COVID-19 policy dataset along with epidemiological and mobility data aggregated at the state level, we propose a methodological framework to quantify the underlying relationships between mobility and key measures of population-level transmission in the context of the COVID-19 pandemic both before and after the vaccines became available in the U.S.. We further evaluate the effectiveness of current combinations of NPIs applied in individual states and identify new optimal strategies that can well balance the public health and socio-economic impacts in the fight against coronavirus. Finally, we investigate the similarities and differences across states and phases to provide new insights into the spatio-temporal dynamics for epidemic control. The findings enable policymakers to better understand the rapidly evolving nature of the pandemic and signpost optimal and more flexible solutions that can adapt to changing needs and circumstances. \section*{Results} \subsection*{Temporal associations between COVID-19 transmission, population mobility, and state policies} Apart from the database of NPIs, we also employ daily COVID-19 case data from the New York Times \cite{NYT2021} and aggregated mobility data from Unacast \cite{Unacast_mobility} to draw a comprehensive comparison of the temporal variations in virus transmission, mobility patterns, and policies during the COVID-19 outbreak. Here, two mobility metrics utilized are relative percentage changes in visits to non-essential venues and average travel distance compared to the corresponding day of week prior to the COVID-19 outbreak for a given date. We map the timelines of the state government policy actions against the daily new reported cases, human mobility trends, and instantaneous reproduction number $R_t$ estimated by the susceptible-exposed-infectious-recovered-susceptible (SEIRS) epidemic model \cite{bjornstad2020seirs}(see the Methods) in Fig. \ref{fig2:Timeline_m}. Here, $R_t$ is a key indicator to monitor the real-time transmissibility of the virus and to estimate the impact of local NPIs on the epidemic. \begin{figure*}[h] \centering \includegraphics[width=17cm]{2Timeline_Merge818.png} \caption{Temporal changes in daily new COVID-19 cases, travel distance difference, visitation difference, instantaneous reproduction number $R_t$ and policy implementation in the ten states with highest number of confirmed cases from February 24, 2020 to August 18, 2021. 7-day moving average is utilized to smooth volatile case reporting data and human mobility metrics. The start dates of policy implementation and vaccine distribution are indicated by dashed vertical lines. A horizontal line is drawn at $R_t$=1. If $R_t$ is greater than 1, the epidemic is expanding at time $t$, whereas $R_t<1$ signals that the epidemic is shrinking. } \label{fig2:Timeline_m} \end{figure*} As Fig. \ref{fig2:Timeline_m} suggests, the state authorities generally started to take measures at the exact time when the highest $R_t$ appeared and employed the NPIs again when the coronavirus spikes were reaching alarming levels during the subsequent waves. One can also notice that the mobility level seems to be an indicator of how stringent the local NPIs are. In the beginning, when the states adopted the strictest interventions, the population mobility experienced a sharp decline from peak to trough in all the states. Then with the adjustments of the NPIs and the application of vaccines, the relative reduction in mobility also changed accordingly. In terms of the relationships between new infections and human mobility, the relevant curves in Fig. \ref{fig2:Timeline_m} hint at the existence of time-lagged associations, which will be further investigated through vector autoregression model \cite{sims1980macroeconomics} and Granger causality analysis \cite{Granger:1969} next. Moreover, other intertwined relationships between NPIs, mobility patterns, and the spread of the virus that we have a glimpse into here will also be explored using multiple linear regression later. Due to space limitations, we only display the detailed analysis results of California and key findings of the other nine states severely affected by the pandemic as examples in the main text. Additional findings of other states in the U.S. are presented in Supplementary Information. \subsection*{Temporal lagged relationships between mobility and viral transmissibility} Prior to examining the dynamic linkages between human mobility and virus transmission, we display basic descriptive statistics in Table \ref{tab2:Descriptive_statistics} and time series of variables selected in Fig. \ref{fig3:CA_RtV}. Here we employ a sub-period analysis to explore how variables and the relationships between them changed over time before and after the administration of the COVID-19 vaccines. Table \ref{tab2:Descriptive_statistics} and Fig. \ref{fig3:CA_RtV} present that $R_t$ in California experienced a significant decrease from up to 3.469 in phase 1 to below 1 during phase 2. In terms of the mobility changes, a clear pattern emerged is that California suffered relatively greater declines in travel distance and visits during phase 1 compared to its counterpart. In addition, as Fig. \ref{fig3:CA_RtV} depicts, the strategies adopted during phase 1 are generally more diverse and stricter than those in phase 2. A visual inspection in Fig. \ref{fig3:CA_RtV} suggests that $R_t$ and \textit{VD} show opposite trends in general with temporal lagged associations and present different tendencies before and after the advent of the vaccines. \begin{table}[ht] \centering \begin{tabular}{||c|c|c|c|c|c|c|c|c|c|c||} \hline &\multicolumn{5}{c|}{\textbf{Phase 1 (Mar.4 2020 - Jan.12 2021)}} & \multicolumn{5}{c||}{\textbf{Phase 2 (Jan.13 2021 - Aug.18 2021)}}\\ \cline{2-11} \textbf{Variables} & \textbf{\textit{NC}} & \textbf{\textit{ND}} & \cellcolor{Mycolor1} $\bm{R_t}$ & \textbf{\textit{TD}} & \cellcolor{Mycolor1}\textbf{\textit{VD}} & \textbf{\textit{NC}} & \textbf{\textit{ND}} & \cellcolor{Mycolor2}$\bm{R_t}$ & \textbf{\textit{TD}} & \cellcolor{Mycolor2}\textbf{\textit{VD}}\\ \hline \hline \textbf{Mean} & 8934 & 99 & 1.255 & -0.309 & -0.489 & 6503 & 157 & 0.721 & -0.217 & -0.437 \\ \hline \textbf{Min} & 10 & 0 & 0.746 & -0.485 & -0.726 & 883 & 16 & 0.680 & -0.517 & -0.628 \\ \hline \textbf{Max} & 44768 & 531 & 3.469 & -0.024 & -0.044 & 39587 & 561 & 1.021 & 0.117 & -0.040 \\ \hline \textbf{Std.Dev.} & 11780.600 & 90.258 & 0.588 & 0.102 & 0.110 & 7253.021 & 169.436 & 0.062 & 0.182 & 0.091 \\ \hline \end{tabular} \caption{\label{tab2:Descriptive_statistics}Summary statistics for COVID-19 and mobility variables in California during different phases. Phase 1 represents the period when NPIs have been adopted but no vaccines had become available yet, while phase 2 represents the time when the NPIs and vaccines were deployed together. \textit{NC} represents daily new reported cases. \textit{ND} means daily new deaths. Mobility variables of \textit{TD} and \textit{VD} represent the changes in average travel distance and visits compared to those for the same day of week during non-COVID-19 time period, respectively.} \end{table} Based on the preliminary observations, we explore multiple temporal dynamic relationships between transmission and mobility variables in a bivariate setting by using vector autoregressive models \cite{sims1980macroeconomics} and the Granger causality tests \cite{Granger:1969}. For clarity, we will take the tests between $R_t$ and \textit{VD} as an example to illustrate in detail how the techniques are employed below. Vector autoregression (VAR) \cite{sims1980macroeconomics} is a widely used statistical method for multivariate time series analysis. Granger causality analysis \cite{Granger:1969} was initially developed in econometrics as a technique for investigating the directed interactions between time-series data \cite{stokes2017study}. This statistical concept of causality is based on the prediction that a time series \textbf{\textit{x}} (\textit{VD}) Granger causes another time series \textbf{\textit{y}} ($R_t$) if the autoregressive forecast of \textbf{\textit{y}} can be better explained when the past information from \textbf{\textit{x}} is considered \cite{papagiannopoulou2017non}. After determining the maximum order of integration ($d$) and optimal time lag length ($m$) for $R_t$ and \textit{VD} (see Supplementary Table 1-2), we establish bivariate augmented VAR models for the two phases in California, based on the idea of the Toda-Yamamoto Granger causality test \cite{toda1995statistical} (see the Methods) as follows: \begin{equation}\label{eq2} y_t = \gamma +\sum_{i=1}^{m+d}\alpha_{i}y_{t-i}+\sum_{i=1}^{m+d}\phi_{i}x_{t-i}+\varepsilon_{t} \end{equation} \noindent where $y_t$ denotes the value of the time series \textbf{\textit{y}} at time $t$, $i$ is the length of the lag-time moving window, $\alpha_i$ and $\phi_i$ are the parameters to estimate, $\epsilon_t$ refers to the white noise residual. The variables of \textbf{\textit{x}} and \textbf{\textit{y}} can be interchanged to test for the Granger causality in the other direction. \begin{figure*}[h] \centering \includegraphics[width=15cm]{3Fig_CA_Rt_V.png} \caption{Temporal changes in $R_t$, \textit{VD}, and COVID-19 policy implementation in California during two phases. The start dates of policy implementation and vaccine distribution are indicated by dashed vertical lines. Existing policy sets and their frequencies are displayed in (\textbf{b}). The temporal distribution of the policy sets is presented on the bottom of (\textbf{a}). The curves of $R_t$ and \textit{VD} are perceived as more tortuous in phase 1. After the vaccines were released, \textit{VD} roughly showed a rising trend and $R_t$, in contrast, declined gradually and kept steady below 1 with a slight increase displayed toward the end of observation.} \label{fig3:CA_RtV} \end{figure*} The results in Table \ref{tab3:GC_CA} suggest that the Granger causality relationship from $R_t$ to $VD$ is statistically significant at the 1\% level during phase 1 in California, but not significant for phase 2. The phenomena can be interpreted as people reacting to the news about confirmed coronavirus cases by changing their mobility patterns significantly in phase 1. This behavioral response, however, is not that evident after the vaccines were available, hinting to the fact that people felt more protected by vaccines and less keen on constraining their movements. To look in the other direction, it is found that the null hypothesis of no Granger causality from $VD$ to $R_t$ can be rejected at the 10\% significance level during phase 2, which implies that the visitation change of individuals in California Granger causes the transmission of the COVID-19 during the period of phase 2. Apart from the variable pair of $R_t$ and $VD$, the Toda and Yamamoto causality test is also performed between other possible pairs of the epidemiological and mobility variables following this framework. It can be observed from Table \ref{tab3:GC_CA} that bi-directional Granger causality emerged between variable pairs of ($ND$, $TD$) in both phases and ($ND$, $VD$) in phase 2. Moreover, all the test results for $ND$ during phase 2 reject the null hypothesis at the significance level of 1\%. For the corresponding tests between $NC$ and the two mobility variables, no Granger causality relationship is found at the 1\% significance level. This observation of stronger Granger causality relationships existing between $ND$ and mobility patterns compared to those of $NC$ seems to be consistent with the research findings of some previous papers \cite{ku2020epidemiological, flaxman2020report,hadjidemetriou2020impact}, in which death count was considered as a more reliable metric over daily infections, since the actual number of infected cases is expected to be significantly larger than what has been reported. It is also noticeable that the optimal lag lengths selected according to information criteria for $ND$ and two mobility metrics are higher than those of $NC$ of around one to two weeks, which may correspond to the length of treatment. \begin{table}[ht] \centering \begin{tabular}{||c|c|c|c|c|c|c|c|c||} \hline &\multicolumn{4}{c|}{\textbf{Phase 1 (Mar.4 2020 - Jan.12 2021)}} & \multicolumn{4}{c||}{\textbf{Phase 2 (Jan.13 2021 - Aug.18 2021)}}\\ \cline{2-9} \textbf{Direction} & \textbf{Lag(m)} & \textbf{Lag(m+d)} & \textbf{Chi-square} & \textbf{Prob.} & \textbf{Lag(m)} & \textbf{Lag(m+d)} & \textbf{Chi-square} & \textbf{Prob.}\\ \hline \hline $\bm{R_t}$ $\rightarrow$ \textbf{\textit{VD}} & 2 & 2 & $16.086^{***}$ & \cellcolor{Mycolor1}{0.000} & 9 & 10 & 11.680 & \cellcolor{Mycolor2}{0.307} \\ \hline \textbf{\textit{VD}} $\rightarrow$ $\bm{R_t}$ & 2 & 2 & 2.531 & \cellcolor{Mycolor1}{0.282} & 9 & 10 & $16.209^{*}$ & \cellcolor{Mycolor2}{0.094} \\ \hline$\bm{R_t}$ $\rightarrow$ \textbf{\textit{TD}} & 2 & 3 & 4.544 & 0.208 & 8 & 9 & 5.687 & 0.771 \\ \hline \textbf{\textit{TD}} $\rightarrow$ $\bm{R_t}$ & 2 & 3 & 1.449 & 0.694 & 8 & 9 & 5.520 & 0.787 \\ \hline \hline \textbf{\textit{NC}} $\rightarrow$ \textbf{\textit{VD}} & 9 & 10 & 4.565 & 0.918 & 8 & 9 & $19.714^{**}$ & 0.020 \\ \hline \textbf{\textit{VD}} $\rightarrow$ \textbf{\textit{NC}} & 9 & 10 & 9.258 & 0.508 & 8 & 9 & $16.648^{*}$ & 0.055 \\ \hline \textbf{\textit{NC}} $\rightarrow$ \textbf{\textit{TD}} & 8 & 9 & $18.044^{**}$ & 0.035 & 8 & 9 & 7.689 & 0.566 \\ \hline \textbf{\textit{TD}} $\rightarrow$ \textbf{\textit{NC}} & 8 & 9 & 10.722 & 0.295 & 8 & 9 & 4.660 & 0.863 \\ \hline \hline \textbf{\textit{ND}} $\rightarrow$ \textbf{\textit{VD}} & 16 & 17 & 13.924 & 0.672 & 23 & 24 & $51.655^{***}$ & 0.001 \\ \hline \textbf{\textit{VD}} $\rightarrow$ \textbf{\textit{ND}} & 16 & 17 & 15.914 & 0.530 & 23 & 24 & $46.339^{***}$ & 0.004 \\ \hline \textbf{\textit{ND}} $\rightarrow$ \textbf{\textit{TD}} & 23 & 24 & $35.936^{*}$ & 0.056 & 20 & 21 & $57.509^{***}$ & 0.000 \\ \hline \textbf{\textit{TD}} $\rightarrow$ \textbf{\textit{ND}} & 23 & 24 & $46.526^{***}$ & 0.004 & 20 & 21 & $58.966^{***}$ & 0.000 \\ \hline \end{tabular} \caption{\label{tab3:GC_CA}Toda-Yamamoto Granger causality test results for transmission and mobility variable pairs in California. ***, **, and * indicate the rejection of the null hypothesis at the 1\%, 5\% and 10\% significance levels, respectively.} \end{table} To check if the VAR models are well specified, we also conducted a series of statistical tests (See Supplementary). The underlying temporal associations between the spread of coronavirus and mobility patterns discovered in this subsection will be considered in the following Pareto analyses for the assessment and optimal design of the NPIs. \subsection*{Pareto optimality for COVID-19 policy assessment and design.} In multi-objective optimization problems, the Pareto-efficient state is achieved if there is no other solution that can bring improvement to one of the objectives without showing degradation in another objective \cite{ngatchou2005pareto}. According to this, our multi-objective optimization problem can be defined as a vector function \textbf{\textit{f}} that maps a vector of policy decision variables \textbf{\textit{p}} to a tuple of two objectives \textbf{\textit{h}} as follows: \begin{equation} \begin{aligned} \text{minimize: } &\textbf{\textit{f}}(\textbf{\textit{p}}) = min \left \{ w_1f_1(\textbf{\textit{p}}), w_2f_2(\textbf{\textit{p}})\right \}\\ \text{subject to: } &\textbf{\textit{p}} = (p_1,p_2,...,p_k) \in P \\ &\textbf{\textit{h}} = (h_1,h_2) \in H \end{aligned} \end{equation} \noindent where $k$ is the number of policy types, $P$ is the policy space, and $H$ is the objective space. In our case, the optimization goal is to strike a delicate balance between the control of the COVID-19 virus and the recovery of socio-economic vitality, which are indicated specifically by $R_t$ and \textit{VD}, respectively. These two variables are chosen because we consider the estimated $R_t$ a more comprehensive metric to measure the transmissibility of the epidemic and visitation frequency a more appropriate indicator of socio-economic vitality. Based on this assumption, one of the objectives in our research task is to minimize the reproduction number of the virus $f_r(\textbf{\textit{p}})$. In the meanwhile, the value of visitation metric $f_v(\textbf{\textit{p}})$ is expected to be maximized. Accordingly, we set the values of $w_1$ and $w_2$ to 1 and -1. Consider two policy decision vectors $\textbf{\textit{a}}, \textbf{\textit{b}} \in P$. The policy decision vector $\textbf{\textit{a}}$ is said to dominate $\textbf{\textit{b}}$ if their objective vectors $\textbf{\textit{f}}(\textbf{\textit{a}})$ and $\textbf{\textit{f}}(\textbf{\textit{b}})$ satisfy: \begin{equation} \begin{aligned} && f_r(\textbf{\textit{a}}) \leqslant f_r(\textbf{\textit{b}}) \wedge f_v(\textbf{\textit{a}}) > f_v(\textbf{\textit{b}}),\\ or && f_v(\textbf{\textit{a}}) \geqslant f_v(\textbf{\textit{b}}) \wedge f_r(\textbf{\textit{a}}) < f_r(\textbf{\textit{b}}) \end{aligned} \end{equation} \noindent Under such rules, a decision vector is said to be Pareto optimal if and only if there does not exist another solution that dominates it. The set of all the policy decision vectors that are not dominated by any other generates the Pareto optimal set, while the corresponding objective vectors are said to be on the Pareto frontier \cite{ngatchou2005pareto}. Identifying the Pareto frontier is particularly useful because it can provide policymakers with a group of optimal solutions to make a well-informed decision that balances the trade-offs between the public health concerns and socio-economic losses rather than a single-point solution. \subsubsection*{Evaluation of existing COVID-19 policy strategies.} We first use the notion of Pareto optimality to evaluate the performance of existing policy combinations. Specifically, for each given date $t$, we collect the corresponding value of visitation metric $v_t$ and estimate the reproduction number ${R}_t^{'}$ using the SEIRS epidemic model with temporal lagged effects considered (see Methods). These two features collectively form the two-dimensional space, in which Pareto-optimal set would be explored. For each Pareto-optimal point obtained, we can figure out the corresponding control measures implemented on a particular date for further investigation. The following offers the results of optimal solutions discovered using this approach in the actual scene. As can be observed from Fig. \ref{fig4:Pareto1_CA}, there are in total two and three unique Pareto optimal solutions for California in phase 1 and phase 2, respectively. Among them, the state of emergency (P1) is found to be the only individual policy present in all the optimal solutions. To discuss by phases, the combined power of stay-at-home order (P7), the closure of movie theaters (P5), gyms (P9), bars (P8), and wearing face masks in businesses (P2) is particularly strong when pending the availability of vaccines since they showed together in both of the optimal policy sets during phase 1. The closure of restaurants (P4) is the only policy type that distinguishes strategy S7 from S4. It is interesting to observe that the closure of restaurants is connected to a considerable reduction in $R'_{t}$, down to 0.769 from 1.206, confirming the relatively high risks of transmitting the virus during convivial activities such as dining in a group. However, closing restaurants also considerably reduces the mobility index, down to -0.393 from -0.319, confirming the trade-off between the need of containing the virus and socio-economic vitality. However, when it came to phase 2, a larger number of enacted control measures did not guarantee a smaller ${R}_t^{'}$. Instead, the lowest average ${R}_t^{'}$ is generated by a moderate policy strategy S3, where mask mandate is in place and only bars are closed. In addition, the slope of the Pareto frontier for phase 2 is greater than that for phase 1 in California, implying that the increase in ${R}_t^{'}$ is accompanied by a relatively larger recovery of $v_t$ when the vaccines became available. It should also be noticed that the solutions selected are considered equally good according to the Pareto optimality concept. To decide which solution to choose depends on the policy makers’ perspectives about the priority of the two objectives in the optimization task. For instance, if the decision-makers in California intend to relax policies to some extent so that they have as little as possible impact on the normal mobility of the residents in phase 1, the corresponding ${R}_t^{'}$ would be as high as 1.206 on average as solution S4 presents. \begin{figure*}[h] \centering \includegraphics[width=16cm]{4Pareto1_CA_2Phases_Table.png} \caption{Pareto optimal trade-offs between human mobility ($v_t$) and virus transmission (${R}_t^{'}$) in California during two phases. Purple-colored spots represent optimal solutions that are connected by dashed lines to visually estimate the Pareto frontier. Candidate points with a value of ${R}_t^{'}$ larger than 2 are filtered. Pareto optimal points with a ${R}_t^{'}$ between 0.7 and 1 are enclosed by green boxes for phase 1 and phase 2, respectively. Corresponding optimal policy strategies after duplicate elimination are displayed in lower sub-figures with average ${R}_t^{'}$ and $v_t$ listed in the tables beside them.} \label{fig4:Pareto1_CA} \end{figure*} \subsubsection*{Design of optimal control strategies for the COVID-19 pandemic.} Following the assessment of the existing policies, we explore possible new policy combinations that might be more effective than the current ones next by employing the non-dominated sorting genetic algorithm II (NSGA-II) \cite{deb2002fast} (see Methods). Specifically, we adopt multiple regression (see Methods) first to estimate the coefficient for each policy type in the prediction of $\hat{R}_t$ and $\hat{v}_t$ during different phases with temporal lags effects considered. These parameters calculated are then fed into the NSGA-II algorithm to generate the Pareto optimal solutions. Then the solutions with an estimated $\hat{R}_t$ no larger than the maximum mean ${R}_t^{'}$ of the existing optimal policy strategies are further selected. Different from the implementation of existing policies that are dummy-coded, the parameter estimated through the generic algorithm for each type of policy is a continuous variable, which can be interpreted as the strength of the policy enforcement, where a value closer to 1 represents the strength is relatively stronger, whereas closer to 0 indicates that the implementation of the policy is weaker. The optimization results for California during phase 1 is presented in Fig. \ref{fig5:Pareto2_CA_PnV}. Comparing these optimization results with those of the existing policy strategies, the last six potential solutions are found more optimized than S4 since they have both smaller $\hat{R_t}$ and larger $\hat{v_t}$. This observation suggests that exploring new possible strategies for better trade-offs between virus control and the maintenance of mobility is necessary. Among theses six optimal solutions, the NPIs of state emergency declaration (P1), wearing face masks in businesses (P2), closing restaurants (P4), movie theaters (P5), and gyms (P9), and issuing stay-at-home order (P7) are expected to be implemented together with strong strengths. In contrast, the closure of non-essential businesses (P6) seems to be not very necessary, which is in accordance with the phenomenon observed in the evaluation of existing optimal strategies previously. The main distinctions between the potential optimal solutions discovered here from the existing ones for phase 1 lie in the adoption of P3 and P8. Essentially, the new proposed optimal solutions put more emphasis on the importance of closing child care centers and the flexible adjustment of the shutdown of bars. \begin{figure*}[h] \centering \includegraphics[width=17cm]{5Pareto2_CA_1PhasePnV_Table.png} \caption{Potential Pareto optimal policy strategies generated for California in phase 1. (\textbf{a}) visually presents the Pareto solutions. Spots and dashed line in purple represent the analytically derived Pareto optimal set and frontier. Optimal points with a $\hat{R}_t$ less than 1.206 are selected. Corresponding parameters estimated for the policy types are displayed in (\textbf{b}) with predicted $\hat{R}_t$ and $\hat{v}_t$ listed in the right table. Orange rectangle highlights the solution similar to the existing strategy of S7; and, coral ones highlight more optimized solutions. Predicted values of the two objectives are summarized in the table.} \label{fig5:Pareto2_CA_PnV} \end{figure*} \begin{figure*}[h] \centering \includegraphics[width=17cm]{6Pareto2_CA_2Phases_Table.png} \caption{Potential Pareto optimal policy strategies generated for California in phase 2. (\textbf{a}) visually presents the Pareto solutions. Optimal points with a $\hat{R}_t$ no more than 0.694 are selected. Corresponding parameters estimated for the policy types are displayed in (\textbf{b}) with predicted $\hat{R}_t$ and $\hat{v}_t$ listed in the right table. Orange rectangles highlight the solution similar to the existing strategy of S3.} \label{fig6:Pareto2_CA_PV} \end{figure*} While for the design of optimal strategies for California in phase 2 (Fig. \ref{fig6:Pareto2_CA_PV}), it presents a significantly different pattern from that for phase 1. Specifically, the overall strength of the policies for phase 2 is relatively weaker, and the solutions generated are more heterogeneous. In addition, policymakers in California should also shift the focus of the policy types to wearing face masks in businesses (P2) and closing bars (P8) in phase 2. In the meantime, the closures of restaurants (P4), movie theaters (P5), gyms (P9), and the implementation of the stay-at-home order (P7) during this period are considered less significant than those during phase 1. To provide a clearer picture of how to sketch out the implementation plans, we then replace policy parameters that fall within the ranges (0, 0.5) and (0.5, 1) as 0 and 1, respectively. This simplified version of the optimal policy scheme is shown in Fig. \ref{fig7:Pareto2_filter_all}, from which we can see that there are five and six types of optimal policy strategies extracted for phase 1 and phase 2 in California, respectively. Among them, the current solutions of S7 and S3 are included, while the other nine potential optimal strategies that may achieve better or equally good performance compared to the existing ones offer decision-makers a list of possible alternatives in the fight against coronavirus. \begin{figure*}[h] \centering \includegraphics[width=17cm]{7Pareto2_States10.png} \caption{Optimal response strategies generated by NSGA-II for ten states with the highest number of confirmed COVID-19 cases during different phases. Strategies for each state are listed in ascending order of the average predicted $\hat{R_t}$. If more than five optimal solutions are distilled for a certain state and phase, only the top five strategies are retained. Orange rectangles mark solutions already included in the existing strategies for the state; and, coral rectangles highlight more optimized ones.} \label{fig7:Pareto2_filter_all} \end{figure*} Following the same framework, we conduct analyses for other states and display their simplified optimal strategies in Fig.\ref{fig7:Pareto2_filter_all}. From the view of comparisons across space and time, following major findings emerge: (1) the differences between optimal policy designs for the ten states studied are evident, indicating the necessity of adopting differentiated and tailor-made COVID-19 response strategies in each individual state; (2) existing policy strategies (enclosed by orange rectangles) seldom appear in the list of new proposed ones, suggesting that there are a considerable number of alternatives available for COVID-19 prevention beyond current policy programs; (3) new solutions generated that are more preferable than the current ones (enclosed by coral rectangles with smaller $\hat{R_t}$ and higher $\hat{v_t}$) show in the first phase of some states (California, Illinois, and North Carolina), offering potential solutions that could be considered to replace the existing ones to policymakers; (4) for each state, two different phases present widely divergent strategies regarding policy types and amount of enacting policies. Specifically, the designs for phase 2 include fewer policy types and amounts compared to phase 1 in general, the phenomenon of which may be explained by the availability of vaccines in phase 2 when the control of COVID-19 no longer relies solely on the NPIs. \section*{Discussion} In this paper, we propose a flexible decision support system that allows state policymakers to evaluate and create refined COVID-19 policy strategies based on the art of balancing public health and socio-economic vitality. Here tailor-made adjustment schemes and novel optimal policies in response to the COVID-19 pandemic are generated for state authorities to choose depending on their priorities and current vaccination status. This can be achieved through the joint utilization of epidemiological data, mobility data, NPIs, and in-depth exploration of the dynamic relationships between them by fusing multiple techniques. We started with a discussion of the intertwined associations among the spread of the virus, policy implementation, and human mobility during different phases and discovered some prevailing patterns across the states (Fig. \ref{fig2:Timeline_m} and Supplementary Fig. 2-5). For instance, the state governments generally began to implement NPIs when the $R_t$ was at its maximum. In addition, human mobility can be used as a proxy for NPIs that it dropped steeply to the lowest level when the most stringent NPIs were issued in the early stages of the pandemic. Then with the subsequential relaxation and tightening of NPIs later on, human mobility levels also changed accordingly. The emergence of COVID-19 vaccines introduced new variables into these interrelationships. Some states (e.g., CA, IL, PA, MI, MN, WA, IA, and OR) began to loosen their NPIs, which coincided with virus transmission decline and human mobility increase. Another key observation that warrants further investigation is the existence of underlying temporal associations between human mobility and virus transmission, which might be bidirectional and dynamic. For instance, people would adjust their travel behaviors if they saw a dramatic rise in coronavirus cases; and the changes in mobility trends would, in turn, affect the confirmed cases in a few days. The results of VAR models prove the existence of temporal lagged effects as well as Granger causality relationships between some transmission and mobility variable pairs during different phases (Table \ref{tab3:GC_CA}). With regard to the variable pair of ($R_t$, $VD$) that we pay particular attention to, significant Granger causality relationships are largely discovered in the states affected the most by coronavirus in the U.S. (Supplementary Table 4). Here for each state, at least one direction in one phase offers results that are significant at the 5\% level. These findings help deepen our understanding of the transmission dynamics of COVID-19 and human behaviors by uncovering the intertwined temporal associations between them, and thus enable more holistic policy-making with temporal effects taken into account. We then evaluate the performance of existing policy strategies across the states using Pareto analysis, so as to offer policymakers a lens for looking back to identify effective policy combinations and adjust less effective ones in the future. For the pre-vaccine stage, to measure the contribution of policy types to health-economic balance individually, state of emergency (P1) and wearing face masks (P2) show as the most important NPIs that they appear in all the optimal strategies among the top ten states (Supplementary Table 5). The closure of recreational services (P8, P5, P9, P4) comes next with moderate impact, while essential businesses (P6) and child care centers (P3) do not present in any of the optimal strategies. From the perspective of the policy mix, the co-activation of P1 and P2 accounts for the largest proportion (30\%) and is present in the optimal strategies for six states (TX, FL, IL, GA, OH, NJ). The second most frequent policy combination is (P1, P2, P8), which accounts for 25\% of the optimal strategies. This finding implies that paying closer attention to the control of gathering sites where social scenes are more complex (e.g., bars) is particularly necessary before the advent of vaccines. Then when the COVID-19 vaccines were available, the percentage of each policy type shown in the optimal strategies has decreased in general (Supplementary Table 6). However, from a ranking view, what does not change compared to phase 1 is that the most effective individual policy types are still P1, P2, and P8. Finally, we employ NSGA-II algorithm to generate new optimal policy strategies for each state and phase. Here, the results reveal substantial differences between different phases and states. For instance, wearing face masks (P2) is particularly important for all the states in the pre-vaccine period (Supplementary Fig. 7-15). However, this is not the case in the later phase. The policy type of closing restaurants (P4) is essential for FL and NJ in phase 1, but not that important for the states of TX, NY, PA, and NC. In addition, new optimal solutions created differ significantly from the existing ones. In a nutshell, these findings illustrate the necessity of designing tailor-made new policy strategies through genetic algorithms for individual states and phases. The results obtained here can provide policymakers in each state with a general guiding policy formulation reference. It also enables them to compare the expected effects of potential optimal solutions with the performance of existing strategies and make more deliberate decisions regarding what kind of adjustments shall be made to the current schemes and how. Moreover, the implementation strategies proposed by our framework are spatio-temporal, context-aware, and more fine-grained than the existing policy schemes. This is reflected in the state-tailored considerations of temporal lag effects, Granger causality relationships, policy-based transmission and mobility predictions in a phase-wise manner. Furthermore, our framework also offers sophisticated implementation strategies that produce the strengths of policy enforcement as outputs for decision-makers. Our study has several limitations. First, we mainly focus on NPIs implementation in the regions with the most confirmed cases, since they play a more crucial role in combating the COVID-19 pandemic. However, an in-depth analysis of areas with fewer cases may raise other intriguing questions, such as why they performed relatively better in the fight against coronavirus. This sort of exploration may lead to a deeper understanding of how to improve the combined power of NPIs or offer novel insights into reasons for the effectiveness of control measures varies considerably across regions. This future investigation may require the additional use of demographic data, which can also help reveal the underlying logic of the results we have obtained. In addition, we perform COVID-19 policy-making optimization by considering two primary objectives in the study. However, many other aspects also need particular attention in the decision-making process in real-world settings, like the psychological distress and economic recession following the COVID-19 outbreak. In conclusion, we provide detailed insights into the spatio-temporal dynamics of the COVID-19 epidemic during different stages and highlight the essential role of some core intervention portfolios in the controlling of the pandemic. The methodology proposed here can offer policymakers reasoned estimates of the potential effectiveness of the NPIs to be attained and becomes even more critical when health systems are facing extreme loads. Furthermore, for other populations lacking local COVID-19 data and in the future similar circumstances for other emerging infectious diseases in which an outcome of interest is not yet available, the framework presented can also play a part. \section*{Methods} \subsection*{Epidemiological model.} We apply a modified SEIRS \cite{bjornstad2020seirs} compartmental model to detect the local spread of COVID-19 in the U.S. at different stages and estimate the effects of containment measures on the epidemic evolution in each state. In epidemiology, classical compartmental models provide a simplified representation of the mechanisms of virus propagation by dividing the population into different subgroups according to the infection status from the transmission process. Depending on the epidemiological characteristics and transmission patterns of infectious diseases, appropriate epidemic models should be chosen accordingly. Most notably, a canonical model used in this area is the SIR model \cite{kermack1927contribution}, in which individuals are assumed to be in one of three distinct epidemiological phases: susceptible (\textbf{\textit{S}}), infected (\textbf{\textit{I}}), and recovered (\textbf{\textit{R}}). \textbf{\textit{S}} represents a group of individuals who have not yet been infected by the virus; \textbf{\textit{I}} models infected people with symptoms of the disease who can spread the virus to individuals in the \textbf{\textit{S}} compartment; and, \textbf{\textit{R}} stands for those who have recovered from the disease and become immune to the virus. Considering the existence of incubation period, the SEIR model adds an exposed state (\textbf{\textit{E}}) between susceptibility and infection to the basic SIR model to represent individuals who have contracted the virus, showing no visible clinical signs of the disease, and may infect others. In recent decades, the SEIR model has been widely used for simulating the spread of infectious diseases, including severe acute respiratory syndrome (SARS) in 2002 \cite{lloyd2003curtailing}, H1N1 influenza in 2009 \cite{bajardi2011human}, and the 2014 Ebola virus outbreak in West Africa \cite{althaus2014estimating}. SEIR model has also been recently adopted in the analysis of the COVID-19 pandemic \cite{prem2020effect,peirlinck2020outbreak,linka2020outbreak}. The SEIR model assumes individuals carry lifelong immunity to the disease upon recovery, however, there have been clinical findings showing that patients who have recovered from COVID-19 can get reinfected with the virus \cite{radulescu2020management,ng2020covid,to2020covid}. Even though the immune response to this novel virus is not yet fully understood, the possibility of reinfection cannot be ruled out. To reflect this, we adopt a modified SEIRS model tailored for COVID-19 instead, allowing recovered individuals to return to the susceptible state after some time when their immunity vanishes. Moreover, an additional compartment representing the number of individuals died due to the virus is added in our model and is denoted by \textbf{\textit{D}}. It is the only compartment that would be removed from the total population \textbf{\textit{N}} and have no further interactions with the rest of the epidemic system. The coupled dynamics of the compartments are governed by the following set of ordinary differential equations: \begin{equation} \frac{dS(t)}{dt} = -\frac{\beta S(t)I(t)}{N(t)}+\xi R(t) \end{equation} \begin{equation} \frac{dE(t)}{dt} = \frac{\beta S(t)I(t)}{N(t)}-\sigma E(t) \end{equation} \begin{equation} \frac{dI(t)}{dt} = \sigma E(t)-(\gamma+ \mu)I(t) \end{equation} \begin{equation} \frac{dR(t)}{dt} = \gamma I(t) - \xi R(t) \end{equation} \begin{equation} \frac{dD(t)}{dt} = \mu I(t) \end{equation} \noindent where $\beta$ is the rate of infection transmission, which is normalized by $N(t)$, representing the total population at time $t$: $N(t) = S(t)+E(t)+I(t)+R(t)$. $\sigma$ denotes the incubation rate of latent individuals becoming symptomatic, and is calculated as the inverse of incubation period length of COVID-19. Similarly, $\gamma$ represents the recovery rate, the inverse of which is the average time an infected person needs to be recovered. In our model, patients are assumed to develop short-term immunity of $1/\xi$ days after recovering from the viral infection and become susceptible to the virus again. However, their unlucky counterparts who died from the virus at the fatality rate $\mu$ would be removed from the transmission process spontaneously. In compartmental epidemic models, a key parameter used to characterize the transmissibility of the virus is called the basic reproduction number ($R_0$). It corresponds to the average number of secondary cases generated by per infectious individual in a fully susceptible population and can be computed from the following equation: \begin{equation} R_{0}=\frac{\beta }{\gamma + \mu } \end{equation} \noindent While the $R_0$ is typically considered as a biological and clinical characteristic of a virus measuring how contagious the infectious disease is, it is also influenced by NPIs. The logic behind this is that a drastic reduction in mobility associated with the implementation of COVID-19 containment measures would decrease the contact rate between infected and susceptible individuals, leading to a decline in the estimated $\beta$ and $R_0$. Under this assumption, a sliding window-based extension of the SEIRS model is proposed to capture the real-time epidemic dynamics of the Coronavirus during different phases of intervention development. Specifically, using a sliding window of size $2n+1$, we calculate a time-varying transmission rate of the infection at time $t$ as: \begin{equation} {\beta(t)}' =\sum_{i = t-n}^{2n+1}\beta(i)/(2n+1) \end{equation} Based on the dynamic contact rate $\beta(t)'$, we then infer the instantaneous reproduction number $R_t$ to track the epidemic progression over time and estimate the impact of local interventions. Here, if $R_t$ is greater than 1, the epidemic is expanding at time $t$, whereas $R_t<1$ indicates that the epidemic is shrinking. The expression for the $R_t$ is: \begin{equation} R_t =\frac{\beta(t)'}{\gamma + \mu } \end{equation} \noindent It allows rapid detection of the ongoing evolution during the COVID-19 pandemic, taking the virus's epidemiological characteristics and human mobility patterns that may be significantly affected by local control measures into account. Specifically, we simulate the local spread of the COVID-19 pandemic in different states using the compartmental model introduced above, fitted with publicly available data from the New York Times \cite{NYT2021}. Disease-specific parameters in the model were derived from the recent literature, including a mean incubation period of 5.2 days (95\% confidence interval [CI] 4.1-7.0) \cite{li2020early}, an average recovery time of 8 days \cite{maier2020effective} and the mean time to death from onset of 17.8 days (95\% CI 16.9-19.2) \cite{verity2020estimates}. In addition, patients are assumed to develop temporal immunity of $\xi = 180$ days, after recovering from the initial infection of the virus \cite{seow2020longitudinal}. \subsection*{Granger causality analysis.} To introduce the idea of Granger causality more concretely, let \textbf{\textit{x}} $= [x_1, x_2, …, x_n]$ and \textbf{\textit{y}} $= [y_1, y_2, …, y_n]$ denote the two stationary time series of length $n$. To examine whether time series \textbf{\textit{x}} Granger causes \textbf{\textit{y}}, consider the following model: \begin{equation}\label{eq1} y_t = \gamma +\sum_{i=1}^{m}\alpha_{i}y_{t-i}+\sum_{i=1}^{m}\phi_{i}x_{t-i}+\varepsilon_{t} \end{equation} \noindent where $y_t$ denotes the value of the time series \textbf{\textit{y}} at time $t$, $i$ is the length of the lag-time moving window, $\alpha_i$ and $\phi_i$ are the parameters to estimate, $\epsilon_t$ refers to the white noise residual. In this setting, the Granger causality can be investigated based on an $F$ test with the null hypothesis of $H_0: \phi_1 = \phi_2 = ... = \phi_i = 0 $. Essentially, if $H_0$ is rejected, one can conclude that the Granger causality from time series \textbf{\textit{x}} to \textbf{\textit{y}} exists, since that the lagged values of \textbf{\textit{x}} provide additional explanatory and predictive power to the regression model. Based on the conventional Granger causality test introduced above, Toda and Yamamoto \cite{toda1995statistical} proposed a modified version that overcomes several limitations of traditional approaches in hypothesis testing when there are unit roots in the VAR system. Specifically, Toda and Yamamoto causality test does not require pre-testing for the cointegrating properties of the system, and thus avoids the potential bias associated with unit roots and cointegration tests \cite{clarke2006comparison, zapata1997monte}. Given these advantages of the Toda and Yamamoto causality test, we adopt this method in the present study. \subsection*{Multiple linear regression analysis.} Multiple linear regression analysis is used to assess the association between policy types and estimate regression coefficients. For each state, we build two multiple linear regression models, in which independent variables are policy types ${[p_1, p_2, …, p_k]}$, while the continuous dependent variables are $v_{t}$ and ${R_{t}}^{'}$, respectively. Here, ${R_{t}}^{'}$ denotes the temporal lagged reproduction number for date $t$ with individualized temporal relationships between the $v_{t}$ and $R_{t}$ in each state considered. The assumption here is that the changes in human mobility are visible on the same date when the NPIs are issued, while ${R_{t}}^{'}$ is determined by the temporal lagged associations between mobility and the spread of the coronavirus investigated using VAR model with Granger causality test. For instance, since there is a significant Granger causality relationship discovered from $R_{t}$ to $v_{t}$ with a lag of $m=2$ in California during phase 1, the corresponding ${R_{t}}^{'}$ for $v_{t}$ is equal to $R_{t-2}$. This operation applies to both of the Pareto analysis parts, including the evaluation of existing policy strategies and the design of new policy solutions. To accomplish the second task, the processed data is used to fit two multiple linear regression models for each phase in a state as follows: \begin{equation}\label{eq1} {R_t}^{'} = {\lambda_0}+{\lambda_1}{p_1}+{\lambda_2}{p_2}+\cdots+{\lambda_k}{p_k} \end{equation} \begin{equation}\label{eq1} {v_t} = {\eta_0}+{\eta_1}{p_1}+{\eta_2}{p_2}+\cdots+{\eta_k}{p_k} \end{equation} \noindent The estimated parameters of ${[\lambda_0, \lambda_1, \lambda_2, …, \lambda_k]}$ and ${[\eta_0, \eta_1, \eta_2, …, \eta_k]}$ are used for the prediction of $\hat{R_t}$ and $\hat{v_t}$ in the generation process of new optimal policy strategies. \subsection*{Pareto optimality.} The concept of Pareto efficiency \cite{pareto1964cours} is originally introduced to describe an economic state in which the reallocation of resources cannot make at least one person better off without making any other individual worse off \cite{Fudenberg1991}. To generate new policy strategies for each individual state, we employ the NSGA-II algorithm \cite{deb2002fast} by using the Platypus package \cite{hadka2019platypus} for multi-objective evolutionary computing in Python 3.7. NSGA-II differs from traditional genetic algorithms in two aspects: (1) the selection of appropriate individual solutions among possible ones to generate the next generation is based on their dominance levels according to the Pareto optimality; (2) The crowding distance is employed as a measure to make choices between individual solutions that have the same dominance level. Additionally, NSGA-II adopts an elitist strategy for the selection that unless better solutions are found, the best ones obtained so far are retained. The algorithm produces a set of optimal solutions that collectively make up the Pareto front when the optimization process is terminated \cite{yoo2010using}. \section*{Data Availability.} All data used in this manuscript are publicly available. COVID-19 epidemiological data are available from the New York Times at [https://github.com/nytimes/covid-19-data]\cite{NYT2021}. Daily aggregated mobility data at the state level are available for each state from Unacast [https://www.unacast.com/covid19/social-distancing-scoreboard]\cite{Unacast_mobility}. State-wide policies related to COVID-19 are collated by the researchers at the Boston University School of Public Health [https://github.com/USCOVIDpolicy/COVID-19-US-State-Policy-Database]\cite{raifman2020covid}. \section*{Code availability.} The code and processed data to reproduce tables and figures in the main text and Supplementary Information are publicly available on GitHub at: https://github.com/XiaoZHOUCAM/COVID-NPIs-Optimal.
{'timestamp': '2022-03-01T02:57:49', 'yymm': '2202', 'arxiv_id': '2202.13980', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13980'}
arxiv
\section{Introduction} Mitotic count is an important histologic parameter for cancer diagnosis and grading. Traditionally, mitotic count is obtained by manually counting mitotic figures through a light microscope. The hotspot area, usually spanning 10 high-power microscopic fields, that contain the highest density of mitotic figures in the whole histologic section(s) is identified and the number of mitotic figures in this area is reported as mitotic count. With the increasing use of digital pathology, whole slide image (WSI) is now routinely generated in several pathology laboratories. Nonetheless, mitotic count is still obtained by manual counting of mitotic figures on screen. Conventionally, the manual process of obtaining MI is tedious and error-prone \cite {Veta}. Thus, several studies \cite{PAN2021107038} have utilized machine learning algorithms to assist pathologists by automatically recognizing mitotic figures in the WSI and proposing the hotspot area. Recently, deep learning has gained popularity due to its impressive image recognition performance compared to traditional approaches and is now widely used in a wide range of digital pathology applications, including histopathological image analysis \cite{Srinidhi_2021}. Errors in mitotic figure detection by machine learning models can be attributed to the quality of data collection process and the ambiguity between mitotic figures in different cell division stages and other mitotic-like objects. First, each WSI is scanned on a single focal plane that could not be readjusted. As a result, many cells are out-of-focus and produce poor texture information. Additionally, the mitotic figures themselves can have diverse appearances across cell division stages and may be confused with other cell types or non-cell objects. Consequently, the classification of some mitotic figures could be highly subjective, which leads to drastically different mitotic counts reported by different experts \cite{Bertram2019ComputerizedCO}. Despite these problems, automated mitotic figure detection and mitotic count prediction is still considered as a crucial task in digital pathology and is an active area of research. To develop models for automatic mitotic figure detection, datasets with expert annotations, such as the ICPR MITOS-2012 \cite {MITOS2012}, AMIDA 2013 \cite{AMIDA13}, ICPR MITOS-ATYPIA-2014 \cite{noauthor_mitos-atypia-14_nodate}, and TUPAC16 \cite{TUPAC16} challenges, can be used. However, as these datasets contain mitotic figure annotations only in the high power fields (HPF) corresponding to the hotspot ares, the model cannot fully learn from majority of the WSIs that were unannotated. Moreover, the number of the annotated mitotic figures in these datasets are low, often less than one thousand objects each. Recently, two large-scale mitotic figure datasets with annotations covering the whole slides have been released: the canine cutaneous mast cell tumor (CCMCT) \cite{CCMCT} dataset and the canine mammary carcinoma (CMC) \cite{CMC} dataset. The availability of these new datasets allow the model to learn from greatly increased mitotic figure and background diversity, which immediately improved the model's performance \cite{CCMCT}. Nonetheless, it should be noted that these datasets were annotated with fixed size circular bounding box with a radius of 25 pixels which do not perfectly capture the shape of mitotic figures and would lead to noises and errors during the training process. Not only imperfection in data acquisition and annotation, but also the formulation of deep learning approach to solve the task plays an important role in the model's performance. Existing models for mitosis recognition often break the task into two stages: detection and classification \cite{Chen_Dou_Wang_Qin_Heng_2016, LI2018121, alom2019}. A main reason for this is because the sheer size of WSI prevents the model from operating directly on it. Instead, the WSI has to be broken down into smaller patches with a sliding window on which the inference is then performed to extract the locations of mitotic figures. The detection stage proposes the locations of mitotic figures in the WSI by using deep object detection or segmentation models. After the mitotic figures are proposed, the classification stage then refines the prediction results by first extracting the position of each predicted mitotic figure and revising the corresponding image patch to make it center around the mitotic figure and to ensure that only one mitotic figure is contained within the patch. Each revised image patch is then fed to a deep object classifier to obtain a confidence score. The classification stage significantly improves the mitotic figure recognition performance because it overcomes the drawback of the detection stage which has to handle a much broader variety of image patches, some with no mitotic figure and some with multiple mitotic figures. Despite the aforementioned benefits, a multi-stage pipeline also comes with a critical drawback; the classification stage suffers from inconsistency in the input data received from the detection stage and training distribution mismatch. As an inference is being performed at the detection stage, its outputs would inevitably consist of inaccurate object locations and poor quality bounding boxes, leading to inconsistently positioned objects at the image patch of the subsequent stage. The inconsistency results in classification stage performance degradation because most convolutional neural networks do not possess the shift-invariant property to properly handle the changes in distributions of object locations and bounding boxes produced by the detection stage \cite{Engstrom2017ARA}. The situation is further worsened with the use of a sliding window as it may split an object into pieces across multiple patches, which leads to additional poor-quality false positives. Inconsistency in training data distributions between the two stages is also non-negligible. While the detection stage learns the entire data distribution of the WSI, the classification stage mostly observes only mitotic figures and other similar-looking objects. This training distribution mismatch causes the classification stage to suffer from out-of-distribution problem when it receives inputs with no mitotic figure. DeepMitosis\cite{LI2018121} mitigates this problem by using all predictions, including low confidence ones, from the detection stage to train the classification stage. However, this method is impractical on large-scale datasets where hundreds of thousands of objects are proposed by the detector. To address all of the aforementioned problems, we introduce Refine Cascade Network (ReCasNet), an enhanced deep learning pipeline to improve the recognition performance on large-scale mitotic figure recognition datasets. Our pipeline improves the performance of the classification stage by increasing the consistency of input data distribution and exposing the model to more informative data. First, we propose Window Relocation, a simple, effective method that overcomes the weakness of an overlapping sliding window by removing objects around the window border and re-evaluating them as the center of newly extracted patches. This method seeks to eliminate poor bounding boxes while requiring less computation cost than the overlapping sliding window. Second, we introduce an Object Center Adjustment Stage, a deep learning model responsible for bridging the gap between the classification stage and the detection stage. It generates new image patches that center on mitotic figures predicted by the detection stage and feed them to the classification stage to reduces the variance in input translation. Third, we improve the training data sampling process of the verification model (i.e., classification stage) of DeepMitosis by focusing on a subset of informative samples from the proposed objects on which the detector and the classifier disagree with each other the most. We evaluated the performance of ReCasNet on the CCMCT and CMC datasets, two public large-scale datasets for mitotic figure assessment. ReCasNet achieved 83.2\% test F1 on the CCMCT dataset and 82.3\% test F1 on the CMC dataset, which correspond to +1.2 and +4.8 percentage point improvements over the baseline, respectively \cite{CCMCT, CMC}. An end-to-end evaluation on both datasets by comparing the HPF and mitotic count (MC) produced by ReCasNet to the ground truth annotation showed that the mitotic count proposed by our pipeline on a fully-automated setting produced 44.1\%, and 28.2\% less mean absolute percentage error (MAPE) compared to the baseline on the CCMCT and CMC datasets, respectively. \section{Related Work} To perform automatic mitosis detection, many detection algorithms have been proposed to solve this problem. Early on, hand-crafted based object detection was a popular approach for automatic mitosis detection \cite{veta2013, 6460094, 6460626, 7165640, Tek2013, 6460515, Nateghi, 10.1007/978-3-319-24571-3_12}. It was also widely used in a general computer vision tasks before the resurgence of the deep learning approach. In this approach, the object candidates were proposed first by using traditional computer vision techniques to assign the probability of each pixel being a mitotic figure, and a threshold was then applied. After that, the shape, texture, and statistical features of the mitotic figure candidates were extracted based on pathologist's knowledge. Finally, the extracted features were fed to a classifier to distinguish objects of interest from background. This approach achieved competitive performances compared to deep object detection on the ICPR MITOS-2012, AMIDA 2013, and ICPR MITOS-ATYPIA-2014 dataset. Nevertheless, this approach does not scale well to large-scale datasets, since manually designing features that could explain all the mitotic figures would be extremely labor-intensive and would not generalize well to new datasets. Another approach for solving the problem is deep learning. It uses a convolutional neural network (CNN) to learn important features from training images. This paradigm achieves a state-of-the performance on many general computer vision tasks such as image classification, object detection, and semantic segmentation. Moreover, it could also be applied to medical imaging tasks, leading to widespread adoption \cite{LITJENS201760}. Malon et al. \cite{Malon2013} used image processing to propose the location of the candidate for mitotic cells, then used hand-crafted and CNN features to recognize mitotic figures. Cireşan et al. \cite{Cire13} trained a single-stage pixel-level classifier based on CNN to recognize mitotic figures on an image patch and perform inference in a sliding window manner, removing the need for hand-crafted features. CasNN \cite{Chen_Dou_Wang_Qin_Heng_2016} started using a two-stage pipeline to perform mitosis detection. The first stage was a semantic segmentation network trained to coarsely propose the location of mitotic cells. After that, the classification network was used to refine the prediction result observing it in fine detail. DeepMitosis \cite{LI2018121} changed the detection algorithm of the first stage from semantic segmentation to object detection, leading to a significant performance gain. In the dataset without pixel-level annotation, the bounding box was estimated using a semantic segmentation network. MitosisNet \cite{alom2019} changed the first stage by posing the problem as multi-task learning by training both segmentation and detection tasks in parallel. Though significant progress has been made, the benchmarks are mainly performed on small-scale datasets. An introduction of large-scale mitosis detection dataset \cite{CCMCT, CMC} opened up the possibility of evaluating model performance on a whole slide level. Aubreville et al. \cite{Aubreville2020} compared three deep learning-based methods for identifying the location with the highest mitotic density in the WSI of canine cutaneous mast cell tumor. (CCMCT). It was found that a two-stage pipeline, which contains a dedicated object detector, achieved the highest correlation between the predicted and the ground truth mitotic count. In addition, the prediction proposed by the models generally performed better than individual expert. Later, Bertram et al. \cite{Bertram2021.06.04.446287} showed that the use of a model to assist human expert by pre-selecting the region of interest led to a consistently more accurate mitotic count. In terms of speed, Fitzke et al. \cite{Fitzke2021OncoPetNetAD} proposed a high-throughput deep learning system that could perform mitosis detection on the WSI with an inference time of 0.27 minutes per slide. Most importantly, their system led to a change in tumor grading compared to human expert evaluation in some cases. \section{Methods} \begin{figure}[t] \centering \includegraphics[width=0.9\textwidth]{fig/figure1.png} \caption{A brief overview of our proposed pipeline. Our contributions are highlighted in the green dashed box. Two new stages, namely window relocation and object center adjustment are introduced in our pipeline. Window Relocation is used to remove superfluous poor quality predictions around the sliding window borders. The object center adjustment stage is responsible for aligning the center of the predicted positive class object from the detection stage to the image patch center. Data selection is used to filter training examples from the WSI to improve the model in the classification stage.} \label{fig:main_pipeline} \end{figure} In this section, we explain each component of our proposed pipeline in full detail. An overview of our pipeline is shown in Figure \ref{fig:main_pipeline}. The pipeline consists of four stages. First, a detection stage proposes the location of the mitotic figures in the WSI using an object detection algorithm. After that, a window relocation algorithm reevaluates poor quality false positive predictions around the image border. Then, an object center adjustment stage refines the quality of the extracted object to be more aligned to the patch center. Finally, a classification stage rescores the object confidence of each patch. In the classification stage, an additional technique is used to select training examples from the WSI to boost the model performance by using disagreement between the detection and classification stage. The subsections provide a detailed explanation of each stage. \subsection{Detection Stage} The detection stage is the first component of the pipeline responsible for proposing the location of the mitotic figures from the image. It is a deep object detector that receives an image as an input and return a set of bounding boxes \{($x_1$, $y_1$, $w_1$, $h_1$, $S_1$), ..., ($x_n$, $y_n$, $w_n$, $h_n$, $S_n$)\}, where each tuple in the set represents the center of the predicted object, object width, object height, an positive object confidence, respectively. Due to the sheer size of the WSI, the slide is broken down into smaller patches in a sliding window manner. The sliding window algorithm breaks down the slide with the dimension of $W \times H$ into $\lceil\frac{W}{K}\rceil \times \lceil\frac{H}{K}\rceil$ image patches (window) with the window size of $K \times K$. The detection stage then performs inference on every patch to extract the location of the mitotic figures inside it. To train the detector, we follow the data sampling strategy of the CCMCT and CMC baseline \cite{CCMCT, CMC}. To stabilize the model performance, we slightly modify the training process by sampling training images beforehand instead of querying them on the fly. The use of the sliding window algorithm leads to overproduced poor quality false positive predictions. This is because the object around the window boundary might be partially split into multiple objects in multiple sliding windows. Thus, an overlapping sliding window is performed to mitigate this issue by allowing the patches to be overlapped with the former one. This results in partially split boxes around the window border getting fully covered, though redundant predictions are also excessively produced. Therefore, non-maximum suppression (NMS) is used as a post-processing method to remove redundant objects. The NMS suppresses the bounding box when there exist nearby bounding boxes of which an intersection over union (IOU) is over a certain threshold and has higher confidence. The use of NMS results in a reduction of false-positive predictions as low-quality, low confidence boxes are mostly removed while retaining the good quality, high confidence ones. Despite the advantage, the overlapping windows increased the number of patches to perform inference to $\lceil\frac{W}{K(1 - \sigma)}\rceil \times \lceil\frac{H}{K(1-\sigma)}\rceil$, where $\sigma$ is an overlapping ratio. Moreover, though the problem is mitigated, this method does not guarantee good performance at the borders. \subsection{Window Relocation} \begin{figure} \centering \includegraphics[width=0.99\textwidth]{fig/figure2.png} \caption{An illustration of the window relocation algorithm. An object of interest (orange box) resides within non-overlapping sliding windows A and B. As a result, patches A and B each produce a poor-quality box whose center is the point P1, and P2 respectively. Since both centers are in the relocation area, they are valid candidates for relocating. The window relocation algorithm starts by discarding the two boxes in both patches. Then, patches A' and B' are newly created with the points P1 and P2 at the patch center. Finally, the newly created patches are fed to the detector, which returns two blue boxes.} \label{fig:refocusing} \end{figure} Window Relocation is a simple algorithm used to remove poor quality predictions around the sliding window border. This method aims to eliminate the two main weaknesses of the overlapping sliding window. The first weakness is that poor quality predictions around the window border still exist when the IOU is not high enough for the NMS to suppress, which results in an increased number of false positives during the final evaluation. Another weakness is that the computation resource is wasted when the window and its surroundings do not contain any object, especially for this task where mitotic figures are often sparsely populated across the WSI. Figure \ref{fig:refocusing} illustrates the process of the window relocation algorithm. Window relocation mitigates both problems by performing three steps. First, a relocation area is defined around the border of each patch (the yellow area in Figure \ref{fig:refocusing}). All positive objects whose center resides in the area are then discarded. After that, for each discarded object, the new window whose center is the center of the discarded object is created (patch A' and B' in Figure \ref{fig:refocusing}). Finally, the detector performs inference on the newly created windows. By performing these steps, the focus of the object is moved from the window border to the newly-created window center. This algorithm provides us with three advantages. First, it would reduce the poor quality predictions around the window border as most of them are removed. Second, having a relocated object positioned at the window center results in a more consistent detection result. Third, this method does not increase computation cost in the area that does not contain any object. Though this method might incur redundant predictions, it does not pose a significant impact on the whole pipeline as the new consistently produced boxes could be easily removed by using NMS. Next, we define a clear definition of a relocation area. The $i^{th}$ object in each window could be considered to be in the relocation area if the condition below is satisfied. \begin{equation} ( min({x_i, y_i, K - x_i, K - y_i}) \leq M ) \wedge (S_i \geq D)) \end{equation} In other words, the center of the object that is less than equal to $M$ pixel from the window border in any axis and has higher positive object confidence than $D$ is in a relocation area and is eligible for window relocation. $M$ is a hyperparameter determining a distance threshold from a window border, affecting the number of re-observed objects. If $M$ is set to a low value, window relocation would act as a non-overlapping sliding window. In contrast, a high value of $M$ would allow more objects to be re-scored. Setting $M$ to a high value would also come with a trade-off because it would result in an increased computation cost since the detector has to re-inference more objects. Nevertheless, the use of window relocation is expected to have less computation costs than the overlapping sliding window. This is because it would only try to re-inference the objects around the window border, and the objects in the datasets are often sparse. $D$ is a positive confidence threshold used for discarding obvious negative objects produced by the detector. It is set to 0.05 for both datasets. Since we know beforehand during the annotation process that the mitotic figure often has a form of circular shape with a radius around 25 pixels, we also follow this assumption and set $M$ to 25 pixels. It should be noted that this method would not work efficiently on general object detection tasks as the object shape could not be known beforehand. \subsection{Object Center Adjustment Stage} \begin{figure}[ht] \centering \includegraphics[width=0.8\textwidth]{fig/figure3.png} \caption{An overview of an object center adjustment stage. The object center adjustment stage learns to estimate the distance from the extracted patch center (red dot) to the ground truth positive class object center (green dot) and its class. During inference, the model estimated the location of object center (yellow dot) and generates a new image patch at the predicted location if the predicted object is recognized as a positive class. The blue box is a bounding box predicted by the detection stage.} \label{fig:relocation} \end{figure} Although many false-positive samples around the border of the sliding window are reevaluated after window relocation, there is still the problem of poor-quality bounding boxes that cause input inconsistency at the classification stage. The input inconsistency could make extracted object not being positioned at the image patch center, leading to classification stage performance degradation due to input translation variance. Therefore, we introduce an object center adjustment stage as a refinement process after window relocation to reduce position inconsistency of the positive class objects in the image patch by making the object center more aligned to the center of the patch to reduce input translation variance. The object center adjustment stage is a model which learns to locate the center of the positive object by estimating the distance from the image patch center to the ground truth positive class object center. Then, during an inference, it predicts the object center location and generates a new patch of which the center is the predicted location if the object class is positive. The negative class objects are refrained from adjustment because the concept of object center is ambiguous for non-cell background and broad tissue texture areas. Figure \ref{fig:relocation} shows an overview of the object center adjustment stage. To train the model to estimate the position of the object center, we generate the data representing the object center at different locations in the patch as an input to the model. The generation process starts by randomly sampling positive and negative objects from the dataset and extracting them in an image patch. By doing so, the image center of the sampled object is always at the same position as the ground truth object center. Then, random geometric transformations, which are random image shifting, flipping, rotation, are applied to the sampled image. As a result, the ground truth center is shifted from the image center by $(d_X, d_Y)$ pixels. After the image is transformed, the model learns to predict the position of the object center by predicting $(d_X, d_Y)$. The value of $d_X, d_Y$ is drawn from a normal distribution and is limited to a small value ($d_X, d_Y \leq $ 12 pixels) because we assume that the center of the predicted object should be close to the ground truth object center. Since the objective of this stage is to relocate the center of the positive object, the class of the object has to be known beforehand, which is not practical in a real-world situation. Therefore, the object class has to be inferred from the model. We could straightforwardly obtain the class by using object confidence from the detection stage. The detected object could be inferred as a positive class when the confidence is above a certain threshold. However, using detector confidence might not be ideal as the confidence produced by the poor bounding boxes might be inaccurate. Therefore, we added an auxiliary task for the object center adjustment stage to classify the object class. Since the input to this stage is just an extracted patch, it allows the model to observe a single object at a time, removing an unnecessary distraction from other objects. As a result, the confidence produced by this improvement should be superior to the detector confidence because it inherits the advantage of the limited observation like the classification stage, and it also has information of the annotated object center. The object center adjustment stage is a deep convolutional neural network (CNN) that outputs two prediction heads: the main regression head to estimate the distance from the image center to the ground truth center $(d_X, d_Y)$, and the auxiliary classification head to predict the object class. The model is optimized using relocation loss $L_{rel}$ as shown below. \begin{equation} L_{rel} = \lambda_{reg}L_{reg} + ( 1 - \lambda_{reg})L_{cls}. \end{equation} The relocation loss $L_{rel}$ is a combination of the regression loss $L_{reg}$ and classification loss $L_{cls}$ weighted by the parameter $\lambda_{reg}$. The classification loss is a standard cross-entropy loss calculated between the predicted and the ground truth object class. The regression loss is a $L1$ loss calculated between the predicted and the ground truth object center distance. To prevent a regression noise, the regression loss calculation is ignored when the ground truth class is negative. During inference, the model receives an extracted object as input then returns the object class and location of its center by estimating the distance from the object center to the patch center as an output. If the predicted object confidence is above a certain threshold, the object would be considered a positive object, and a new patch of which the center is the predicted location is generated. On the other hand, the model does nothing if the object's confidence is below the threshold. \subsection{Classification Stage} After the object center adjustment stage is performed, the center of the extracted object moves closer to the patch center and is ready to be fed to the classification stage. A classification stage is a model that resembles the object center adjustment stage but is dissimilar in its functionality. In contrast to the previous stage, this stage is a CNN that only outputs a classification head. The classification stage receives an extracted object from the object center adjustment stage as an input and returns the object's confidence. It could be argued that this stage might be redundant as the object center adjustment stage could also return the confidence. However, the main difference from the previous stage is that the object is consistently positioned at the image center. This means that the importance of having the model captured object translation variance is lessened. As a result, data augmentation strategies that could change the location of the object center are not included during training, leading to an increase in training stability and better recognition performance. The training process of this stage is similar to the object center adjustment model. First, positive and negative objects are randomly sampled from the dataset in an isolated area. The samples are then augmented and fed to the classifier, which predicts the object confidence. We follow DeepMitosis \cite{LI2018121} for the final object confidence calculation. The final object confidence $S$ is weighted between the confidence produced by the detection stage $S_{det}$ and the classification stage $S_{cls}$ using the weight $\omega$ as shown below. \begin{equation} S = \omega S_{det} + ( 1 - \omega) S_{cls}. \end{equation} \subsection{Active Learning Data Selection} Though the proposed pipeline yields a amiable performance, the dataset is still not fully utilized. This is because the classification stage only observes annotated objects, and the unannotated ones are left untouched. DeepMitosis\cite{LI2018121} tackled this issue by using the detector to extract image regions from the original WSI to to train the classification stage. However, this method became less effective in a large-scale dataset because it would generate an enormous number of objects from the negative class from the WSIs. Inclusion of these additional data would introduce not only a severe class imbalance but also the issue of negative class's uninformativeness. Therefore, active learning techniques should be used to select only the informative subset of proposed objects. To quantify the informativeness of a proposed object, we use an L1 distance between the positive class confidence of the detector and the classifier. This criterion offers us two advantages. First, it would encourage the classifier to correct its mistake by learning from the detector which generally performs better at filtering out negative objects. Second, it discourages the selection of noisy annotations, since it is possible that many objects of the positive class were not annotated as such. In these cases, both the detector and the classifier would return high positive class confidences and discard them. Here, we select top N (N = 20,000) negative objects which has the highest informativeness as additional queries for retraining the classification model. \section{Experimental Setup} \subsection{Dataset} The datasets chosen for benchmarking of our method were the ODAEL variant of the CCMCT dataset \cite{CCMCT} and the CODAEL variant of the CMC \cite{CMC} dataset. The prominent characteristic of the two datasets was the availability of a complete mitotic figure annotation on the WSI level using algorithm-aided annotation and the consensus of experts. In addition, hard negative objects (mitosis figures lookalikes) were also annotated, which improve training information. The CCMCT dataset contains an annotation of 44,800 mitotic figures on 32 WSIs, of which 11 of them were held out for testing. The CCMCT dataset consists of four classes: Mitosis, Mitosislike, Granulocyte, and Tumorcell. The first class is a positive class while the rest are considered negative. In the same manner, the CMC dataset contained an annotation of 13,907 mitotic figures on 21 WSIs, of which 7 of them were held out for testing. The CMC dataset consists of two classes: Mitosis, and Nonmitosis. \subsection{Detection Stage} The training was conducted using Faster R-CNN \cite{NIPS2015_14bfa6bb} with ResNet-50 \cite{he2015deep} as a network backbone with an input training resolution of $512 \times 512$. The network backbone was initialized using ImageNet pre-trained weights \cite{5206848}. We did not modify the base detection algorithm except for the number of output classes. We sampled 5,000 image patches from each training slide using the same data sampling strategy as the baseline. The training framework was based on an object detection framework MMDetection \cite{chen2019mmdetection}. The model was trained using a batch size of 8 and SGD as an optimizer. The model was trained with an initial learning rate of $10^{-3}$ for 8 epochs which were divided by 10 after 5 and 7 epochs. Random flip and standard photometric augmentation were used during training. \subsection{Object Center Adjustment Stage} The training was conducted using EfficientNet-B4 \cite{tan2020efficientnet} as a network backbone with an input training resolution of $128 \times 128$. The network backbone was initialized using ImageNet \cite{5206848} pre-trained weights. The model was trained using a batch size of 64 and Adam as an optimizer. The model was trained with an initial learning rate of $10^{-4}$ for 30,000 iterations which were divided by 10 after 22,500 and 27,000 iterations. $\lambda_{reg}$ was set to 0.95 for every experiment. Random image geometric and standard photometric augmentation was used during training. The positive class threshold was set to 0.2, and 0.5 for CMC and CCMCT datasets, respectively. \subsection{Classification Stage} The training was conducted using EfficientNet-B4 \cite{tan2020efficientnet} as a network backbone with an input training resolution of $128 \times 128$. The network was initialized using ImageNet pre-trained weights. The model was trained using a batch size of 64 and Adam as an optimizer. For the CCMCT dataset, the model was trained with an initial learning rate of $5 \times 10^{-4}$ for 30,000 iterations which were divided by 10 after 22,500 and 27,000 iterations. For the CMC dataset without data selection, the model was trained with an initial learning rate of $5 \times 10^{-4}$ for 15,000 iterations which were divided by 10 after 10,000 and 13,000 iterations. For the CMC dataset with data selection, the model was trained with an initial learning rate of $5 \times 10^{-4}$ for 24,000 iterations which were divided by 10 after 15,000 and 21,000 iterations. Random image geometric and standard photometric augmentation except for random translation were used during training. \section{Results} In this section, we evaluated the performance of the proposed method on the CCMCT \cite{CCMCT} and CMC \cite{CMC} datasets. We followed the prior study \cite{CCMCT} by using F1 (\%) as a primary metric and using the same train-test split. We reported an average of three splits with standard deviations. The models used for evaluation were the checkpoints at the last training step. The result shown in table \ref{mainresult} summarized the performance of our method. Ultimately, the performance of the proposed pipeline improved from 82.0\% to 83.2\% on the CCMCT dataset and 77.5\% to 82.6\% on the CMC dataset. The main contributing factors were data selection and object center adjustment stage, which contributed 2.6\% and 4.2\% absolute performance improvement. The result suggested that input consistency and exposure of additional unannotated data at the classification stage was crucial for performance improvement. We then investigated the mispredictions produced by our pipeline by observing false-positive errors and categorized them as easy and hard errors. The hard errors are the hard-negative object that is confused as a positive class, while the easy error is confusion between the positive class and a non-hard negative object or background image. Figure \ref{fig:error_result} shows a visualization of false-positive errors of our method. Our method greatly reduced the number of easy false positive predictions compared to the baseline. Nevertheless, the confusion between positive and hard-negative samples persists. This indicated that input translation variance was not the only factor for the confusion between hard-negative and positive objects. \begin{table} \caption{The test F1 (\%) performance of the proposed method evaluated on the CCMCT and CMC datasets. $\pm$ denotes standard deviation.} \begin{center} \begin{tabular}{|l|c|c|} \hline \textbf{Method} & \textbf{CCMCT test F1(\%)} & \textbf{CMC test F1(\%)} \\ \hline Baseline \cite{CCMCT, CMC} & 82.0 & 77.5 \footnotemark\\ \hline Reproduced baseline ($\omega = 0$) & 79.9 $\pm$ 0.3 & 77.6 $\pm$ 0.2 \\ \hline + Data selection & 81.8 $\pm$ 0.1 & 80.3 $\pm$ 0.1\\ \hline + Object center adjustment & 82.5 $\pm$ 0.1 & 81.8 $\pm$ 0.1\\ \hline + Weighted confidence ($\omega = 0.4$) & 83.0 $\pm$ 0.1 & 82.1 $\pm$ 0.1\\ \hline + Window relocation & \textbf{83.2 $\pm$ 0.1} & \textbf{82.3 $\pm$ 0.1}\\ \hline \end{tabular} \label{mainresult} \end{center} \end{table} \footnotetext{The number was based on the erratum in their Github.} \begin{figure} \centering \begin{subfigure}{0.45\textwidth} \centering \includegraphics[width=\textwidth]{fig/figure4a.png} \caption{} \end{subfigure} \begin{subfigure}{0.45\textwidth} \centering \includegraphics[width=\textwidth]{fig/figure4b.png} \caption{} \end{subfigure} \caption{Multiple Bar charts showing the frequency of easy and hard false positive (FP) errors on the CCMCT and CMC dataset. Our method greatly reduced the number of easy false positive predictions, yet confusion between positive and hard-negative samples still remained in high quantity.} \label{fig:error_result} \end{figure} \subsection{Effect of Object Center Adjustment Stage} In this subsection, we study the effect of the object center adjustment stage on the proposed pipeline. First, we show that the presence of this stage leads to an improvement of the proposed object center quality. Then, we provide ablation studies to confirm the choice of our design. For every experiment, $\omega$ was set to zero, and window relocation was excluded. One metric that can measure the performance of the object center adjustment stage is the distance between the patch center and the original location. The false positives were not included in this metric as it was irrelevant for this stage. The object center adjustment stage reduced the average distance from 3.59 to 3.17 on the CCMCT dataset and 3.61 to 3.40 on the CMC dataset. The result suggested that the use of the object center adjustment stage clearly reduces the input translation variance. Figure \ref{fig:qualitative_relocation} shows examples of the predicted object center produced by the object center adjustment stage. The model often correctly located the position of the actual object center as shown in Figure \ref{rel_success}. However, falsely adjusted objects were also present. Some common mispredictions came from confusion of cells in the late telophase stage which can look like two separate mitotic figures. As a result, the model aligned to one of the spindles instead of the actual center. Others causes of misprediction came from the model's inability to precisely locate the object center when the predicted object center is too far from the ground truth center, object center ambiguity, and silly mistakes. Next, we justify the exclusion of negative class in the regression loss and the presence of auxiliary head. Table \ref{relocation_ablation} shows that the model performance reduced from 81.8\% test F1 to 81.1\% when the negative class was included in the regression loss. The result indicates that the ambiguity of object center in the negative class object led to a regression noise during training, eventually leading to reduced performance. Moreover, the auxiliary head improves the model performance from 81.5\% to 81.8\%, showing the importance of multi-task learning. We also conducted ablation studies on the choice of pipeline design and the removal of data augmentation strategies that could change the location of the object center. Table \ref{relocation_importance} shows that translation augmentation improved the performance of the classification stage of the base pipeline. However, the object center adjustment training scheme, which formulated the problem as a multi-task problem, is more efficient than data augmentation. We confirmed this by replacing a classification stage with an object center adjustment stage and using its classification head to produce object confidence. It was found that, by only using the object center adjustment stage, the performance of the whole pipeline improved from 80.5\% to 81.3\% test F1 on the CMC dataset. By stacking the relocation and classification stage, the performance was further increased to 81.8\%. However, having a translation augmentation in the classification stage of the stacked pipeline degraded the performance. The result also indicated that translation augmentation hampered the performance when the translation variance of the object center was controlled. \begin{table} \caption{The result of the ablation study on the importance of the object center adjustment stage conducted on the CMC dataset. The use of an object center adjustment stage outperformed the classification stage with translation augmentation. In addition, the removal of translation augmentation at the classifications stage was crucial for the performance improvement of the whole pipeline.} \begin{center} \begin{tabular}{|l|c|c|c|} \hline \textbf{Method} & \textbf{CMC test F1(\%)} \\ \hline Classification stage & 80.3 $\pm$ 0.1 \\ \hline Classification stage w/ translation augmentation & 80.5 $\pm$ 0.3 \\ \hline Object center adjustment stage & 81.3 $\pm$ 0.1 \\ \hline Object center adjustment stage+Classification stage & \textbf{81.8 $\pm$ 0.1} \\ \hline Object center adjustment stage+Classification stage w/ translation augmentation & 81.5 $\pm$ 0.1 \\ \hline \end{tabular} \label{relocation_importance} \end{center} \end{table} \begin{table} \caption{The result of the ablation study of the object center adjustment stage conducted on the CMC dataset. The use of an auxiliary head improved the stage performance while the inclusion of negative class for relocation loss resulted in reduced performance.} \begin{center} \begin{tabular}{|c|c|c|c|} \hline \textbf{Negative class relocation loss} & \textbf{Auxiliary head} & \textbf{CMC test F1(\%)} \\ \hline - & - & 81.5 $\pm$ 0.2 \\ \hline \checkmark & - & 81.1 $\pm$ 0.1 \\ \hline - & \checkmark & \textbf{81.8 $\pm$ 0.1} \\ \hline \end{tabular} \label{relocation_ablation} \end{center} \end{table} \begin{figure} \centering \begin{subfigure}{0.8\textwidth} \centering \includegraphics[width=\textwidth]{fig/figure5a.png} \caption{Successful cases of object center adjustment stage.} \label{rel_success} \end{subfigure} \begin{subfigure}{0.8\textwidth} \centering \includegraphics[width=\textwidth]{fig/figure5b.png} \caption{Failure cases of object center adjustment stage.} \label{rel_fail} \end{subfigure} \caption{Example prediction results produced by the object center adjustment stage on the CMC dataset. (a) shows a successful examples. (b) shows failure examples. The first four images of are failures at the telophase stage. Red, yellow, and green dots indicate original, relocated, and ground truth object center, respectively. The red boxes are the bounding box produced by the detection stage. } \label{fig:qualitative_relocation} \end{figure} \subsection{Effect of Window Relocation} This subsection aimed to measure the effect of window relocation on the whole pipeline. Table \ref{refocusing_ablation} shows a comparison between window relocation and the sliding window method. The use of overlapping sliding windows did not improve the performance of our pipeline as most of the overproduced samples could be removed using the object center adjustment stage and non-maximum suppression. By using window relocation, the performance of the pipeline was better than the non-overlapping sliding window and the overlapped one with 0.2\% test F1 absolute improvement on the CMC dataset. The result suggested that some produced errors could not be mitigated through the method above. This is because the center of the overproduced object might be too far for the object center adjustment stage to adjust back to the actual center. In addition, we also found that window relocation only incurs a small amount of additional inference time over non-overlapping sliding window in a practical setting. This is because mitotic figures in the WSI generally have low density. Moreover, unlike overlapping sliding windows, window relocation could ignore most of the background image as it did not contain any objects in the first place. Since both window relocation and object center adjustment stage have a similar objective of improving poor quality predictions for the detection stage, we conducted an ablation study to observe the effect of each component separately. Table \ref{refocusing_ablation2} shows a comparison of the two components on the CMC dataset. Window relocation improved the test F1 from 80.3\% to 81.1\%. Nevertheless, the performance was inferior to the object center adjustment stage, which achieved 81.8\%. This is because window relocation mostly affects the objects positioned around the sliding window border. \begin{table} \caption{A comparison of different sliding window algorithms on the CMC dataset. Window relocation outperformed overlapping sliding windows while incurring less computation cost. } \begin{center} \begin{tabular}{|l|c|c|} \hline \textbf{Method} & \textbf{CMC test F1(\%)} & \textbf{\thead{Number of test inference window\\ done in the detection stage} }\\ \hline Non-overlapping sliding window & 82.1 $\pm$ 0.1 & 211482 (+0\%)\\ \hline Overlapping sliding window & 82.1 $\pm$ 0.1 & 261909 (+23.8\%) \\ \hline Window relocation & \textbf{82.3 $\pm$ 0.1} & 217368 (+2.7\%) \\ \hline \end{tabular} \label{refocusing_ablation} \end{center} \end{table} \begin{table} \caption{The comparison between window relocation and object center adjustment stage on the CMC dataset. Window relocation could partially mitigate the problem of input translation variance.} \begin{center} \begin{tabular}{|c|c|c|} \hline \textbf{Window relocation} & \textbf{Object center adjustment stage} & \textbf{CMC test F1(\%)} \\ \hline - & - & 80.3 $\pm$ 0.1 \\ \hline \checkmark & - & 81.1 $\pm$ 0.2 \\ \hline - & \checkmark & 81.8 $\pm$ 0.1 \\ \hline \checkmark & \checkmark & \textbf{82.1 $\pm$ 0.1} \\ \hline \end{tabular} \label{refocusing_ablation2} \end{center} \end{table} \subsection{The effect of the detection algorithm} We conducted an ablation study on the detection algorithm on the CMC dataset by changing the base detection algorithm and found that our method reduced the dependence on the strength of the detection model. We compared the chosen detection algorithm, Faster-RCNN-ResNet50, to the RetinaNet-ResNet18 \cite{retina}, which is a detection algorithm in both CCMCT and CMC paper. We also observed the effect of different model backbones by comparing them with Faster-RCNN-ResNet101. Every experiment was trained using the same set of data and training schedule, and $\omega$ was set to 0. Table \ref{detection_ablation} shows that the choice of detection algorithm had a significant impact on the base pipeline. The use of RetinaNet-ResNet18 as a detection algorithm reduced the test F1 on the CMC dataset by 9.0\% on the detection stage and 2.2\% on the classification stage compared to Faster-RCNN-ResNet50. The presence of object center adjustment stage and data selection helped mend the performance gap from 2.2\% to 0.5\% test F1 difference. The result suggested that the performance of the detection algorithm has a direct impact on the quality of the predicted bounding box, leading to worse classification stage performance, and the object center adjustment stage is an essential component for the object center correction. It could also be implied that, by emphasizing the classification stage, it allowed us to use a fast detection algorithm to potentially greatly reduce the inference time of the detection stage while not suffering a sharp performance reduction. \begin{table} \caption{A comparison of different detection algorithms on the CMC dataset. The choice of different detection algorithms led to drastically different results on the classification stage. However, an introduction of the object center adjustment stage and data selection greatly mitigated this problem.} \begin{center} \begin{tabular}{|c|c|c|c|c|} \hline \textbf{Detection algorithm} & \textbf{\thead{detection \\ test F1(\%)} } & \textbf{\thead{+classification \\ stage}} & \textbf{+data selection} & \textbf{\thead{+object center \\ adjustment}} \\ \hline RetinaNet-ResNet18 & 61.4 $\pm$ 0.8 & 75.4 $\pm$ 0.2 & 78.8 $\pm$ 0.4 & 81.3 $\pm$ 0.2 \\ \hline Faster-RCNN-ResNet50 & 70.4 $\pm$ 0.3 & 77.6 $\pm$ 0.2 & 80.3 $\pm$ 0.1 & 81.8 $\pm$ 0.1 \\ \hline Faster-RCNN-ResNet101 & 71.3 $\pm$ 0.1 & 78.1 $\pm$ 0.2 & 80.2 $\pm$ 0.1 & 81.8 $\pm$ 0.1 \\ \hline \end{tabular} \label{detection_ablation} \end{center} \end{table} \subsection{End-to-End evaluation} We further extended an evaluation of our method to an end-to-end setting by comparing the mitotic count (MC) produced by our method to the ground truth mitotic count. We follow Meuten et al.\cite{meuten} by counting mitotic figures at 10 HPF (2.37 $mm^2$) with an aspect ratio of 4:3 at the area with the highest mitotic figures density. The HPF area was calculated by selecting the rectangle window size of 7110/5333 pixels which contains the highest number of mitotic figures \cite{Bertram2019ComputerizedCO}. We evaluated the proposed pipeline on two settings: GA, and GB. The GA setting directly compared the mitotic count from the HPF proposed by our pipeline to the ground truth mitotic count. In contrast, the GB setting only used the proposed HPF, but the mitotic count was instead obtained by counting the ground truth mitotic cell. The GA setting could be considered as a fully automated mitosis counting while the GB was a human-in-the-loop setting where the optimal pathologist, who always correctly recognized mitotic figures, was also included in the pipeline. Moreover, the GB setting put an importance on the quality of the proposed HPF over the predicted mitotic count, which was mainly focused on the GA setting. We reported mean absolute percentage error (MAPE) and mean absolute error (MAE) at the prediction threshold which yielded the lowest MAPE. For a baseline comparison, we used the prediction results on the test set in their GitHub. Table \ref{end2end1} shows the result of GA and GB settings on the CCMCT and CMC dataset. Our method significantly reduced the MAPE and MAE on the CCMCT and CMC datasets in both settings. Figure \ref{end2end0} shows a relation between the predicted mitotic count and the ground truth. Compared to the baseline, our method clearly changed the mitotic count when the object appeared in high density, though the impact was lessened in a low-density case. \begin{table}[htbp] \caption{The end-to-end performance of the proposed method evaluated on the CCMCT and CMC datasets. Our method consistently outperformed the baseline in both settings.} \begin{center} \begin{tabular}{|c|l|cc|cc|} \hline \multicolumn{1}{|l|}{\textbf{Dataset}} & \textbf{Method} & \multicolumn{2}{c|}{\textbf{GA}} & \multicolumn{2}{c|}{\textbf{GB}} \\ \cline{3-6} \multicolumn{1}{|l|}{} & & \multicolumn{1}{l|}{\textbf{MAPE}} & \multicolumn{1}{l|}{\textbf{MAE}} & \multicolumn{1}{l|}{\textbf{MAPE}} & \multicolumn{1}{l|}{\textbf{MAE}} \\ \hline CCMCT & Baseline & \multicolumn{1}{c|}{18.8} & 10.5 & \multicolumn{1}{c|}{11.2} & 4.4 \\ \cline{2-6} & Ours & \multicolumn{1}{c|}{\textbf{10.5}} & \textbf{8.3} & \multicolumn{1}{c|}{\textbf{6.8}} & \textbf{1.9} \\ \hline CMC & Baseline & \multicolumn{1}{c|}{7.8} & 3.1 & \multicolumn{1}{c|}{8.1} & 2.4 \\ \cline{2-6} & Ours & \multicolumn{1}{c|}{\textbf{5.6}} & \textbf{1.9} & \multicolumn{1}{c|}{\textbf{5.6}} & \textbf{1.6} \\ \hline \end{tabular} \label{end2end1} \end{center} \end{table} \begin{figure} \centering \begin{subfigure}{0.3\textwidth} \includegraphics[width=\textwidth]{fig/figure6a.png} \end{subfigure} \begin{subfigure}{0.3\textwidth} \includegraphics[width=\textwidth]{fig/figure6b.png} \end{subfigure} \centering \caption{Scatter plots illustrating the predicted mitotic count and the ground truth on the CCMCT and CMC dataset on GA setting. Compared to the baseline, our method clearly changed the predicted MC when the object appeared in high density, though the effect become less noticeable on the slides with low mitotic figures.} \label{end2end0} \end{figure} \section{Conclusion} We propose ReCasNet, an enhanced deep learning pipeline that introduces three improvements to the two-stage mitosis detection pipeline. First, we introduced window relocation, a method used to reduce the number of false positives introduced by the sliding window algorithm by removing predictions around the window border and assigning them to a new window for re-performing inference. Second, we proposed the object center adjustment stage, a deep learning model responsible for adjusting the center of the mitotic cell predicted from the detection stage. This improves the consistency of inputs for the classification stage. Third, we utilized an active learning technique to alleviate the inconsistency in training data by identifying additional informative examples, based on the disagreement between the two stages, to train the classification stage. Our proposed method significantly increases the performance of the whole pipeline on both detection of individual mitotic figures and end-to-end region-of-interest proposal and mitotic count predictions on the CCMCT and CMC dataset. \section*{Acknowledgment} This work was supported by the Thailand Program Management Unit (PMU-B) Grant for Multi-Institutional AI Development in Digital Pathology (to S.Sa., S.Sh., and S.Sr.) and the Grant for Supporting Research Unit, Ratchadapisek Sompoch Endowment Fund, Chulalongkorn University (to C.P., S.Sr., and E.C.). \section*{Code availability} All used code in the experiments is available at https://github.com/cmb-chula/ReCasNet. The implementation is based on MMDetection\cite{chen2019mmdetection} and tensorflow \cite{tensorflow2015-whitepaper}. \bibliographystyle{unsrtnat} \section{Additional training details} \subsection{Detection stage data preparation strategy} We followed the data preparation strategy of the CCMCT and CMC baseline. 50\% of the cropped patches were randomly acquired from the training slide. 40\% were sampled to contained at least one mitotic figure in the cropped image. 10\% contained at least one mitotic figure-lookalike in the cropped image (class MitosisLike and NonMitosis in the CCMCT, and CMC dataset respectively). \subsection{Data augmentation strategies} Table \ref{auglist2} shows a detailed list of augmentation strategies of the object center adjustment and classification stages. Random rotation was still allowed in the classification stage because the relocated object center patch can still rotate. \begin{table}[b] \caption{List of augmentation strategy of the the classification and object center adjustment stage.} \begin{center} \begin{tabular}{|l|c|c|c|} \hline \textbf{Augmentation strategy} & \textbf{Classification stage} & \thead{Object center \\ adjustment stage} & \textbf{Intensity} \\ \cline{2-3} & \multicolumn{2}{c|}{\textbf{probability}} & \\ \hline Random flip & 0.5 & 0.5 & - \\ \hline Random brightness & 0.5 & 0.5 & (0.8, 1.2) \\ \hline Random contrast & 0.5 & 0.5 & (0.8, 1.2) \\ \hline Random gaussian blur & 0.25 & 0.25 & (3,3) and (5, 5) kernel \\ \hline Random hue & 1 & 1 & (-0.1, 0.1) \\ \hline Random rotation & 1 & 1 & (-90, 90) \\ \hline Random translation & 0 & 1 & $d_x, d_y \sim N(0, 6^2) $ \\ \hline \end{tabular} \label{auglist2} \end{center} \end{table} \section{Additional ablation studies} \subsection{Effect of relocation loss weight} We investigated the effect of $\lambda_{reg}$, a hyperparameter determining an importance of the regression task in the relocation loss on the performance of the whole pipeline. We compared the effect by using different sets of $\lambda_{reg}$ and measured the performance of the whole pipeline. Table \ref{lambda_reg} shows that the performance does not vary much when $\lambda_{reg}$ is set at the high value. However, there was a degradation of the object center adjustment stage's ability to locate object center when the value of $\lambda_{reg}$ was below a certain threshold. \begin{table} \caption{The of $\lambda_{reg}$ on the performance of the pipeline on the CMC dataset.} \begin{center} \begin{tabular}{|c|c|c|c|} \hline $\lambda_{reg}$ & \textbf{CMC test F1(\%)} \\ \hline 1 & 81.5 $\pm$ 0.2 \\ \hline 0.99 & 81.7 $\pm$ 0.1 \\ \hline 0.95 & 81.8 $\pm$ 0.1 \\ \hline 0.9 & \textbf{81.8 $\pm$ 0.1} \\ \hline 0.8 & 81.8 $\pm$ 0.1 \\ \hline 0.7 & 81.6 $\pm$ 0.4 \\ \hline 0.6 & 80.3 $\pm$ 1.6 \\ \hline \end{tabular} \label{lambda_reg} \end{center} \end{table} \subsection{Effect of data selection algorithm for the classification stage} In this section, we show that our criterion of informativeness is effective for this task. Thus, we provided a comparison of our method against three baselines. The first baseline is DeepMitosis \cite{LI2018121} query strategy, which queries every negative object proposed by the classification stage from the training slides. The second baseline is uncertainty sampling, a strong baseline in the Active Learning field \cite{Settles2009ActiveLL}. This method measures the uncertainty produced by the model as a selection criterion for data acquisition. We used entropy as an uncertainty measurement and used classification stage confidence to produce model uncertainty. The third baseline is K-Center-greedy \cite{sener2018active}, a query strategy based on the core set approach. It aims to select the samples that provide the most coverage over the training distribution by minimizing the distance between a data point and its nearest chosen samples. We also follow their work by using the output after the last convolutional layer of the classification stage to represent the data point and L2 as a distance function. We used the same classification model for data acquisition for every baseline. Window Relocation and object center adjustment stage were excluded during the experiments. Table \ref{query_strategy} shows the result of our experiment. It was found that our method outperformed DeepMitosis's querying strategy and Active Learning baselines, and every Active Learning baseline is better than not selecting any data at all. The result supported our claim that overexposure of negative samples led to sub-optimal performance but still better than not querying any additional data at all. \begin{table} \caption{The effect of data selection algorithm on the performance of the pipeline on the CMC dataset.} \begin{center} \begin{tabular}{|l|c|c|c|} \hline \textbf{Query method} & \textbf{CMC test F1(\%)} \\ \hline Baseline (no query) & 77.6 $\pm$ 0.2 \\ \hline DeepMitosis (query all) & 80.0 $\pm$ 0.2 \\ \hline K-Center greedy & 79.0 $\pm$ 0.1 \\ \hline Uncertainty sampling & 79.8 $\pm$ 0.1 \\ \hline Disagreement (Ours) & \textbf{80.3 $\pm$ 0.1} \\ \hline \end{tabular} \label{query_strategy} \end{center} \end{table}
{'timestamp': '2022-03-01T02:53:56', 'yymm': '2202', 'arxiv_id': '2202.13912', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13912'}
arxiv
\section{Introduction} Complex real-world systems can be modeled, analyzed, and optimized through their respective graph representations. These systems range from social networks~\cite{tang2010graph}, to biological networks~\cite{aittokallio2006graph}, to the full Internet~\cite{boccaletti2006complex}. Data mining, information retrieval, recommendation systems, and fraud detection are just a few applications of graph analysis~\cite{cook2006mining, besta2021graphminesuite, gianinazzi2021parallel, benson2016higher, besta2021sisa}. The local clustering coefficient (LCC)~\cite{watts1998collective} indicates the likelihood that neighbors of a node are also neighbors to each other, which has applications in the link prediction problem~\cite{lu2011link}. In particular, this metric has been proven useful in many applications, such as community detection~\cite{communitydetection, besta2020communication} or link recommendation~\cite{linkrecommendation}. In the former case, LCC is used to detect communities in, e.g., social networks, distinguishing between vertices that are central to the cluster from others on its frontier. In the latter, clustering coefficient is used to locate thematic relationships by looking at the graph of hyperlinks. The LCC of a vertex is given as the fraction of the pairs of its neighbors that are themselves connected by an edge. Figure~\ref{fig:intro:overview} (left) shows an example of LCC scores on a toy graph. Vertices with darker backgrounds have higher LCC. Given a vertex, two of its neighbors contribute to its LCC score if the three vertices form a triangle in the graph. Therefore, to compute the LCC, one has to count the number of triangles that are closed by its neighbors for every vertex. With the rapid growth in the size of graphs to be analyzed, both memory and computational capacities of a single machine become insufficient to perform triangle counting (TC) analysis on a single node. There are two main strategies to compute TC in distributed memory: (1) by first computing overlapping partitions that are necessary for local triangle counting or (2) by issuing communications between processes. Current state-of-the-art solutions~\cite{TRUST,hu2018tricore,Tric,hoang2019disttc} all follow either the Bulk Synchronous Parallel model~\cite{BSP} or MapReduce~\cite{kolda2014counting} and suffer from synchronization, as well as the overhead of computing the partitioning of the graph. The 2020 graph champion paper TriC~\cite{Tric} utilizes blocking all-to-all communication resulting in synchronization overheads being as costly as communication. To minimize communication, DistTC~\cite{hoang2019disttc} computes and distributes shadow edges that are necessary for computing triangles locally. This approach leads to a low computation time but makes the total running time dominated by this pre-computation step, similarly limiting scalability. \begin{figure}[t] \centering \includegraphics[width=0.9\columnwidth]{Final_figures/lcc_overview.pdf} \vspace{-0.5em} \caption{LCC example and data reuse. Left: graph partitioned between two compute nodes. The gradient of the vertices indicates their LCC score. Dashed edges indicate RMA communications needed to read adjacency lists from remote nodes. Right: data reuse in social network graph~\cite{mcauley2012learning}.} \vspace{-1.5em} \label{fig:intro:overview} \end{figure} However, distributed triangle counting and local clustering coefficient do not necessarily require synchronization. In fact, as the graph is not updated during the computation, the distributed algorithm can be organized to let different processes progress asynchronously while still storing only partitions of the graph. We exploit this characteristic by proposing a fully asynchronous solution that uses Remote Memory Access (RMA) one-sided operations to read remote portions of the graph without involving target nodes. For example, the graph of Figure~\ref{fig:intro:overview} (left) is distributed on two computing nodes. To compute the LCC of vertex 1, node A reads the adjacency lists of vertices 0 and 2 locally and the adjacency list of vertex 4 via RMA. We notice how some RMA accesses are repeated and, in principle, can be avoided to save communication time. For example, when node A needs to compute the LCC of vertex 2, it will again read via RMA the adjacency list of vertex 4. Figure~\ref{fig:intro:overview} (right) shows the data reuse in a real-world graph modeling social network circles~\cite{mcauley2012learning}. The plot shows how many remote reads ($x$-axis) are repeated $y$ times when the graph is partitioned among two computing nodes. We exploit data reuse in the remote access pattern of LCC computations by caching RMA accesses using CLaMPI~\cite{rma-caching}, a transparent caching layer for RMA. Moreover, we extend CLaMPI to accept application-defined scores for cached entries and show how this can improve caching efficiency. All in all, in this work we: \begin{itemize}[noitemsep,topsep=1pt,parsep=0pt,partopsep=0pt,leftmargin=10pt] \item propose a distributed and fully asynchronous algorithm for both triangle counting and LCC (Section~\ref{sec:distlcc}). \item introduce a hybrid strategy for triangle computation based on the frontiers (Section~\ref{sec:dynamic}). \item show how data reuse in remote access patterns of LCC computation can be exploited by caching RMA accesses and reduce the overall communication time. We further increase caching performance by introducing application-defined scores for victim selection (Section~\ref{sec:datareuse}). \end{itemize} Our hybrid approach for the local computation of triangles can improve performance by up to 8\% on a CPU. We achieve shared memory parallelism by computing the intersection in parallel using OpenMP, leading to a speedup of up to 2.7$\times$ using 16 threads compared to a sequential implementation. On distributed memory, our non-cached algorithm achieves a speedup of up to $14\times$. Moreover, we can reduce the total running time using caching by up to \review{$73\%$}{G1}{Green} compared to a non-cached version until the graph is not over-partitioned. Finally, we show up to \review{$100\times$}{G2}{Green} better performance compared to TriC. \section{Background} \subsection{Notation} We denote an unweighted graph that contains no multi-edges and loops as $G = (V, E)$, where $V$ is the set of vertices and $E \subseteq V \times V$ the set of edges ($|V|=n$ and $|E|=m$). We will use $v_i$ to denote a vertex and $e_{ij}$ for the edge from $v_i$ to $v_j$. We call the adjacency of $v_i$ the set of vertices $adj(v_i) = \{v_j : e_{ij} \in E\}$ and denote by $\mathbf{A}$ the adjacency matrix of $G$. Moreover, we define the in-degree of $v_i$ as $deg^-(v_i) = \left|\{v_j : e_{ji} \in E\}\right|$ and the out-degree as $deg^+(v_i) = \left|\{v_j : e_{ij} \in E\}\right|$ (note, for a directed graph in and out-degree equals). We use the symbol $\triangle_{ijk}$ for the triangle that consists of the edges $e_{ij}$, $e_{ik}$ and $e_{jk}$. We will denote by $p$ the number of processes. For simplicity, we assume that $p$ is always a power of 2 and $p$ divides $n$. A summary of the notation used in the paper can be found in Table~\ref{tab:symbols}. \subsection{Graph format}\label{sec:graph_format} \input{Inlines/symbols} We consider graphs with no multi-edges and remove vertices that have degree less than two, as they cannot be part of any triangle. If the input graph is stored in a degree-ordered format, we use a random relabeling to avoid assigning all the highest degree vertices to the same process. The graph is stored in the CSR (Compressed Sparse Row) format (see Figure~\ref{fig:csr_example}), where each process stores its partition with the help of two arrays: \texttt{offsets} and \texttt{adjacencies}. An element $i$ of the \texttt{offsets} array stores the offset at which adjacency list of vertex $v_i$ starts in the \texttt{adjacencies} array. \begin{figure}[H] \vspace{-1em} \centering \includegraphics[width=0.75\columnwidth]{Final_figures/csr_corrected.pdf} \caption{\review{Compressed Sparse Row (CSR) representation of the subgraph stored on node A of Figure~\ref{fig:intro:overview}.}{R4.1}{red}} \label{fig:csr_example} \end{figure} \subsection{Triangle computation} \label{sec:tc} We follow the edge-centric method for triangle counting and compute the number of triangles that are closed by an edge $e_{ij}$ for every $e_{ij}\in E$. This is given by the number of common neighbours, which can be formulated as $\left| adj(v_i) \cap adj(v_j) \right|$. We note that in the undirected case, the presence of a triangle $\triangle_{ijk}$ implies the presence of $\triangle_{ikj}$. However, in the general edge-centric method, both triangles are enumerated because they lie on different edges. To reduce computation, this double counting can be eliminated by offsetting the neighbor's adjacency to count the common elements only for the upper triangle in the adjacency matrix, that is, for the set of vertices $\{v_k : v_k\in adj(v_j) \wedge j < k$\}. For the computation of the intersection, we apply either binary search or sorted set intersection (SSI), which proceed for two sorted lists $A$ and $B$ with $|A| \leq |B|$ as follows: \subsubsection{Binary search} With binary search, the computation of the intersection breaks down to issuing $|A|$ lookups in a sorted array of length $|B|$ resulting in a \review{running time complexity}{R4.2}{red} of $\mathcal{O}(|A| \cdot log(|B|))$. To minimize this, one should always assign the longer list as the search tree and the shorter one as the array of keys. \subsubsection{Sorted Set Intersection} SSI traverses the two lists simultaneously by comparing the current elements and progressing the array whose current element is smaller. If a common element is found, it increments the counter and moves an element in both arrays. Trivially, SSI computes the intersection of two lists in $\mathcal{O}(|A| + |B|)$. The described algorithms are outlined in Algorithm~\ref{algo:bin_search} and \ref{algo:ssi}. We emphasize that these methods assume sorted adjacency lists, however, most graph datasets are already of this form. \input{Inlines/bin_search} \input{Inlines/ssi} \subsection{Local Clustering Coefficient} The Local Clustering Coefficient of a vertex $v_i$ was defined by Watts and Strogatz~\cite{watts1998collective} as the proportion of existing edges between the vertices adjacent to $v_i$ divided by the possible number of edges that can exist between them. For directed graphs, this can be computed as: \begin{equation} \label{eq:lcc-directed} C(i) = \frac{|\{e_{jk}: v_j, v_k \in adj(v_i), e_{jk} \in E\}|}{deg^+(v_i) \cdot (deg^+(v_i) - 1)} \end{equation} Similarly, for an undirected graph: \begin{equation} \label{eq:lcc-undirected} C(i) = \frac{2 \cdot |\{e_{jk}: v_j, v_k \in adj(v_i), e_{jk} \in E\}|}{deg^+(v_i) \cdot (deg^+(v_i) - 1)} \end{equation} For a pair of vertices $\{v_j, v_k\}$, in order to contribute to the numerator, the edges $e_{ij}$, $e_{ik}$ and $e_{jk}$ must exist, forming the triangle $\triangle_{ijk}$ in $G$. Thus, if vertex degrees are known, LCC can be computed by detecting, for every vertex, the number of triangles in which they participate. \subsection{MPI-RMA} Remote Memory Access (RMA) operations are defined by the MPI-3 standard~\cite{hoefler2015remote} and enable MPI processes to access memory regions of remote peers in a one-sided fashion. When running on networks supporting remote direct memory access (RDMA), RMA operations are naturally mapped to the hardware interface (e.g., ibverbs~\cite{bedeir2010rdma}, uGNI~\cite{alverson2012cray,uGNI2}), resulting in higher throughput and lower latency. \review{While also two-sided communications can benefit from a RDMA-based implementation, they still incur in overheads caused by MPI message matching that can lead to additional message copies or synchronization. }\review{For this reason, in this work we focus on MPI RMA.}{R3.7}{orange} Processes can expose their local memory by creating a window that serves as a logically distributed memory region. To access remote memories, MPI processes can use functions like \texttt{MPI\_Put} and \texttt{MPI\_Get}. With the first, a process can write into memory regions exposed over the network by remote peers. With the second, a process can read the content of such regions. Communications in MPI RMA are always non-blocking, and synchronization is enforced only at the beginning and at the end of an epoch. The process-local memory region can be accessed by other processes during an exposure epoch, whereas a process can access remote data during an access epoch. MPI defines two types of synchronization modes: active and passive. With the first, both initiator (i.e., the process issuing RMA operations) and target (i.e., the process targeted by RMA operations) processes synchronize to start a new epoch. With the passive mode, the participation of the target process is not required. \begin{figure*}[t] \includegraphics[width=\textwidth]{Final_figures/full_overview_corrected.pdf} \caption{\review{Overview of the proposed approach for distributed, fully-asynchronous LCC computation with RMA caching.}{R4.1}{red}} \label{fig:full-overview} \end{figure*} \subsection{RMA Caching} CLaMPI~\cite{rma-caching} is a software caching layer that transparently caches data retrieved through MPI RMA operations. CLaMPI can be linked to MPI applications, and it is designed to fit into the \mbox{MPI-3 RMA} programming model, minimizing cache-management overheads and relying on the concept of MPI epochs to enforce consistency. As applications can issue arbitrary-size read operations, CLaMPI supports caching of variable-size entries. This is achieved by using two data structures: a hash table to index cached entries and an AVL tree to store free regions in the memory buffer reserved for caching. Both the size of the hash table and the capacity of the memory buffer are parameters that can be tuned to the specific use case. CLaMPI includes an adaptive parameter tuning heuristic that automatically resizes the hash table and the memory buffer by observing indicators such as cache misses, conflicts in the hash table, and evictions due to lack of space in the memory buffer. In CLaMPI, the eviction procedure is triggered when the application makes remote memory accesses over an MPI window that: (a) is enabled for caching, (b) does not contain the referenced data in cache, and (c) does not have enough space either in the hash table or in the memory buffer to index or store the new data. Due to the variable size of the cached entries, the system can incur in external fragmentation of the memory buffer: the free space can be fragmented in small non-contiguous regions that cannot fit a new entry. To reduce external fragmentation, CLaMPI assigns a score to the cached entries that reflect both their temporal locality and how much fragmentation they are causing in the memory buffer. The victim selection takes this score into account when deciding which entry to evict: e.g., if an entry is poorly placed in the memory buffer (e.g., surrounded by free space that could be merged if the entry would be removed), it will be more likely to be evicted even if it presents higher temporal locality. CLaMPI provides three operational modes to enforce consistency of cached data: \emph{transparent}, \emph{always-cache}, and \emph{user-defined}. The \emph{transparent} mode does not make any assumption on the nature of the cached data (e.g., read-only or read-write) and flushes the cache at every epoch closure. In this case, CLaMPI can still save remote accesses that target the same data and that are made within the same epoch. However, cached data does not persist among multiple epochs. Consistency within the epoch is guaranteed by the MPI RMA semantic that, e.g., forbids conflicting \emph{put} and \emph{get} operations happening in the same epoch. The \emph{always-cache} mode assumes that data accesses with RMA operations is read-only. In this case, there is no need to flush the cache since there are no updates to be propagated. Finally, the \emph{user-defined} mode leaves the responsibility of flushing the cache to the application. For example, an application might be using data as read-only for a number of epochs, during which cached data can persist, and then switch to another phase where updates are issued, hence needing to flush the cache. \section{Accelerating Distributed LCC} LCC can be formulated in terms of counting the number of closed triplets centered in a node. This formulation enables the use of triangle counting as a fundamental primitive for LCC computation. Moreover, it implies that it is possible to compute LCC of each vertex asynchronously. The problem of computing triangles in large-scale graphs has been widely investigated, and, as we mentioned, the main limitation to scalability comes from the synchronization cost and the unbalancing of the graph partitioning. In our algorithm design, we explore asynchronous computation and a mechanism for improving data locality based on the concept of vertex delegation. To this aim, we distribute the input graph among multiple computing nodes and let them access remote partitions via one-sided RMA operations. By distributing the graph, we lower the per-node memory requirements and reduce initialization overheads (i.e., I/O time to read the graph), which would otherwise limit strong-scaling capabilities because of Amdahl's law. Additionally, we show how the remote memory access pattern of LCC presents data reuse (temporal locality), which we exploit by caching RMA \emph{get} operations with CLaMPI. Figure~\ref{fig:full-overview} shows an overview about the proposed approach. \input{Inlines/lcc_comp} \subsection{Asynchronous computation} \label{sec:distlcc} We use a 1D partitioning scheme to distribute the graph among the processes~\negcircnum{1}. In this scheme, an equal number of vertices are assigned to each process. With $p$ computing nodes this is given by $V = V_1 \cup V_2 \ldots \cup V_p$, such that: \begin{displaymath} V_k = \left\{v_i : i \in \left(\frac{(k-1) \cdot n}{p}, \frac{k \cdot n}{p}\right]\right\} \end{displaymath} We note that, in case the degrees are highly skewed, this partitioning method can introduce load imbalance between processes. A more balanced partitioning can be achieved by cyclic distribution~\cite{CyclicDistribution}. However, this would require sorting vertices, introducing additional computation as well as communication. Processes compute the number of triangles for every locally owned vertex~\negcircnum{2}. In the edge-centric method (see Section~\ref{sec:tc}), a process $p_i$ computes $|adj(v_i) \cap adj(v_j)|$ for every $e_{i,j} \in E$ such that $v_i \in V_i$ and $v_j \in adj(v_i)$. In case the vertices $v_i$ and $v_j$ belong to different partitions, the owner process first reads the adjacency of $v_j$ from remote memory. In the CSR representation, the degree of a vertex is implicitly stored in the \texttt{offsets} array, therefore, after computing the number of triangles the LCC score is instantly attainable. The algorithm is outlined in Algorithm~\ref{algo:dist_lcc}. As the graph is stored in CSR representation~\negcircnum{3}, to read the adjacency list of a vertex from a remote node, we need to perform two remote read operations: one for reading from the \texttt{offsets} array the offset of the adjacency list in the \texttt{adjacencies} array~\negcircnum{4}, followed by a second one that reads the actual adjacency list from the \texttt{adjacencies} array (i.e., starting at the right offset)~\negcircnum{5}. To enable remote access, processes expose their local graph partitions over the network. As a result, the graph is logically shared among all the processes: it can be accessed either locally (i.e., for locally owned partitions) or remotely (i.e., for partitions owned by other processes). Using MPI-RMA, this can be achieved in two windows, denoted by $w_{\textrm{offsets}}$ and $w_{\textrm{adj}}$~\negcircnum{3}, in which processes share their local \texttt{offsets} and \texttt{adjacencies} arrays, respectively. When performing remote reads, processes first issue a RMA \emph{get} targeting the $w_{\textrm{offsets}}$ RMA, then issue a RMA \emph{get} on the $w_{\textrm{adj}}$ window to retrieve the adjacency list. To guarantee that the algorithm is fully asynchronous, we adopt the MPI passive target synchronization mode~\cite{hoefler2015remote}. In this way, processes initially expose the interested memory regions in RMA windows, which then become accessible from remote peers without further synchronization. A process that wants to access a remote window first calls a \texttt{MPI\_Win\_lock\_all} to start an access epoch. This is followed by one or more RMA \emph{get} operations. \emph{We remark on the unfortunate name of \texttt{MPI\_Win\_lock\_all}: it is not an actual lock, and thus it does not synchronize processes. Instead, its effect is to signal the beginning of a new access epoch; the remote window can still be accessed by multiple (``all'') processes.} After accessing data, the process can then perform a \texttt{MPI\_Win\_flush} operation or close to access epoch with an \texttt{MPI\_Win\_unlock\_all} to make sure that the remote reads are completed and that the relative data can be accessed without risk of corruption. Even in this case, the closure of an access epoch in the passive synchronization mode is a local operation, and it does not require synchronization. Finally, to increase efficiency, we use a double-buffering approach where we overlap the processing of two consecutive edges by overlapping the computation phase of the current edge with the communication corresponding to the next one. \subsection{Exploiting data reuse} \label{sec:datareuse} While remote memory accesses enable a global memory abstraction where each node can access the memory of remote ones, these accesses are normally one or more orders of magnitude more expensive than accessing local memory. For example, they can take up to 2-3 microseconds on a Cray Aries network~\cite{rma-caching}. In contrast, a DRAM accesses takes hundreds of nanoseconds that become tens of nanoseconds if the data is in cache. By distributing the graph among multiple processes, a large portion of the edges has endpoints in distinct partitions, thus requiring remote communications. For example, in an R-MAT graph with $2^{20}$ vertices and $2^{24}$ edges equally partitioned among 8 processes using 1D partitioning, 95\% of the edges go between different partitions. Assuming that vertices are randomly assigned to computing nodes, the in-degree of a vertex directly correlates with the number of times it will be remotely accessed. Using $p$ computing nodes, a node will access a non-local vertex $v_j$ in expectation $\frac{deg^-(v_j) - p}{p}$ times. Most real-world graphs present a degree distribution that follows a power law. Hence, a large portion of the remote reads will target the same small set of vertices. An illustration of how the highest degree vertices contribute to the number of remote communications can be found in Figure~\ref{fig:data_reuse}. \salvo{explain fig 3 in the text, make example how to read it} \begin{figure}[t] \centering \input{Final_figures/data_reuse_presi_2.pgf} \caption{Data reuse in four datasets using 8 processes and 1D partitioning. The plot shows how the highest degree vertices contribute to the total number of remote reads issued. Upper left, we show a graph with uniform degree distribution, while the other graphs follow a power law-like degree distribution (see Table~\ref{tab:snap_graphs}). We highlight the fraction of remote reads that target the top 10\% of the highest degree vertices.} \vspace{-1.5em} \label{fig:data_reuse} \end{figure} We exploit temporal locality in the remote memory access pattern by using a caching layer for RMA, CLaMPI, that allows to transparently cache MPI RMA accesses~\negcircnum{6}. By caching remote data, each node stores a dynamically defined sub-graph containing vertices that are frequently accessed and thus are expected to be accessed in the future as well. As discussed in Section~\ref{sec:distlcc}, an access of a remote adjacency list is done through two steps: a first RMA \emph{get} to read from the $w_{\textrm{offsets}}$ of a remote node, followed by a second RMA \emph{get} to the $w_{\textrm{adj}}$ of the same node (using the data offset read with the first \emph{get}). We enable caching for both RMA windows at every process. This results in two CLaMPI caches: $C_{\textrm{offsets}}$ and $C_{\textrm{adj}}$. \review{The former caches data offsets telling the position at which the adjacency list of a vertex starts and ends}{R3.11}{orange}, \review{whereas the latter stores full adjacency lists of cached vertices.}{R3.4}{orange} Both caches are set to \emph{always-cache} as the graph is never modified during the computation. In this configuration, CLaMPI does not automatically flush caches between access epochs. \subsubsection{Cached windows characterization} The following two observations describe the characteristics of the two CLaMPI caches and serve as a ground for their analysis: \begin{observation} \label{obs:1} As noted earlier, the number of accesses to a vertex correlates with its degree. As the entries in $C_{\textrm{adj}}$ are adjacency lists and the size of the adjacency list of a vertex is equal to its degree, the size of the cached adjacency lists is a good indicator for the reuse of entries in $C_{\textrm{adj}}$. \end{observation} \begin{observation} \label{obs:2} On the other hand, $C_{\textrm{offsets}}$ stores fixed-size entries, namely the offsets of adjacency lists in the remote \texttt{adjacencies} arrays. Therefore, there is no connection between the size of an entry and its reuse. However, an entry that stores the position of the adjacency list of a high-degree vertex will be accessed more often than an entry corresponding to a low-degree vertex. \end{observation} We illustrate these observations in Figure~\ref{fig:degree} using the Facebook circles dataset~\cite{mcauley2012learning}. The figure shows how, in the case of $C_{\textrm{adj}}$, the entry reuse (left) correlates with the entry size (right). Even though for directed graphs in- and out-degree may differ, we expect that the second observation also holds in the directed case due to the high reciprocity in real-world graphs. \begin{figure}[H] \vspace{-0.5em} \centering \includegraphics[width=\columnwidth]{Final_figures/degree_access.pdf} \caption{Data reuse and cache entry sizes for the Facebook circles dataset~\cite{mcauley2012learning} distributed among two computing nodes.} \label{fig:degree} \vspace{-0.5em} \end{figure} We enable CLaMPI's adaptive strategy for the auto-tuning of the hash table size. However, as the adaptive strategy flushes the cache every time it adjusts the hash table size, it is crucial to determine good starting values. The size of the hash table should be equal to the expected number of entries in the cache. $C_{\textrm{offsets}}$ stores fixed-size entries, where every entry corresponds to one vertex in the graph. Therefore, the number of entries in $C_{\textrm{offsets}}$ is linear in $n$ and in the size of memory allocated for the cache. For example, if the cache size equals $n/2$ bytes, the optimal size of the hash table for $C_{\textrm{offsets}}$ will roughly equal $n/2$. We expect to cache some of the highest degree vertices. Thus a small number of entries in $C_{\textrm{adj}}$ is likely to take up much of the space allocated for this cache (recall the size of the entry equals the degree of the corresponding vertex). If the graph's degree distribution follows a power law, the size of the hash table for $C_{\textrm{adj}}$ will be a function of the graph size and the cache size, which will also follow a power law. In this case, if the cache size is half of the graph's size, we expect to store $n \cdot 0.5^{\alpha}$ many entries in the cache. We found that $\alpha = 2$ results in a good approximation for the hash table size. \subsubsection{Application-defined scores for cached entries} \review{By default, CLaMPI selects entries to evict with a least recently used (LRU) scheme weighted on a positional score to limit external fragmentation. With this scheme, high-degree vertices can still be evicted if the CLaMPI cache fills up (e.g., due to many low-degree vertices being accessed). Additionally, as CLaMPI caches a missing entry only if it has resources to store it, evicted high-degree vertices have a lower chance of being re-cached due to their larger sizes.} \review{We notice how the vertex degree represents a good indication of the importance of storing that vertex: the higher the degree, the more probable it is that the vertex will be accessed multiple times.}{R3.6}{orange} In particular, Observation~\ref{obs:1} enables us to use this application-specific knowledge about an entry's value to increase further caching performance. By controlling the eviction procedure based on the degree centrality of the vertices, we expect to avoid storing a high number of low-degree vertices. Lower degree vertices would consume space in the cache while having a lower likelihood of being reused. We modified CLaMPI to accept an application-specific score passed by the user. This score is used by CLaMPI in the victim selection process whenever an entry must be evicted. After completing the \emph{get} targeting $w_s$, we know the out-degree of the non-local vertex, and we can assign it as a score of the respective adjacency list in $C_d$. We note that this extra knowledge about an entry's value may lead to increased performance, but we lose the spatial effect of the score that attempted to reduce fragmentation. \subsection{Optimization of local computation} \label{sec:dynamic} We take advantage of parallelism on the edge level and compute the intersection of the adjacency lists in parallel with OpenMP. For the binary search-based method, we distribute work among the threads by splitting the shorter (keys) array into equal-sized chunks. On the other hand, for SSI, we split the longer array and every thread intersects the assigned chunk with the shorter list. By using parallelism for the computation of the intersection and not on a higher level (e.g. distributing edges among threads) we can achieve low imbalance between the threads. However, as a too-small parallel region would limit performance, we determine a cut-off value, for which case the intersection is computed sequentially. Moreover, to decrease the cost of entering a parallel block, we specify \texttt{OMP\_WAIT\_POLICY=active} that forces threads to spin even if they are inactive. Based on the time complexities of the algorithms described in Section~\ref{sec:tc}, for two sorted lists $A$ and $B$ with $|A| \leq |B|$, one can arrive at the following rule for the case where SSI is theoretically faster: \begin{equation} \frac{|B|}{|A|} \leq log_2(|B|) - 1 \label{eq:bin_ssi_rule} \end{equation} We utilize this decision rule to arrive at a hybrid method for triangle counting where frontiers are empirically compared to decide which method to apply for computing the intersection. \section{Experimental Evaluation} \subsection{Experimental setup} To evaluate our distributed LCC solution, we used R-MAT~\cite{chakrabarti2004r} synthetic graphs and real-world graphs from \review{several databases}{R4.4}{red}~\cite{snapnets, konect, UbiCrawl}. An R-MAT graph with scale $x$ and edge factor $y$ includes $2^x$ vertices and $2^{x+y}$ edges. We generate R-MAT graphs with the parameters $a=0.57$, $b=c=0.19$ and $d=0.05$ for controlling the degree distribution. \reversemarginpar \review{Table~\ref{tab:snap_graphs} lists properties of the graphs that were used for the final experiments and shows the size of their CSR representation after one-degree removal.}{R4.5}{red} \normalmarginpar Shared memory benchmarks were run on an Intel® Xeon Gold 6154 @ 3.00GHz CPU with 16 cores, and the code was compiled with Intel's ICC 2021.1 with the \texttt{-O3} flag. The distributed version was tested on the Piz Daint cluster at the Swiss National Supercomputing Centre (CSCS). We used the XC50 computing nodes, which are powered by 12 core Intel® Xeon® E5-2690 v3 2.60GHz CPUs equipped with 64GB RAM per node and interconnected with Cray's Aries network arranged in a dragonfly topology. The code was compiled with the ICC 19.1 compiler with \texttt{-O3} flag and using the cray-mpich 7.7.16 MPI implementation. \review{We distinguish small-scale experiments with no more than 64 computing nodes that we allocate on a single electrical group and large-scale experiments with 128 or more, allocated freely over the whole cluster.}{R3.12}{orange} Time measurements were taken using the LibLSB library~\cite{benchmarking}. For shared memory experiments, we report the median and repeated every experiment until the 5\% of the median was within the 95\% CI. For distributed memory experiments, we measure two different job allocations with three executions per allocation. We report the median of the longest-running node among all runs with the corresponding 95\% CI. The reported results do not include the read-in of the graph and the relative distribution phase but only the time taken for the LCC computation. \begin{table}[h] \vspace{-0.5em} \renewcommand{\arraystretch}{1.3} \centering \caption{\review{Graphs used in this paper.}{R4.5}{red}} \label{tab:snap_graphs} \begin{tabular}{l c c c} \hline \textbf{Name (type)} & $\mathbf{|V|}$ & $\mathbf{|E|}$ & \textbf{CSR Size}\\ \hline SNAP-Orkut (U) &3 M&117.2 M& 905.8 MiB\\ SNAP-LiveJournal (U) &4 M&34.7 M& 273.8 MiB\\ SNAP-LiveJournal1 (D) &4.8 M&69 M& 273.7 MiB\\ SNAP-Skitter (U) &1.7 M&11.1 M&89.5 MiB\\ uk-2005 (D) &39.5 M&936.4 M& 3.6 GiB\\ wiki-en (D)&13,6 M&437.2 M& 1.7 GiB\\ R-MAT S21 EF16 (U)&2.1 M&33.6 M& 251.1 MiB\\ R-MAT S23 EF16 (U)&8.4 M&134.2 M& 1021 MiB\\ R-MAT S30 EF16 (U)&1073.7 M&17179.9 M& 130 GiB\\ \hline \end{tabular} \end{table} \subsection{Comparison baseline} \begin{table}[b] \vspace{-1em} \renewcommand{\arraystretch}{1.3} \centering \caption{Performance comparison of the different intersection methods on different graphs using 16 threads. We report the number of edges processed per microsecond.} \label{tbl:int_comp} \begin{tabular}{l c c c} \hline \textbf{Name} & \textbf{Hybrid} & \textbf{SSI} & \textbf{Binary search}\\ \hline R-MAT S20 EF8 & 0.540 & 0.508 & 0.449\\ R-MAT S20 EF16 & 0.425 & 0.403 & 0.340\\ R-MAT S20 EF32 & 0.325 & 0.311 & 0.250\\ LiveJournal & 1.084 & 1.018 & 0.984\\ Orkut & 0.596 & 0.552 & 0.503\\ \hline \end{tabular} \end{table} \begin{figure}[b] \vspace{-0.5em} \centering \includegraphics[width=\columnwidth]{Final_figures/shared_memory.pdf} \vspace{-2em} \caption{Strong scaling on shared memory with hybrid method. We report the number of edges processed per microsecond.} \label{fig:int_scale} \end{figure} \begin{figure*}[t] \centering \includegraphics{Final_figures/cache_behavior.pdf} \caption{Cache behaviour as a function of the cache size. We enable caching only on the respective window, and issue non-cached reads on the other. We used an R-MAT graph with $2^{20}$ vertices and $2^{24}$ edges distributed among 2 computing nodes and measured 100 configurations for both caches. The grey area shows compulsory misses.} \vspace{-1em} \label{fig:mem_scale} \end{figure*} \review{We compare our solution to TriC~\cite{Tric}, a state-of-the-art, distributed-memory framework for global triangle counting. TriC achieves TC in a per-vertex fashion, implicitly computing LCC scores. The main difference to our solution lies in the query-response approach used by TriC to check for necessary remote edges that leads to synchronization between processes.}{G2}{Green} \review{TriC's memory demand significantly increases for scale-free graphs, often leading to out-of-memory errors. In those cases, we employed a new version of TriC (\emph{TriC Buffered}) that allocates fixed-size buffers towards remote processes.} \review{We build TriC using the same Intel ICC 19.1 compiler and map tasks to CPU cores, as it is an MPI-only implementation. For every execution, we specify the \texttt{-b} flag to achieve a more balanced partitioning. We set the buffer size to the largest possible value not bigger than 16 MiB. This cap was necessary due to a network protocol change for messages bigger than 16 MiB that led to higher communication overheads.} \subsection{Shared memory experiments} Our measurements comparing the different methods for computing the intersection are summarized in Table~\ref{tbl:int_comp}. The trade-offs between binary search and sorted set intersection were discussed in Hu et al.~\cite{hu2018tricore}. They locate the main weakness of binary search on CPUs in the random accesses in the lookup tree, which leads to a high number of cache misses. On the contrary, SSI traverses the arrays linearly making possible close to zero cache misses. However, in a graph with skewed degree distribution, most edges connect vertices with degrees that are multiple orders of magnitude different from each other. In that case, binary search is essential, as its running complexity is logarithmic in the length of the longer array. Our results show the necessity of both methods on CPU, as the hybrid version always performed better than using SSI or binary search exclusively. A strong scaling experiment was carried out to measure the gains of computing the intersection in parallel (Figure~\ref{fig:int_scale}). \review{We distribute the local computation on edge level that leads to leaving and re-entering the parallel region for every edge. In effect, the large number of OpenMP library calls becomes a performance bottleneck, which we could also justify by profiling our implementation.}{R1.1}{Blue} \review{We could see a minor improvements of 2\%-4\% with using \texttt{OMP\_WAIT\_POLICY=active}.}{R1.2}{Blue} The best results are achieved for the R-MAT S20 EF32 graph with a speedup of 2.7$\times$ from 1 to 16 threads. \subsection{Distributed memory experiments} \subsubsection{Caching performance} The time of a remote read of size $s$ bytes can be modeled by $t(s) = \alpha + s \cdot \beta$, where $\alpha$ is the setup overhead and $\beta$ the time to read one byte. This means that for the analysis of the cache, both the number of \emph{get}s saved by caching (hit rate) as well as the size of such \emph{get}s have to be taken into consideration. In Figure~\ref{fig:mem_scale} we demonstrate how the difference between the entries stored in $C_{\textrm{offsets}}$ and $C_{\textrm{adj}}$ (see Section~\ref{sec:datareuse}) and the above remark on the duration of a remote memory read influence communication time for LCC computation. The power law-like relationship between the miss rate and $C_{\textrm{adj}}$'s size is the straight consequence of our algorithm and the graph's degree distribution. In this case, we also notice how already a small memory overhead (relative to $|V|$) allows us to save up to 30\% of the time spent on communication. In contrast, we observe a linear relationship between the miss rate in $C_{\textrm{offsets}}$ and its size due to the connection between an entry's size and the frequency of remote reads targeting the entry. However, a large portion of transferred data comes from remote reads targeting $w_{\textrm{adj}}$, which is reflected in the reduction in communication time achieved by $C_{\textrm{adj}}$. In this experiment, we reduce communication time by 51.6\% with caching only $w_{\textrm{adj}}$. We expect that for larger datasets, this difference will grow further. Summarizing, with a small memory overhead, one can save an initial amount of communication that targets $w_{\textrm{offsets}}$. However, any further decrease will have a memory overhead linear in terms of the graph's size. \begin{figure}[t] \centering \includegraphics[width=\columnwidth]{Final_figures/score_comparison.pdf} \caption{Comparison of original and user-defined scores. We show the average time taken for reading a remote vertex. The grey area shows compulsory misses.} \vspace{-1em} \label{fig:score_comparison} \end{figure} \input{Inlines/overall_performance} In the following, we assess the effect of the application-specific score described in Section~\ref{sec:datareuse}. In this experiment, we fix the memory allocated for $C_{\textrm{adj}}$ to 25\% of the size of the graph's non-local partition at every node to trigger the eviction procedure. The results for an R-MAT graph with $2^{20}$ vertices and $2^{24}$ edges are shown in Figure~\ref{fig:score_comparison}. Degree centrality scores improve caching performance between 14.4\% and 35.6\% with respect to the original scores for this dataset. \subsubsection{Overall performance} Finally, in Figures~\ref{fig:full_exp} and~\ref{fig:big_exp} we report the performance of our LCC implementation both with and without caching. Next to the measurements, we denote the speedup achieved with respect to the smallest configuration. \review{For experiments using caching, a total of \emph{16 GiB} memory is reserved, allocating $0.8 \cdot |V|$ bytes for $C_{\textrm{offsets}}$ and the rest for $C_{\textrm{adj}}$.}{R3.10}{orange} \review{Note, that with this configuration $C_{\textrm{offsets}}$ can store $0.4 \cdot |V|$ many vertices, as the position of a remote adjacency list is given as a pair of \emph{(start, end)} positions.}{R3.11}{orange} Furthermore, we also show measurements using TriC to better asses our implementation. \review{In case of missing data points, the corresponding experiment exceeded a wall-time of 9 hours.}{G2}{Green} As the graph is distributed among more computing nodes, the number of edges that cause communication increases. For example, for the R-MAT S21 EF16 graph, the average fraction of remote and local reads grows from 66\% to 98\%. For the same graph, with 4 computing nodes, communication already takes up to 78.9\% of the total running time, which rises to 97.7 \% for 64 nodes. In general, we could observe that communication quickly dominates the total running time, implying that the limitations of the shared memory computation have minor effects on overall performance. \review{Moreover, it follows that overlapping communication and computation, even for more than a single edge, cannot significantly improve the runtime.}{R3.5}{orange} As communication dominates, the speedup achievable is determined by the number of edges causing communications. At small scale, the worst scaling for a real-world graph is observed on the Orkut graph with $9.4\times$ speedup from 4 to 64 nodes. We explain this with the following two reasons. Firstly, for this graph, the running time is mostly determined by computation when 4 nodes are used, but quickly becomes communication-bound with larger configurations. Secondly, in this case, 1D partitioning causes load imbalance, leading to an up 25\% difference in the running time of the different processes. We achieve our best results for the LiveJournal1 graph, with 14$\times$ speedup from 4 to 64 computing nodes. Our large-scale experiments are similarly limited by load imbalance, which bounds the achieved scaling. \footnotetext{We report only one measurement per data point for the RMAT S30 EF16 graph due to cost reasons.} \review{The efficiency of caching is influenced by multiple factors. Firstly, in case the cache size is significantly smaller than the size of the graph, capacity misses are unavoidable. Secondly, the graph structure inherently determines the possible data reuse, and graphs with flatter degree distribution will lead to a large number of compulsory misses.}{R4.6}{Red} Finally, by distributing the graph among an increasing number of computing nodes, data reuse reduces due to the increasing number of edges that cross partitions. This will similarly result in an increased number of compulsory misses. Compulsory misses decrease the overall hit rate and incur an overhead caused by the caching process in CLaMPI. For example, for the LiveJournal graph, 15.5\% of the remote reads are compulsory misses for 4 nodes (a compulsory miss is always a compulsory miss in both caches) that grows up to 64.9\% with 64 nodes. Regarding the overall performance, we can distinguish between 3 scenarios: (1) computation dominates and caching has no significant effect; (2) high number of compulsory misses limit caching performance; (3) caching is beneficial and reduces the communication time. Scenario (1) can be seen for the Orkut graph where the effect of caching increases from 4 to 8 computing nodes. Scenario (2) is especially notable for the LiveJournal and LiveJournal1 graphs. In these cases, CLaMPI's overhead leads to worse performance than the non-cached version. However, we see significant reduction in running times between these two extremes. At small scale, we achieve up to 67\% and 47\% better running times for the R-MAT S21 EF16 and LiveJournal graphs, respectively. \review{At large scale, the cached version resulted in 73\% better performance compared to the non-cached implementation for the R-MAT S30 EF16 graph. We remark, that this result is achieved with a cache size of only 12\% of the graph's CSR representation.}{G1}{Green} \review{We achieve significantly better execution times both at large-scale (up to 3.6x speedup) and at small-scale (up to 100x) compared to TriC. The advantages of our asynchronous implementation over TriC is especially notable with the synthetic datasets that posses a close to perfect scale free degree distribution.}{G2}{Green} Despite the imbalance between processes coming from the 1D distribution, we conclude that these results justify the necessity of an asynchronous algorithm for distributed-memory LCC computation. \section{Related Work} In the following, we summarize the main techniques used for shared and distributed-memory TC analysis. For a thorough comparison of the different triangle counting algorithms, we refer the reader to the paper from Schank and Wagner~\cite{tclisting}, and to work by Shun et al.~\cite{shun2015multicore}. \subsection{Frontier intersection} SSI has been introduced by Green et al.~\cite{intersect-path}, and binary search appeared first for triangle counting in Hu et al.~\cite{hu2018tricore}. Pandey et al.~\cite{pandey2019h} utilize hashing for computing intersections but, instead of hashing every element, they use a selected number of bins where multiple elements are stored. This solution was further improved in their recent work~\cite{TRUST}. \subsection{Algebraic computation} For a graph $G$ one can compute the matrix $\mathbf{C} = \mathbf{A}\mathbf{A}\circ\mathbf{A}$, whose entry $c_{ij}$ stores the number of triangles that contain $e_{ij}$. For undirected graphs, this can be simplified to $\mathbf{C} = \mathbf{L}\mathbf{U}\circ\mathbf{A}$, where $\mathbf{L}$ and $\mathbf{U}$ are the lower and upper triangular matrices. Triangle counting implementations based on this algebraic computation method take advantage of the sparsity of $G$ and use highly optimized libraries for sparse matrix multiplication. An improved parallel implementation can be found in the paper from \review{Azad et al.~\cite{azad2015parallel}}{R1.5}{Blue}, and a distributed algebraic-based TC algorithm has been proposed by Hutchinson~\cite{hutchison2017distributed} using the Apache Accumulo distributed database. Aznaveh et al.~\cite{graphblas} implemented shared memory parallel TC and LCC computation based on the SuiteSparse\:GraphBLAS implementation of the GraphBLAS standard. \subsection{Distribution techniques} For any TC or LCC algorithm that utilizes parallelism on some level, work distribution is of primary importance. Kolda et al.~\cite{kolda2014counting} use the Mapreduce technique for triangle counting. Lumsdaine et al.~\cite{CyclicDistribution} introduced a cyclic distribution for 1D to achieve balanced partitions. Two-dimensional partitioning assigns edges to processes in a grid-based manner. \reversemarginpar \review{Tom and Karypis~{\cite{tom20192d}}}{R1.4}{Blue}\normalmarginpar~developed a triangle counting algorithm for undirected graphs following a parallel matrix multiplication scheme based on 2D. Acer et al.~\cite{8916302} utilize 2D partitioning among the computing nodes and achieves shared memory parallelism based on 1D. Hoang et al.~\cite{hoang2019disttc} compute shadow edges and corresponding vertices that are necessary for local triangle computation, thus avoiding any communication during the computation phase. We emphasize that all the aforementioned work requires synchronization mechanisms, and therefore, their scalability is limited. \section{Conclusion} We introduce a fully asynchronous distributed-memory algorithm for both triangle counting and LCC. Synchronization overheads are removed by using RMA one-sided operations to retrieve remote parts of the graph that are needed to progress the algorithm (i.e., parts of the adjacency lists that have been partitioned and assigned to remote peers). Additionally, we show how irregular graph algorithms such as LCC and TC expose data reuse, which we exploit by using a transparent caching solution for RMA, i.e., CLaMPI. To improve cache efficiency, we extend CLaMPI to take into account application-specific scores when deciding which entries to evict in case of conflict or capacity misses. For example, by using degree centrality as the score for LCC, we are able to reduce the total running time by up to \review{73\%}{G1}{Green}. Overall, we show that removing synchronization costs and achieving vertex delegation by a caching mechanism leads to clear performance improvements over the current state-of-the-art. Finally, we plan to extend this work in many directions by i) designing new asynchronous algorithms for TC/LLC based on distribution schema that have lower communication costs than 1D distribution~\cite{10.1007/978-3-642-23397-5_10}; ii) investigating other graph problems that may benefit from the proposed approach~\cite{9432723, 10.1145/3182656, solomonik2017scaling, besta2020high} and, in general, those that can be expressed in a push-pull dichotomy~\cite{10.1145/3078597.3078616}; iii) studying other application-specific scores for cached entries to improve caching efficiency. \section*{Acknowledgment} \footnotesize This work has been partially funded by the UNIBZ-RTD-CALL2018-IN2087, INdAM–GNCS 2020-NoRMA, MIU-FISR-2020-FISR2020IP\_00802 projects, and the European Project RED-SEA (Grant No.~955776). This project has received funding from the European Research Council (ERC) under the European Union’s Horizon 2020 research and innovation program (Grant agreement No.~101002047). We thank the Swiss National Computing Center (CSCS) for providing computing resources and excellent technical support. \begin{figure}[h] \centering \includegraphics[height=3em]{Final_figures/erc_logo} \end{figure} \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-02T02:42:20', 'yymm': '2202', 'arxiv_id': '2202.13976', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13976'}
arxiv
\section{Introduction} Observations of effects in everyday social and biological systems are riddled with statistical problems familiar to any researcher - low effect generalizability, heterogeneity, confounding and selection biases. Commonly studied processes such as Economic and Evolutionary Competition, Epistemic Development and Viral transmission are not immune to any of these. In each case, it is unclear to what extent these statistical pitfalls are simple nuisances, or have a shaping influence in the overall operation of systems. Here, we use recent advances in the understanding of how combinatorial properties of populations constraints learning to address this question. The \textbf{Pareto Principle} states that '80\% of consequences come from 20\% of the causes', or, that a minority of factors are typically responsible for outcomes \cite{Cooter:2009aa,Newman:2005aa,Holden:2010aa}. It was devised and observed first across economic outputs, becoming a principle of Welfare Economics and the study of inequality. Today, it is known to be ubiquitous across human processes. The pattern is evident in the output of cities, corporations, scientists, sport teams, criminals, websites, etc. It is often used as a heuristic in Business and Engineering. In a previous article \cite{ribeiro-ev}, we discussed the related 80-20\% train-test split in Machine Learning. \textbf{The principle remains, however, a mere fact of observation} and not a scientific theory in any sense. Mathematically, the 80-20 rule is described by a power-law, but for a very particular set of parameters, when its shape is $\log_4 5 = \sfrac{\log_{10} 5}{\log_{10} 4} \approx 1.161$. Why is this ratio so prevalent across selective and competitive systems? Most empirical mathematical models for the spatial growth of cities, such as Power-law and Levy-flight\cite{Gabaix:1999aa,KORTUM:1997aa,Verbavatz:2020aa,Li:2017aa,Song:2010aa}, are based on limits introduced by physical distances among homogeneous 'particles', and not the demographic \cite{Bettencourt:2020aa,Ribeiro:2021aa} and recombination processes \cite{15306,Uzzi:2013aa} shaping growth (see \textit{Sect. Related Models}). These models become useful at high agglomerate levels, where they can employ the Law of Large Numbers to explain statistical issues away. As consequence, however, they (1) lose in specificity and predictive accuracy, and, (2) miss the shaping influence population diversity and biases may have in systems' own growth. Understanding the limits and opportunities brought by population heterogeneity is a current challenge across disciplines\cite{RefWorks:doc:5ae0f6f3e4b07da0d123c2b5}, from precision Medicine to Machine Learning. In spatial systems, in particular, it is not yet clear \textbf{how biases evolve with spatial-levels}, and which levels are optimal in respect to each. There have been recurrent graph-theoretical attempts to connect population diversity, or combinatorial structures, with systems performance \cite{Allen:2017aa,Lieberman:2005aa}. But theories so far have not led to clear empirical confirmation and lack in simplicity (compared to the previous law-like models). A remarkable characteristic of all previous systems is their ability to create inner-outer boundaries and hierarchies that are capable of coping with increasingly complex environments. To that end, they must satisfy two opposing requirements. Systems must promote robustness across their out-of-control contingencies \cite{Gao:2016aa} and selectability among their under-control\cite{Walliser:2011aa}. We say a System undergo Externally Valid (EV) growth when effects of its internal variations remain general across external. They undergo Unconfounded (CF) growth when internal effects remain distinguishable. Competitive processes are a common example of selective processes, and mechanisms to select solutions with largest comparative fitness in populations. \begin{figure} \centering \includegraphics[width=0.9\linewidth]{figs/intro-204.pdf}\\ \caption{\textbf{(a)} Rock-Paper-Scissor game simulation under replicator dynamics with a small exogeneous noise (left, 3 runs), after accumulation of a complete set of counterfactual utility observations (right), \textbf{(b)} Can counterfactual effect observations made in one location be used in another (are they externally valid, EV)? Can they be distinguished from others (are they unconfounded, CF)?, reciprocal growth and balance phases and their representation as hyperbolic rotations, the first increases the number of external conditions effects are measured under (EV), the second of internal conditions (CF), each have distinct statistical consequences on growing populations, \textbf{(c)} a $m{\times}m$ Latin-Square ('square') portrays the full set of counterfactual effect observations with $m$ factors ($m=2,4$), further counterfactuals increases guarantees over the generalizability and bias of populations' effect observations, the square's 1\textsuperscript{st} column ($m=2$, left) is associated with all differences from a reference population $x_0$ of size $1$ (and overlap $m-1$), $\{a\}$ and $\{b\}$, the 2\textsuperscript{nd} column with differences of size $2$ (and zero overlap), $\{a,b\}$, difference-of-differences enumerate all factor permutations, $(\{\{a,b\} - \{a\}\} \sim ba)$ and $(\{\{a,b\} - \{b\}\} \sim ab)$ (upper-left, nested sets), these \textit{derangements} (permutations without overlaps) are the squares' rows and columns (right), \textbf{(d)} Binomial ($\frac{1}{2}$), Fibonaccian ($\frac{1}{\phi}$) and Exponential ($\frac{1}{e}$) rates across squares lead to the hyperbolic relations in (b), each square's triangle area (gray) is related to EV, their area difference to CF, triangle altitude (dashed) to growth 'bandwidth' (number of populations growing under shared EV-CF conditions).}\label{fig-intro} \end{figure} \subsection{Counterfactuals and Games.} Most game-theoretic solutions, such as the standard Nash equilibrium, are formulated from counterfactuals. These are what-if statements (i.e., what would happen to a player's utility if he or she took action $a$, but all else remained constant). Fig.\ref{fig-intro}(a, left) shows a Rock-paper-scissor game (3 simulation runs, gray curves). Each player utility depends on a common noise, $\mathcal{N}(0,0.1)$, that is not observed. Players follow the replicator dynamics \cite{Taylor:1978aa}, a learning strategy akin to natural selection. The state space depicts the probability of players playing each of the 3 actions (triangle corners). The Nash equilibrium is a cyclic choice among them, which players fail to attain. Imagine, however, that players agree to play the game in two phases. In the first, they forego immediate strategic choices to accumulate a full set of action counterfactuals. Fig.\ref{fig-intro}(a, right) shows the state space in this alternative scenario, where trajectories coincide with the theoretic equilibrium, across runs. Players play cooperatively to a combinatorial threshold, and playing-field with minimal statistical guarantees\footnote{the threshold can be either enforced by the statistical consequences of play (i.e., by mechanism design), or anticipated by agents with foresight.}, before entering competitive play. \section{Model Summary} Statistical Growth with selection can be seen as the enumeration, and evaluation, of counterfactual populations across time. Each population member's growth trajectory is an incremental, and temporally ordered, observation of the value of gaining, or losing, a factor from the $m$ possible, $X=\{a,b,c,..., [m]\}$. Each member's trajectory is, however, just one in the $m! \times 2^m$ possible (all factor permutations times gain/loss of each). We say a set of $\omega$ simultaneous trajectories, and permutations, leads, instead, to growth with 'bandwidth' $\omega$. The larger the bandwidth, and number of accumulated counterfactuals, the more (external) conditions in which effect observations are made, and the more likely effects are to generalize across unseen conditions. When $\omega$ is small, effect generalization is only possible at the cost of long time periods, Fig.\ref{fig-intro}(b, upper-right). We demonstrate this implies that growth goes through \textbf{reciprocal phases of growth and balance} of $\omega$ populations. The first permutes ('shuffles'), and the second keeps ('balances') specific frequency relations among new permutations. Together, they maintain basic statistical guarantees across \emph{all} counterfactual interactions and observations, for the $\omega$ populations. Growth and balance are in many ways opposites, as growth bias populations. For the replicator equation in Fig.\ref{fig-intro}(a), populations grow monotonically across a selected dimension, and they are only guaranteed to be balanced once. We say this process has unitary bandwidth, $\omega=1$. Unbiased growth can be understood, combinatorially, in relation to Experimental Designs and, geometrically, to Hyperbolic geometry. The hyperbolic plane's radial component will be associated with the number of permutations accumulated in populations, and the angular component to their balance, Fig.\ref{fig-intro}(b). This portrays growth as rotate-and-forward cycles, in contrast to the forward-only movement of typical processes. We demonstrate empirical patterns in the simultaneous growth of cities, using these representations. \subsection{Combinations, Permutations and Partial Permutations.} The set of all counterfactuals accumulated by growth at one instant can be visualized with a Latin-Square ('square'). A square, as defined here, is a collection of all differences from a reference population $x_0$, $x_0 - \mathcal{P}(X)$, where $\mathcal{P}(X)$ is the set of all subsets of $X$. It is thus a full set of effect observations. This is illustrated for two factors, $\{a,b\}$, in Fig.\ref{fig-intro}(c, left). The simultaneous presence of populations $x_0{+}\{a\}$, $x_0{+}\{b\}$ and $x_0{+}\{a,b\}$ (e.g., in the same location) allow for all permutations of $\{a,b\}$ be enumerated, and therefore each factor's effect, $\Delta y(a)$, be observed, across full variation of others. Squares represent mathematical groups\cite{ribeiro-ev} (\textit{Sect. Statistical Frame-of-Reference Invariance}). Linear-Algebra and Group-theoretic alternative formulations are discussed in the Supplementary Material. The statistical concept of 'population' is often associated with combinatorial combinations, as the set of sample units with a given combination of attributes (e.g., high-income white males). There are thus $\binom{m}{t} = \frac{m!}{t!(m-t)!}$ possible populations of size $t$. A problem with this definition is that it leaves unspecified all non-population factors. To \textbf{define a population we, instead, imagine that we fix the $t$ population factors and vary (i.e., permute) all non-population ('external') factors}. This leads to a combinatorial structure known as a partial permutation. The number of partial permutations with $t$ elements fixed is $\binom{m}{t} \times D_{m-t}$, where $D_{m-t}$ is the number of derangements of size $n=m{-}t$, $D_{m-t}=\sum_{k=0}^{m-t} \frac{(-1)^k}{k!}$. A derangement is a permutation without overlaps. To specify a population, we thus first fix $t$ factors (combination) then vary the all rest (derangement). Squares are related to the first, and sets of squares to the latter (derangements of combinations)\cite{ribeiro-ev}. The full set of permutations, and thus all growth trajectories, can be formulated as sets of partial permutations, \begin{align} m! &=\sum_{t=0}^m \binom{m}{t} \times D_{m-t} \; = \Big[\sum_{t=0}^m\frac{(-1)^tm^t}{t!}\Big] \times \Big[ (m{+}1)!{-}1\Big] \label{eq-derangement}\\ &= \Big[ {\cosh(m{-}1)+\sinh(m{-}1)} \Big] \times (m{-}1)! +1. \label{eq-derangement-2} \end{align} According to Eq.(\ref{eq-derangement}, left), the number of differences necessary to collect one square is $\sum_{t=0}^m \binom{m}{t}$, and all squares is $\sum_{t=0}^m\binom{m}{t}D_{m-t}$ (without repetition). With the latter, we also collect all permutations. After the first square, it thus suffices to continuously derange its constituent combinations. The number $n$ of squares, of size $m\times m$, in a location or sample can thus be specified with the 3D vector $(m,m,n)$, Fig.\ref{fig-intro}(d, left). The odd and even parts of Taylor's expansion of Eq.(\ref{eq-derangement}) leads to hyperbolic trigonometric functions, Eq.(\ref{eq-derangement-2}) (Supporting Material). They indicate the 'period' in which full sets of permutations are collected. Hyperbolic trigonometry will be used below as alternative to Lorentz curves in the study of inequality. \subsection{Externally-Valid (EV) Growth.} The classic definition of factorials tells us that, to generate a permutation, we insert a new factor in all $m-1$ positions of a previous permutation, $m! = m \times (m-1)!$, and repeat. Each square is associated with one such step, when $m$ is limited, Eq.(\ref{eq-derangement-2}). Each (singleton) population $a$, defined as before, is represented by a square diagonal, Fig.\ref{fig-intro}(c). Subsequent square rows and columns correspond to $a$'s points-of-insertion, and permutations of its external factors. This suggests a process where we insert $a$ after varying, in every way, others; after each insertion, we observe the resulting outcome difference, $\Delta y(a)$. An unbiased effect estimate for $a$ is an average across all observations, and constitute an U-Statistic \cite{Lee:1990aa,ribeiro-ev}. There are $F_{m,n}=\sum_{t=0}^m\binom{m-t}{t}$ such sequential observations\footnote{with the convention that $\binom{m-t}{t}=0$, when $t>m$. }. $F_{m,n}$ is the number of factor fixations after $a$ - i.e., $\binom{m-1}{1} = m{-}1$ to fix any second factor, then $\binom{m-2}{2}$ to fix a third, etc. The two previous quantities, $C_m$ and $F_{m,n}$, appear in Pascal's triangle, since a \emph{single} square can be thought as two mirrored triangles, justified to the left, Fig.\ref{fig-intro}(d, middle). The square's upper triangle is the set of all counterfactuals with $a$, and the lower, without $a$, Fig.\ref{fig-intro}(d, right). The number of all possible external conditions for a given square cell is a product of its coordinates, $\binom{m}{t} \times n$, Eq.(\ref{eq-derangement}). Square 'area' is the integration of all these individual area elements. Square area is related to EV, while balance between its two triangles' areas to CF. Growth bandwidth is defined, at time $t$, as $\omega = \frac{F_{m,n}}{D_n}(t)$, or, the number of external observations, $F_{m,n}(t)$, per derangement, $D_n(t)$, in samples or populations. The growth of $C_m$, $D_n$ and $F_{m,n}$ assume Pythagorean relations\footnote{the equation uses the Pythagorean theorem in reciprocal form, as it includes the triangle's altitude.}, Fig.\ref{fig-intro}(d), \begin{subequations} \setlength{\abovedisplayskip}{0pt} \setlength{\belowdisplayskip}{0pt} \noindent \renewcommand{\arraystretch}{0.1 \begin{tabularx}{\linewidth}{>{\hsize=0.4125\hsize\linewidth=\hsize}X >{\hsize=0.4375\hsize\linewidth=\hsize}X>{\hsize=0.15\hsize\linewidth=\hsize}X} \multicolumn{2}{X}{ \begin{equation} \label{eq-pythagoras-1} \Big(\frac{\partial C_m}{\partial D_n}\Big)^{-2} + \Big(\frac{\partial D_n}{\partial D_n}\Big)^{-2} = \Big(\frac{\partial F_{m,n}}{\partial D_n}\Big)^{-2}, \end{equation} }& \begin{equation*} \Big(\frac{\partial C_m}{\partial F_{m,n}}\textit{ const.}\Big) \end{equation*}\\ \begin{equation} \label{eq-pythagoras-2} \frac{1}{\sqrt{ 1 + \Big(\frac{\partial D_n}{\partial C_m}\Big)^2}} = \omega, \end{equation}& \begin{equation} \label{eq-pythagoras-3} \frac{1}{\sqrt{ 1-\omega^{-2}}} = \cosh(\omega^{-1}), \end{equation} & \begin{equation*} \Big(\frac{\partial F_{m,n}}{\partial D_n} = \omega\Big) \end{equation*} \end{tabularx} \end{subequations} Eq.(\ref{eq-pythagoras-1}) suggests the hyperbolic relationship $\partial C_m^2- \partial F_{m,n}^2 = \partial D_n^2$, and visualization of growth as hyperbolae with increasing radius $D_n$, Fig.\ref{fig-intro}(b). The figure shows the hyperbolic asymptotes $C_m=F_{m,n}$ and $C_m=-F_{m,n}$ (dashed). They represent populations with constant EV, $\partial D_n =0$. The figure also shows the asymptotic population (vertical black line) where exactly all members have factor $a$, $F_{m,n}=0$. \textbf{Under this condition, no estimator, algorithm, or player is able to estimate $\boldsymbol{a}$'s effect}. It represents the limiting population with minimum EV, while the outward hyperbolae, populations with increasing EV. Growth in this direction follow a Fibonacci series, whose rate is the Golden number. Notice that $\frac{\partial D_n}{\partial C_m} \in [1/2,1/e]$, as growth can range between purely CF, $\frac{\partial C_m}{\partial m}=2$, and EV, $\frac{\partial D_n}{\partial n}=1/e$, Fig.\ref{fig-intro}(d). The latter (i.e., the rate required for derangements) was famously established by Euler\cite{SandiferCharlesEdward2007HEdi}, and the former is due to $C_m = 2^m$. The combined binomial-exponential process 'doubly-deranges' populations, across their $m!\times 2^m$ possible trajectories. The golden ratio is associated, in contrast, with growth balancing these extremes, EV-CF growth, and with squares. Also associated with squares is the assumption that $\frac{\partial C_m}{\partial F_{m,n}}$ is constant (i.e., a fixed hyperbole), Eq.(\ref{eq-pythagoras-1}). It indicates that all factors are inserted into a common number of permutations (making all factors' diagonals the same size, and the population structure, overall, a 'square'). \subsection{Unconfounded (CF) Growth.} What is the growth rate necessary to collect a square with $m$ factors? We say $m-1/m$ is the 'delay' for counterfactual observations in a $m{\times}m$ square. Any population $a$ must wait $m-1/m$ samples to complete a row \footnote{where $1.0$ is the cost to sample a new difference, with repetition.} (i.e., collect $b,c,d...[m]$). We then write $m-1/m$ for the length of $a$'s balancing cycle, and $m+1/m$ for its growth-balance cycle. The growth-only cycle length is, consequently, their difference, $2/m$. We denote population sizes in each of these cycles: $n_{\overline{a}}$ (balance), $n$ (balance-growth) and $n_a$ (growth). Across time, these quantities express the added cost populations incur to collect, together, a balanced sample. Spatially, they indicate the spatial-level in which they become balanced. Consider the latter, where each location becomes a square cell. Population size $n_t$, with $m$ factors balanced, follow the periodic difference equation $n_{t+m} = n + F_{m,t}$, or, \begin{subequations} \setlength{\abovedisplayskip}{0pt} \setlength{\belowdisplayskip}{0pt} \noindent \begin{tabularx}{\linewidth}{>{\hsize=0.45\hsize\linewidth=\hsize}X >{\hsize=0.3\hsize\linewidth=\hsize}X>{\hsize=0.3\hsize\linewidth=\hsize}X} \begin{equation} \label{eq-n1} n_{t+m}{=}\sum_{n_t} \Big[ \frac{1}{n_t}\Big(m+\frac{1}{m}\Big)+n_t \Big(m-\frac{1}{m}\Big)\Big], \end{equation} & \begin{equation} \label{eq-n2} \sum_{n_t}\frac{1}{n_t} \Big(m+\frac{1}{m}\Big){\rightarrow}\;n, \end{equation} & \begin{equation} \label{eq-n3} \sum_{n_t} n_t\Big(m - \frac{1}{m}\Big){\rightarrow}\; F_{m,t} = n_{\overline{a}}, \end{equation} \\ \begin{equation} \label{eq-n4} \frac{\partial n_{\overline{a}}}{\partial t}=1.6180... \;(\phi), \end{equation}& \begin{equation} \label{eq-n5} \frac{\partial n_a}{\partial t}=2, \end{equation} & \begin{equation} \label{eq-n6} \frac{\partial n_{\overline{a}}}{\partial n_a}=\frac{\phi}{2}, \end{equation} \end{tabularx} \end{subequations} for a constant $m \ll n$. Eq.(\ref{eq-n3}) is an alternative expression for the Fibonacci series\footnote{$F_{m,t+1} = F_{m,t-1} + F_{m,t} \times \Big(m-\frac{1}{m}\Big); \; F_{m,0} =0,F_{m,1} =1$, see \cite{Gazale:1999aa}.}; and, according to Eq.(\ref{eq-n2}), $n$ is fixed per population, under growth with fixed bandwidth\footnote{$\sum_{n_t}\frac{1}{n_t} \Big(m+\frac{1}{m}\Big)=\frac{n_t\times m}{n_t}+\frac{n_t}{n_t \times m} = m+\frac{1}{m}$.}. This reproduces, alternatively, the rates in the previous section. In a random sample with treatment variable $a$, $\Expect [\frac{\partial n_a}{\partial t}\, | \, \boldsymbol{x_0}] = 2$, as, at each 2 time intervals, we are expected to rebalance (random variables are bold). It corresponds to Eq.(\ref{eq-n1}) when $m = 1$, $n_{t+1}$. A location with this property has one population, $a$, balanced, and common external factors, $x_0 = X - \{a\}$. We can alternatively say that $p(a|\overline{a}) = 0.5$, or, $a \perp (X-\{a\}) \; | \; \boldsymbol{x_0}$, which are typical non-confounding conditions. If units in the location share the same external factors, and have the same number of members with $a$ as without $a$, then expected outcome differences between them correspond to $a$'s effect, conditional on the common variation. That is, $\Expect [\Delta y(a) \; | \; \boldsymbol{x_0}] = y(x_0{+}\{a\}) - y(x_0{-}\{a\})$. Selection mechanisms in such locations operate with fair estimates of $a$'s impact (albeit, with low EV). Common factor frequency guarantees no selection biases in 'treatment' assignment, and common external factors, no unobserved confounding. The latter is an instance of the common-cause rule \cite{Reichenbach:1956aa,Scholkopf:2021aa}. In a square, instead of a single factor, \textbf{all $\boldsymbol{m}$ factors are balanced simultaneously} ($m>1$). While single-factor balance requires a binomial series, balancing several factors requires Fibonacci (i.e., square diagonal expansion). Each population, in this case, has asymptotic period $\Expect [\frac{\partial n_{a}}{\partial n_{\overline{a}}}] = \frac{2}{\phi}$ (twice the delay for each diagonal). Square accumulation, furthermore, increases the EV of all its populations simultaneously\cite{ribeiro-ev}, Fig.\ref{fig-intro}(b, upper-right). A spatial square can thus be thought as accumulating higher-frequency local and mutual variation, while sharing the external, and slower, collectively\cite{Ribeiro:2021aa}. Squares are also a generalization of the Shapley value, the central Cooperative solution in Game-Theory. This suggests a hierarchical organization for systems in complex environments. \subsection{EV-CF Growth and Hyperbolic Geometry.} Euler's required period\cite{SandiferCharlesEdward2007HEdi} to derange one population is $e=2.7182...$ Substituting this in Eq.\cref{eq-n1,eq-n2,eq-n3}, for growth with unitary bandwidth, \begin{subequations} \setlength{\abovedisplayskip}{0pt} \setlength{\belowdisplayskip}{0pt}\noindent \begin{tabularx}{\linewidth}{>{\hsize=0.52\hsize\linewidth=\hsize}X >{\hsize=0.48\hsize\linewidth=\hsize}X} \multicolumn{2}{X}{ \begin{equation} \label{eq-cosh1} \Big(e+\frac{1}{e}\Big) = \frac{\cosh(1)}{2},\;\;\; \Big(e-\frac{1}{e}\Big) = \frac{\sinh(1)}{2}, \;\;\; tanh(n)=\frac{\sinh(n)}{\cosh(n)}=\omega^{-1}, \end{equation} }\\ \begin{equation} \label{eq-cosh2} e^{\pm \arctanh\Big(\frac{\partial D_n}{\partial F_{m,n} }\Big)} = \frac{(1 \pm \frac{\partial D_n}{\partial F_{m,n} })}{\sqrt{ \Big(1- \frac{\partial D_n}{\partial F_{m,n} }\Big)^2}}, \end{equation} & \begin{equation} \label{eq-cosh3} \frac{\cosh(n)}{\partial n_a} \rightarrow 0.8090...\; ({EV{-}CF}), \end{equation} \end{tabularx} \end{subequations} which suggests that hyperbolic functions can express population sizes in balance ($\sinh$) and growth-balance ($\cosh$) cycles, as well as the growth process' chosen trade-off between the two ($\tanh$). The same functions appeared in Eq.(\ref{eq-derangement-2}). The equations also suggest, from de Moivre's theorem, an interpretation of hyperbolic angles as the number of growth-balance cycles a system has undergone, $[cosh(1)+sinh(1)]^n = cosh(n)+sinh(n)$, and, from Euler's equation, the rate of a single cycle without balance, $e^{-1} = \cosh(1) - \sinh(1)$. Since $\cosh(n) = (1 - \tanh^2(n))^{-\frac{1}{2}}$, Eq.(\ref{eq-pythagoras-3}) suggests expressing bandwidth in terms of $\tanh(n)$\footnote{with $n =\arctanh(\omega^{-1}) = \arctanh(\frac{D_n}{F_{m,n}})$, which, lets $n$ be the number of accumulated derangements per fixed $F_{m,n}$ (i.e., per square). }, Eq.(\ref{eq-cosh1}). Since $sinh'(n)=cosh(n)$, Eq.(\ref{eq-n6}) indicates the per-population asymptotic rate in balanced growth, Eq.(\ref{eq-cosh3}). The hyperbole with this relative $\cosh$ and $\sinh$ growth rate is indicated in Fig.\ref{fig-intro}(b). \subsection{Statistical Frame-of-Reference Invariance.} While the concept of invariance (of a black-box estimator's response) has applications in Statistics and Machine Learning \cite{Buehlmann:2020aa,Peters:2016aa}, the previous definition brings it closer to how it is understood in the Sciences. A full set of counterfactuals from a fixed reference $x_0$ constitute the set of all discrete differences $x-x_0$. Observation of complete counterfactual sets allow effect observations to become independent of the particular frame-of-reference in which those observations were made, increasing their EV. Multiple square accumulation constitutes a transition between two optimal non-parametric causal effect estimators, from homogeneous to heterogeneous populations \cite{ribeiro-ev}. Eq.(\ref{eq-pythagoras-3}) coincides with Lorentz factor $\gamma$\cite{Hucks:1993aa}. It is natural to think of the transformation as a hyperbolic rotation, as suggested by Emile Borel in 1914\cite{Borel:1914aa}. Here, it preserves frequency relations among factors, $n_a/n_{\overline{a}}$, under changes of basis of the type $x{=}x_0{+}\{a\}$ and $x{=}x_0{-}\{a\}$. Increase of counterfactual observations at an EV level rotates populations in the hyperbolic plane across that level's hyperbole, which led to an interpretation of hyperbolic angles as growth progression with non-zero bandwidth, Fig.\ref{fig-intro}(b). This interpretation also points to an alternative expression for exponential growth as a rotation $\gamma$ with period $\frac{m}{2}$, Eq.(\ref{eq-cosh2}). Hyperbolic relations appear in (heterogeneous) systems where time-to-EV is long, Fig.\ref{fig-intro}(b, upper-right). \subsection{Related Models.} Exponential growth with limited capacity, described by sigmoid curves, are common models for growth across disciplines. A sigmoid is simply a rescaled $\tanh$ function\cite{LeCun:aa}, which is central here (\textit{Sect. Heterogeneous Selection}, see also for the relation to Power-Laws). In such models, capacity is exogeneous and unknown, while here it is an endogenous statistical limit $\omega$. The human population, as well as past isolated populations, have hyperbolic forms\cite{Banks:1994aa}. These are the global 'ends' of the nested spatial process proposed, with local populations expected to follow exponential-binomial growth. Brownian growth in changing environments\cite{Taylor:1922aa,BRETHERTON:1999aa} follows populations' $e$-fold time (i.e., delay to derange). We formulated this as growth with unitary bandwidth, driven by randomness exclusively, and without a binomial balancing component. Hyperbolae are commonly assumed forms for demand-supply relationships, and starting-points of several Economical theories\cite{Humphrey:1996aa}. The model justifies multiple empirical observations in the Economic Complexity literature, left unexplained by previous models, such as the nested, and triangular-matrix, distribution of occupations \cite{Leontief:1965aa,SAAVEDRA:2009aa,Bustos:2012aa,Balland:2020aa}, and multi-scale fitness periodicity across locations \cite{Ribeiro:2021aa}. All previous models make it difficult to model population diversity, which the current has as starting-point. From their formulation, it is difficult to understand what population structures they create \cite{Allen:2017aa}, and, as consequence, the long-term effects of their proposed parameters. \section{Results} \begin{figure} \thisfloatpagestyle{empty} \centering \includegraphics[width=0.75\linewidth]{figs/res1-43.pdf}\\ \caption{\textbf{(a)} $\sinh$ and $\cosh$ functions, \textbf{(b)} increasing spatial-levels starting at two example locations (national and city-levels), same-location pairs share external variation, we consider economic changes for ${\sim}60K$ locations, under increasing scales, and the resulting population overlap and difference (correlation) patterns, finest spatial-level for New-York City (1880, right), \textbf{(c)} occupation frequency ranks vs. location across 4 example scales, each curve is one occupation, \textbf{(d)} enumerated Latin-Squares histograms for Massachusetts and New York, the latter has a square with almost all occupations, \textbf{(e)} periodogram of $cosh(100){+}sinh(100)$, $\sinh(100)$ and $\cosh(100)$, \textbf{(f)} empirical per-occupation periodogram and frequency-ranked series in (c), \textbf{(g)} occupation auto-correlation vs. spatial-level in 1880, economically non-integrated locations have linear correlations, integrated locations have catenaries (free-hanging rope), with given length, for each occupation, $y{=}1.0$ indicate complete correlation with the local level, probability distribution of their slack (red, sidepanel) indicate a fixed $\cosh$ increase per factor at $0.81$ (red horiz. line), across all occupations and locations, Eq.(\ref{eq-cosh3}), \textbf{(h)} standardized catenary across \textit{all} years, boxplots (red, sidepanel) show slack invariance for all occupations, locations and years, and constant ratio between $\sinh$ and $\cosh$ growth, $m\times(1-\frac{1}{e})$ (red vert. line) is a fixed point in binomial-exponential (EV-CF) to exponential (EV) rate transitions.}\label{fig-res1} \end{figure} Data used encompasses microdata of American decennial censuses from 1840 to 1940, and approximately 65 billion individual-level records. This non-aggregate data allows us to calculate pairwise factor differences for all individuals living in the Continental US. This, in turn, allow us to assemble squares across thousands of increasing spatial-levels. The time range corresponds to the highly tempestuous decades of American urbanization, incited by rapid industrial growth and immigration into cities. In 1840, only 10\% of the American population was urban. By 1940, it already neared 60\%. The data provides a unique view into the relationship among urban growth, spatial organization, and the incorporation of new industries and populations into cities. We consider economic and demographic changes as we go from the individual, or household, spatial-level all the way to the national, throughout these years. We create increasing samples, containing sample units at arithmetically increasing levels, $s_{t+1}{=}s_t{+}\Delta s$ (starting from the local $s_0$). We repeat this for approximately 60K American locations, $x_0$. Fig.\ref{fig-res1}(b) illustrates this process. It shows two locations in New York city. At the city level, the two locations share a large amount of external variation (i.e., economic and demographic variations across the rest of the country). This transversal captures patterns of difference and overlaps, for all $x_0$, as we increase scale. Economic distribution across space can be described by the primary occupation and industry of each census individual. We discuss demographic (non-economic) variables in the Supplementary Material. Fig.\ref{fig-res1}(c) illustrates empirical frequency for all occupations (each a curve) at 4 different spatial-levels, going from the local to the state level in Massachusetts (MA) and New York (NY), 1880. They were the country's economic centers until the beginning of the 19th century. The distribution has the familiar shape of a wave that moves to the left. New York reaches a stationary shape at a lower level $s_{sq}$ (2nd upper panel, 0.6 lat-lon distance). We demonstrate these correspond to levels where squares are completed across factors. All squares in a location can be enumerated through an expensive computational procedure\cite{ribeiro-ev}. Histograms are shown in Fig.\ref{fig-res1}(d), where each color correspond to one of $220$ occupation classifications. We see NY has a spatial square that extends to almost all occupations, while MA has missing occupations (horizontal gaps) in comparison. \subsubsection{The Hanging-Rope Model of Unbiased Growth} The Catenary is a curve with long scientific history, being first formulated by Galileo Galilei. Unlike circles and geodesics, they are sums of exponentials. They provide a convenient way to visualize the previous model, since their equation in $(x,y)$ Cartesian coordinates is $y = h \cosh \left(\frac{x}{h}\right)$, and length $h\sinh(\frac{x}{h})$. They describe a free-hanging rope, whose 'slack' $h$ is the difference in height, $y$, between its two hanging points\cite{Cella:1999aa}. Fig.\ref{fig-res1}(a,e) depicts general shapes for functions $\cosh(n)$ and $\sinh(n)$, and for the spectrum of $\cosh(n) + \sinh(n)$. Fig.\ref{fig-res1}(f) illustrates the \textit{empirical} spectrum of curves in Fig.\ref{fig-res1}(c). Taking square sizes $m$ to be temporal or spatial coordinates leads to specific temporal or spatial correlation patterns\cite{ribeiro-ev} across scales. Fig.\ref{fig-res1}(g) shows sample Autocovariance Function (ACF) across 5000 spatial-levels from the local to the national level (as those illustrated in Fig.\ref{fig-res1}(c)). It demonstrates that the auto-correlation of each occupation, as we increase spatial-levels, trace catenaries. The horizontal line $y= 1.0$, of unitary correlation, is associated with the limit $F_{m,n}=0$ where, despite the increasing scale, there are no added population differences. Each catenary is a set of points with constant ratio $C_m/F_{m,n}$, which is \textbf{the defining property of squares}, Eq.(\ref{eq-pythagoras-1}). Fig.\ref{fig-res1}(g) illustrates 4 typical cases among states: rural (Maryland, similar are Rhode Island, Louisiana, Arizona, Idaho, Wyoming, etc.), rural and complex (Iowa, Ohio, Wisconsin, Colorado, etc.), urbanizing and complex (Philadelphia, Massachusetts, Indiana, Michigan, New Jersey, etc.), and metropolitan (New York). Plots for all other states, and for other variables, are available in the Supplementary Material. The first group have linear decreases in correlation, as expected in non-interdependent systems. From 1840, the USA economy and cities become increasingly interdependent. After 1900, no longer any state had such linear correlation signatures. Periodic and linear (zig-zag) correlations, with period $m/2$, are related to non-increasing EV, Fig.\ref{fig-intro}(b). Purely periodic, without growth, and exponential correlations correspond to catenaries with $h=0$ (where a system returns to its original state after a lag). Standardizing catenaries\cite{Cella:1999aa} make $h$ indicate relative growth rate, $h=\cosh(m)-\cosh(0)$. Fig.\ref{fig-res1}(h) shows standardized catenaries for all years and locations. It indicates that $\cosh$ per factor remains constant across a wide range of levels, up to $s_{sq}$, and starting at the local. This was anticipated by Eq.(\ref{eq-cosh3}). The rate up to $s_{sq}$ is $0.81\%$ of correlation. Box-plot for $h$, across all levels, years, occupations, and locations, are shown in Fig.\ref{fig-res1}(h, sidepanel, red). For all spatial-levels below $s_{sq}$, factors $a$ and $\overline{a}$ remain balanced, with binary-exponential rates (i.e., hyperbolic functions with period $m/2$). Levels above $s_{sq}$ reverse to exponential growth. We called this a transition between EV and EV-CF growth. This is indicated in plots by the dislocation of the catenary center, after $s_{sq}$, from $m/2$ to $m/e$. This is most apparent in urbanizing locations (Philadelphia and New York). Estimated levels $s_{sq}$ for all states are shown in Fig.\ref{fig-res2}(d). New York is the only state, at the studied period, with 2-level squares. Catenaries for the lower square are shown in Fig.\ref{fig-res1}(h, upright-panel), and levels are illustrated cartographically in Fig.\ref{fig-res2}(b). The two squares' factors are disjoint (gray, lower factors taking exponential rates in higher). American states had then different work forces, economic characteristics, and regional distributions. While catenary lengths are different across occupations and locations, Fig.\ref{fig-res1}(g), their slack remains invariant across all occupations, locations and years, Fig.\ref{fig-res1}(h). \subsubsection{Heterogeneous Selection} \begin{figure} \centering \includegraphics[width=0.75\linewidth]{figs/res2-63.pdf}\\ \caption{\textbf{(a)} $\coth$ and $\tanh$ functions, colored arrows illustrate square factor frequency increases with scale, $a$ (red) is the location's most frequent factor, $b,c,d, ...$ are most-frequent factors in other locations, \textbf{(b)} New York (NY) state population density (left), NY has squares at two levels $s_{sq}$ after 1910, at $0.018$ and $0.65$ lat-lon distance (red circles), \textbf{(c)} schematic depiction of frequency rank vs. spatial-scale plots in (g), area between min. (green) and max. (red) ranks across all locations indicate square size (gray), \textbf{(d)} $s_{sq}$ (spatial-level of first square) for all states and years, levels $s_{sq}$ become less random, and more similar, with increasing economic integration, \textbf{(e)} BIC model likelihood ratio of $\coth$ over a Zipf model, Zipf uses only one (frequency-based) permutation, it becomes increasingly inaccurate as locations become more complex (and squares larger), \textbf{(f)} accuracy of state-of-the-art predictors vs. spatial-level, $s_{sq}$ level is diagonal (dashed), NY (red) gains little from external data, as it already encompasses large amounts of variation (bandwidth), other locations gain significantly from others' data as they have \textbf{incomplete squares}, \textbf{(g)} max. (red) and min. (green) frequency ranks across locations, each curve is a different spatial-scale, blue curves indicate square size, which follows a $\tanh$ function, $(m/2,m/e)$ inflection (red vert. line), \textbf{(h)} $\coth$ model, as illustrated in (a), with empirical data.}\label{fig-res2} \end{figure} Zipf's law was originally formulated to describe word frequency in corpora. It started much of the recent scientific interest in Power-laws, with famous explanations such as the principle-of-least-effort and preferential-attachment \cite{Tria:2014aa,Adamic:2011aa,Verbavatz:2020aa}. It is the central model for city size distribution \cite{Gabaix:1999aa,Verbavatz:2020aa}. The law is based on a frequency ranking of the studied factors, and thus, on only one of all their permutations. It is, here, associated with a homogeneous, or 'winner-takes-all', conception of selection. Fig.\ref{fig-res2}(a) depicts general shapes for curves $\tanh(n)$ and $\coth(n)$. Fig.\ref{fig-res2}(g) shows occupations' frequency ranks across locations for increasing spatial-levels. Each curve is one level. An occupation's minimum rank across all locations is denoted $r_{0}$ (green), and its maximum rank $r_{\omega}$ (red). The maximum-frequency rankings (red) are closely related (\textit{Methods}) to Zipf's frequency rankings and the Pareto distribution, as the three are Power-laws. With a homogeneous selection assumption, we expect one highest-rank industry ('winner') across locations, and thus $r_{\omega}-r_{0} = 1$. What we observe, however, is that factors are ranked in constant-sized ranges, as visualized by squares. Each occupation is the highest ranked in \emph{some} location, the second in other, etc. These rankings define an arithmetic series $-$ $r_{0}, r_{0}+1, r_{0}+2, ..., r_{\omega}$ $-$ for each location. The series has mean $\bar{r}=\frac{r_0 + r_\omega}{2}$, which is also shown (blue). The previous model predicts that $r_{\omega}-r_{0}$ is constant, and reflect the bandwidth $\omega = \tanh(n)^{-1}$. Fig.\ref{fig-res2}(g) shows that empirical rankings have a fixed $r_{\omega}-r_{0}$, with increasing minimum $r_{0}$ and fixed point in $(m/2,m/e)$. Squares correspond to the band indicated in Fig.\ref{fig-res2}(c, gray). The square rotates around $(m/e, m/2)$ by some angle $\theta_1 \approx \arctan(r_{\omega}/r_{0})$. A closer examination of both branches (red and green) reveals they correspond to the positive and negative sections of the $\coth(n) = 1/ \tanh(n)$ function, Fig.\ref{fig-res2}(h,a). Imagine the following process: pick a location $x_0$, and its most and least-frequent factors (i.e., with rank $1$ and $m$). Label them, respectively, $a$ and $z_0$. Balance $z_0$ to match $a$'s frequency. Move one spatial-level up, pick a second least-frequent factor (label it $z_1$), balance, and repeat. In a single square row, $n_a$ is the number of units in cell $a$, and $n_{\overline{a}}$ in all others cells (i.e., not $a$). The cost to balance each $z$ is thus $n_a$/$\omega$. So, we can write, for all locations $x_0$, and levels $s_0 \leq s \leq s_{sq}$, \begin{equation} \begin{split} n_a \times \frac{1}{\omega}- n_{z \in \overline{a}} &= 0,\\ n_a - n_{z \in \overline{a}} \times \coth(n) &= 0,\\ \end{split} \end{equation} which implies $\sum_{i=0}^{sq} n_{z_i} = n_{\overline{a}}$, and $ n_a = n_{\overline{a}}$. Observed min. and max. ranks take this shape across spatial-levels, Fig.\ref{fig-res2}(g,h). The $coth$ function separates, by sign, each location's balancing and growth phases, and reveals the order in which squares are completed in real systems, Fig.\ref{fig-res2}(a). This is illustrated as one hyperbolic rotation, with subsequent square derangements leading to others. This reflects the spatial transversal used (bottom-up), where, until level $s_{sq}$, each location corresponds to a square row. The process also constitutes a change of perspective, from selection as winner-takes-all processes to $\omega$-winners-take-all (driven by changing, but shared and stationary, external conditions). Methodologically, this suggests fitting a $\coth$ function to observed frequency ranks. A Zipf- distribution can be fit by Power-law or Pareto distribution regressions. We show in the Supplemental Material that the Pareto distribution can be used to reproduce, with alternative methods, the results in Fig.\ref{fig-res1}(g,h). The $81\%{-}19\%$ split is apparent in the previous plots, as the ratio between positive and negative $\coth$ branches' angles, Fig.\ref{fig-res2}(c). Bandwidth increases imply increasingly different min. and max-frequency permutations. This predicts that Zipf-Pareto regressions will become, as cities become more heterogeneous, increasingly inaccurate (compared to $\coth$). This is illustrated in Fig.\ref{fig-res2}(e), which shows increase of up to 18 times fit likelihood favoring the $\coth$ model throughout the studied period, according to a Bayesian Information Criterion (\textit{Methods}). What impact does complete squares have in their populations statistically (in respect to the EV and CF of effects)? This has been formulated theoretically, and demonstrated practically in simulated, cohort, experimental, economic, and genetic data \cite{ribeiro-ev,Ribeiro:2021aa,ribeiro2021experimentaldesign}. Fig.\ref{fig-res2}(f) demonstrates a further result, using census microdata, with an Accuracy vs. Spatial-level plot. It shows the maximum accuracy of 24 state-of-the-art supervised algorithms predicting whether a given occupation will grow, or not, in a location, as we use data from increasing spatial-levels (starting at the local and reaching all national data). According to Fig.\ref{fig-res1}(h), spatial-level $s_{sq}$ concentrates around an $81\%$ oversample for a local subset of occupations, across locations. According to Fig.\ref{fig-res2}(d), these levels become increasingly similar with time, across locations. In Fig.\ref{fig-res2}(f), $s_{sq}$ is mapped to the diagonal (dashed). Each state is one curve. Boostrap accuracy variation bands (across states' locations) are shown for the two most accurate states, New York (red) and Illinois (green). We observe that New York gains little from external data (above $s_{sq}$) as it already contains, within its boundaries, high levels of variation. Homogeneous locations, in contrast, have incomplete squares, and observed effects are susceptible to external and unobserved variation. This also implies that, without unobservables, ${\sim}81\%$ of the sample is sufficient for prediction. The impact of unobservables is formulated in \cite{ribeiro-ev}. This demonstrates an information asymmetry among locations (where the former is more useful to the latter than vice-versa). Network and Economic Development studies often describe New York as an early 'information hub' or 'sandbox for innovation'. The previous substantiate, statistically, these descriptions. \section{Conclusion} The challenge for any adaptive system in a complex environment is how to organize its under-control variation in face of its external. There is a cooperative dimension to this problem, where systems with common external variation (e.g., that are in the same location) can increase both the external validity and unbiasedness of their strategic choices by coordination. Each collected square increases, simultaneously, the external validity of $\omega$, fully unconfounded, populations. The set of all squares is related both to an optimal estimator in Theoretical Statistics and a solution in Cooperative Game-Theory. It is, however, not only this asymptotic state that is optimal, but the way there (i.e., the growth process), given its limits. Throughout growth, $\omega$ populations remain fully unconfounded, with effects increasingly externally valid. Exponential growth and hyperbolic functions offered a natural implementation and visualization for these alternative growth patterns. Increase in external validity, for $\omega = 1$, requires exponential growth. Increase in unconfoundness requires, however, Fibonaccian, with a half-golden growth ratio. The latter increases in 81\% the required population size for each individual population, and should be a requirement of large selection systems. The consequent 80-20 split is employed everyday across real-word systems, and in Machine Learning practice. We demonstrated not only functional-form evidence for the model, as typical\cite{Gabaix:1999aa,Verbavatz:2020aa}, but also enumerative, combinatorial, and for its 3 predicted growth rates. Most uniquely, we connected growth to the statistical environment (biases, predictability and explainability) growth processes create for their populations. These contributions predicted, and confirmed, Golden rates for city growth, and offered an explanation for the Pareto principle. \section*{References}
{'timestamp': '2022-03-16T01:03:46', 'yymm': '2202', 'arxiv_id': '2202.13961', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13961'}
arxiv
\section{Introduction} Querying a database with semi-structured natural language (e.g., in JSON format) has many real-world applications~\citep{arora2013modeling, mongodbcouchdb}. One particular application that we are interested in is \emph{\textbf{Place of Interest (POI) Match}}, which is an active product where the user input is a paper bill image and the desired output is a database entry that corresponds to the POI where the financial transaction is deemed to have taken place. Most commercial receipts have place information, and thus the receipt and POI matching can be done by extracting the information from the receipt image and querying the POI database. This can be done in steps as follows: (1) An optical character recognition (OCR) is first applied to extract text and its geometric location from the receipt image. (2) A document parsing (information extraction) process is applied to determine which pre-defined category (e.g., store name and store address) the obtained text belongs to (see the details in Figure~\ref{fig:ocr_demo}). (3) Finally, the grounding process uses the extracted information as a query to the POI database, i.e., find the corresponding store in the database. We present the whole end-to-end pipeline for \emph{POI Match} in Figure~\ref{fig:teaser}. This paper focuses on the \emph{grounding} stage of the pipeline, or more generally, the problem of grounding a semi-structured query on document-oriented databases, and we use \emph{POI Match} as the primary testbed for evaluating our solution to the problem. \footnotetext{\url{https://clova.ai/ocr}} One baseline approach for the grounding module (that has been in service in our product for the last few years) is to build a rule-based system with document-oriented databases~\citep{mongodb,couchdb}. In the system, querying functions implemented in the databases are used to find the store, e.g., regular expression-based search algorithms~\citep{10.1145/1376616.1376706, lockard-etal-2019-openceres, nadig-etal-2020-database}. If multiple stores are retrieved by the function, the system can finalize the answer with predefined rules, e.g., return the most visited store. Although the idea is simple, it is difficult to make good rules to cover numerous user queries. However, in fact, such a heuristic rule-based approach is fundamentally limited as there are limitless exceptions in real-world environments. In practice, the problem becomes increasingly non-trivial when (1) the input image is of bad quality, so that the model fails to extract correct information (See the bottom of Figure~\ref{fig:ocr_demo} and (a, b, c) of Figure~\ref{fig:teaser}), or (2) the information in the receipt does not exactly match the corresponding database entry, e.g., missing value or outdated information (See (d) of Figure~\ref{fig:teaser}). Furthermore, the size of a database is often in the order of millions or more (for instance, our database for \emph{POI Match} has approximately six million entries) and many database entries include similar values, such as the name of franchises, so that it is difficult to differentiate. Hence, for robust grounding in a real-world scenario, the model should consider multiple fields simultaneously and should handle both semantic and lexical similarities among the data to distinguish similar entries. Also, the model should deal with the issues of missing values and noises of the data. Because of these difficulties, our current rule-based model has a more than 30\% failure rate for all incoming queries. To address these issues, we combine an idea of embedding-based retrieval~\citep{karpukhin-etal-2020-dense,fairembed} into database querying. In our system, both queries and database entries are represented by vectors. Given a query, the corresponding database entries are retrieved by searching nearest neighbors in the vector space. To make a good system for grounding, we first introduce a framework for grounding that consists of several replaceable modules. And then, we conduct extensive experiments to assess the contribution of individual modules more rigorously and find the best module combination over the model architectures. The proposed model successfully alleviates the issues of missing values and noises of the data, and significantly outperforms the rule-based baseline model by more than 8\% point of top-1 matching accuracy in \emph{POI Match} (this corresponds to approximately 2 million user queries per month). While our work primarily focuses on one particular application (\emph{POI Match}), we believe that our findings can be easily extended to other real applications that rely on semi-structured queries on databases. \section{Background} \subsection{OCR and Parsing} Information extraction (IE) on semi-structured document images is a core step towards automated document processing. In general, document IE systems consist of two stages: OCR and Parsing. \subsubsection{OCR} The OCR process consists of two sub-steps: detection and recognition. First, in the detection procedure, all text regions in the given image are predicted~\citep{baek2019craft}. The recognition module receives the detected image patch as its input and extracts all texts in the patch~\citep{baek2019STRcomparisons}. \subsubsection{Post-OCR Parsing} The parsing task can be interpreted as a named entity recognition (NER) task that maps texts to predefined categories based on the recognized text and location information. The task aims to extract the information in a structured form (See Figure 1)~\citep{hwang2019postocr,hwang-etal-2021-spatial}. However, the inference cannot always be accurate, especially in a real application environment. There have been various additional studies on how to correct the recognized information, which is still often inefficient and error-prone in practice~\citep{post_ocr, hwang-etal-2021-cost}. \subsection{Database Querying} In document-oriented databases, the data is stored in the form of semi-structured data that consists of several key-value pairs, e.g., JSON or XML. Database querying is done by retrieving corresponding database entries that satisfy the input conditions. For instance, in MongoDB~\citep{mongodb}, the database entries whose the value of ``color'' is ``gold'' is retrieved by using the input query \texttt{find({color:"gold"})}. Querying with multiple conditions is also supported, e.g., \texttt{find({color:"gold",type:"necklace"})}. Database querying often fails in real-world applications since both queries and database entries are noisy in most practical scenarios, e.g., misspellings in a query or missing values in database entries. A common solution to this problem is using a text-based search engine (e.g., Apache Lucene)~\citep{elasticsearch, couchdb}. However, the performances are limited as the core idea is based on simple string distance calculation algorithms which are not good at capturing semantic similarities among the data~\citep{robertson2009probabilistic, elasticsearch}. \subsection{Embedding-based Retrieval} To retrieve textual data such as words, sentences, or documents, many modern NLP applications convert the data into vector representations, i.e., embeddings~\citep{mikolov-etal-2013-linguistic,devlin-etal-2019-bert,karpukhin-etal-2020-dense}. Once the data is embedded in vector space, retrieval can be done efficiently by calculating similarities among the vectors. For instance, if the data is embedded into an inner-product space, the retrieval can be done with maximum inner product search algorithms~\citep{pmlr-v89-ding19a,tan-etal-2019-efficient, faiss}. The embeddings are expected to hold characteristics, properties, or even semantics of the data so that retrieval targets can be found simply by calculating the distances in the vector space. To obtain such good embeddings, a range of representation learning methods has been studied~\citep{mikolov-etal-2013-linguistic,kim-2014-convolutional,bojanowski-etal-2017-enriching} and most of the modern methods utilize BERT-based models to embed the data~\citep{devlin-etal-2019-bert,karpukhin-etal-2020-dense}. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{figure2_v3.pdf} \caption{\textbf{An overview of semi-structured data embedding process.} Values of valid fields are concatenated and passed to a BERT-based model to obtain the vector representation.} % \label{fig:embedding_process} \end{figure} \section{Grounding} In this section, we aim to introduce our model for grounding. Before introducing the model, we formally define \emph{grounding} and provide some preliminaries. \paragraph{Problem Definition.} In this paper, we are interested in the task of finding a corresponding database entry from a large-scale document-oriented database, given a \textbf{noisy} semi-structured query (e.g., JSON). % We denote this task as \emph{grounding}. In the task, both queries and database entries are semi-structured data that consists of several key-value pairs. We are given $n$ queries ($\in\mathcal{Q}$), $m$ database entries ($\in\mathcal{D}$), and their associations which can be expressed as a matrix $(a_{i\hat{j}}) \in \mathbb{R}^{n\times m}$, where the value of $a_{i\hat{j}}$ represents the strength of the association between $i$-th query and $\hat{j}$-th database entry. For instance, we may use the number of link (edge) between $i$-th query and $\hat{j}$-th database entry in the trainset as the association strength $a_{i\hat{j}}$. The model is trained to predict the given association strengths $(a_{i\hat{j}})$. In a test phase, for an input user query, the database entry with high predicted association strength is considered as the matching target. We assume the target is a single database entry but it can be a set of database entries if the database is noised with duplicated entries (this is not rare in real application environments). \subsection{Grounding Model} We bring an idea of embedding-based retrieval into database querying. In the proposed model, both queries and database entries are represented by dense vectors (i.e., embeddings). Under this setting, grounding (database querying) becomes finding a close corresponding database entry vector for a given query vector. The entire model architecture is based on a simple Siamese neural network~\citep{siamesenn, reimers-gurevych-2019-sentence,gillick-etal-2019-learning,wips,karpukhin-etal-2020-dense}. Two neural networks (i.e., backbones) learn nonlinear mapping functions to learn the embeddings of queries and database entries that are used for database querying. The querying is done by calculating similarity scores among the obtained input query vector and the embeddings of database entries. \subsubsection{Backbones} We use BERT-based models~\citep{devlin-etal-2019-bert,conneau-etal-2020-unsupervised} following recent trends in NLP. % To apply BERT-based models on document-oriented data, the first step is to vectorize the input data as the model assumes continuous data as inputs. To prepare input vectors, we convert the document-oriented data into a sequence of tokens (See Figure~\ref{fig:embedding_process}). Each token is converted to a vector representation through a look-up operation over a learnable embedding matrix~\citep{devlin-etal-2019-bert}. \subsubsection{Input feature selection} There are several choices to be made to make the input sequence; (1) what fields to consider, (2) how to concatenate the multiple field information. % In our pipeline, a set of valid fields is first defined and only the values of the valid fields are concatenated to make a sequence (See Figure~\ref{fig:embedding_process}). In BERT-based models, a separator token \texttt{[SEP]} is used for the concatenation of different fields in general~\citep{devlin-etal-2019-bert,cohan-etal-2019-pretrained,karpukhin-etal-2020-dense}. However, in the real-world data, the number of fields is often more than two and the data has lots of missing values (i.e., null values). In our preliminary experiments, we observed that a naive concatenation of multiple fields degrades the performance of the system. To resolve this issue, we introduce two additional special tokens (\texttt{[MASK]}$_{\ast}$ and \texttt{[SEP]}$_{\ast}$) per each field $\ast$. The token \texttt{[MASK]}$_{\ast}$ is used when the value of the field $\ast$ is missing. The token \texttt{[SEP]}$_{\ast}$ is used for separating the value of $\ast$ with other values. See Figure~\ref{fig:embedding_process} for more details. \subsubsection{Similarity functions} To calculate the association strength $a_{i, \hat{j}}$ between queries and database entries, the model learns $\boldsymbol{f}_{\boldsymbol\theta}:\mathcal{Q}\mapsto\mathcal{Y}$ and $\boldsymbol{g}_{\boldsymbol\vartheta}:\mathcal{D}\mapsto\mathcal{Y}$, where $\mathcal{Y} \in \mathbb{R}^{K}$ is a set where embeddings take a value with some dimensionality $K\in\mathbb{N}$. The generated embeddings of query $\boldsymbol{y}_{i} := \boldsymbol{f}_{\boldsymbol\theta}(\boldsymbol q_i)$ and database entry $\boldsymbol{y}_{\hat{j}} := \boldsymbol{g}_{\boldsymbol\vartheta}(\boldsymbol d_{\hat{j}})$ capture the association strength by $s(\boldsymbol y_{i}, \boldsymbol y_{\hat{j}}) \propto a_{i, \hat{j}}$, where $s:\mathcal{Y}\times\mathcal{Y}\mapsto\mathbb{R}$ is a similarity function, such as, inner product similarity (IPS) $\langle\boldsymbol y_{i}, \boldsymbol y_{\hat{j}}\rangle$ or negative squared distance (NSD) $-||\boldsymbol y_{i} - \boldsymbol y_{\hat{j}}||^2_2$. \subsection{Model Training} Given the training data $\{a_{i,\hat j}\}$, the model parameters $\{\boldsymbol\theta, \boldsymbol\vartheta\}$ are learned by maximizing $\sum_{1\le i\le n, 1\le \hat{j}\le m} a_{i, \hat{j}} \log P(\hat{j}|i)$, where $P(\hat{j}|i)$ is modeled as, \begin{equation} \frac{\exp(s(\boldsymbol y_{i}, \boldsymbol y_{\hat{j}}))}{\sum_{1\le \hat{k}\le m}\exp(s(\boldsymbol y_{i}, \boldsymbol y_{\hat{k}}))}. \end{equation} The summation in the denominator makes training difficult, especially when $m$ is large, which is often the case in real-world environments. The problem can be circumvented by using \textit{negative sampling}, leading to a modification of the above objective as follows, \begin{equation} \frac{\exp(s(\boldsymbol y_{i}, \boldsymbol y_{\hat{j}}))}{\sum_{\hat{k}\sim P_\text{neg}}\exp(s(\boldsymbol y_{i}, \boldsymbol y_{\hat{k}}))}, \end{equation} where $P_{\text{neg}}$ is a distribution for negative sampling, such as, uniform, empirical frequency, etc. For efficient model training, we train the models with mini-batch gradient descent and use other samples in a mini-batch as negative samples~\cite{gillick-etal-2019-learning,karpukhin-etal-2020-dense}. \subsection{Implementation} We implement a library \texttt{grounder} that includes all fundamental functionality for training and deploying a grounding system. \texttt{grounder} is implemented in PyTorch~\citep{pytorch} and built upon two public projects. To use a range of BERT-based models, we use \texttt{transformers}~\citep{wolf-etal-2020-transformers} developed by huggingface. For an efficient retrieval of nearest neighbors, \texttt{faiss}~\citep{faiss} developed by Facebook AI is used. % Our implementation will be publicly available on GitHub\footnote{\url{https://github.com/clovaai}}. \section{Experiments} In experiments, we study two architectures of backbone ({MBERT} and {XLMR}), two similarity functions ({IPS} and {NSD}), two options in a separator token ({Single} and {Multi}), and three options in masking missing values ({None}, {Single} and {Multi}). All possible grounding module combinations (2×2×2×3= 24 in total) are evaluated to find the best module combination for our application \emph{POI Match}. We also assess the efficacy of each module, and we believe that our findings in the experiments can be easily extended to other real-world applications that rely on grounding. \paragraph{Common Settings.} Given a receipt image and a database of stores, our task is to find a corresponding store in the database that matches the image. We evaluate all models with top-1 matching accuracy. In experiments, we use 1 million receipt images and a database that contains approximately 6 million POI information. Each query has 4 valid fields, where each field corresponds to the name, telephone number, address, and business number of the store respectively. Each database entry has 4 valid fields, where each field corresponds to the name, telephone number, address, and street name (i.e., another type of address) of the store respectively. There are many missing values in the data, for example, 21\% of the database entries have null values on the telephone number field and 17\% on the street name field respectively. Each receipt image is linked to a database entry with the help of our rule-based model that has been in service in our application; the model is first applied to the image to find a corresponding database entry, and the links are refined by a human annotator. The application is deployed in South Korea and the main language of the data is Korean. \subsection{Comparison Models} \subsubsection{Baseline} To assess the efficacy of our proposal, we use our conventional rule-based model as a baseline model. The model queries a store with regular expression-based searching algorithms on specific fields, such as \textit{telephone number} or \textit{address}. The model may not be able to return a single candidate, for example, franchise stores tend to have the same values in some fields, e.g., \textit{telephone number}, so matching tends to be more difficult. If multiple entries are returned, predefined rules are applied for re-ranking. For example, the most visited store is returned based on the history. These heuristic rules are hard to cope with the various exceptions in real-world environments. \subsubsection{Module Combinations} As explained in Section 3.1, we build a grounding model by combining several replaceable modules as explained below. \paragraph{Backbones.} To embed the multilingual data, we test two BERT-based models; Multilingual BERT (MBERT)~\citep{devlin-etal-2019-bert, pires-etal-2019-multilingual} and XLM-Roberta (XLMR)~\citep{conneau-etal-2020-unsupervised}. \paragraph{Similarity functions.} To score the similarities between the data (i.e., JSON objects), two similarity functions are tested; inner-product similarity (IPS) $\langle\boldsymbol y_{i}, \boldsymbol y_{\hat{j}}\rangle$ and negative squared distance (NSD) $-||\boldsymbol y_{i} - \boldsymbol y_{\hat{j}}||^2_2$. % \paragraph{Separator token for field concatenation.} In our pipeline, each JSON object is converted into a sequence of tokens. During the conversion, we simply concatenate all values in the valid fields separated by a single separator token between the values (Single)~\citep{devlin-etal-2019-bert,karpukhin-etal-2020-dense}. To emphasize the distinctions between values from different fields, we also tet multiple field-wise separator tokens (Multi). See Figure~\ref{fig:embedding_process} and Section 3.1 for more details. \begin{table}[t!] \centering \resizebox{\linewidth}{!}{ \begin{tabular}{ c c c c c } \toprule \textbf{Backbone} & \textbf{Sim.} & \textbf{Sep.} & \textbf{Mask.} & \textbf{Acc.} \\ \midrule MBERT & IPS & Single & None & 86.61 \\ MBERT & IPS & Single & Single & 87.45 \\ MBERT & IPS & Single & Multi & 85.38 \\ MBERT & IPS & Multi & None & 88.91 \\ MBERT & IPS & Multi & Single & 88.01 \\ MBERT & IPS & Multi & Multi & 88.15 \\ MBERT & NSD & Single & None & 85.61 \\ MBERT & NSD & Single & Single & 87.09 \\ MBERT & NSD & Single & Multi & 90.26 \\ MBERT & NSD & Multi & None & 90.85 \\ MBERT & NSD & Multi & Single & 90.73 \\ MBERT & NSD & Multi & Multi & \textbf{91.61} \\ % XLMR & IPS & Single & None & 87.36 \\ XLMR & IPS & Single & Single & 89.36 \\ XLMR & IPS & Single & Multi & 90.36 \\ XLMR & IPS & Multi & None & 90.14 \\ XLMR & IPS & Multi & Single & 89.36 \\ XLMR & IPS & Multi & Multi & 89.58 \\ XLMR & NSD & Single & None & 89.11 \\ XLMR & NSD & Single & Single & 91.05 \\ XLMR & NSD & Single & Multi & 90.94 \\ XLMR & NSD & Multi & None & 90.55 \\ XLMR & NSD & Multi & Single & 89.87 \\ XLMR & NSD & Multi & Multi & 89.81 \\ \bottomrule \end{tabular} } \caption{\textbf{Performances of all module combinations.} We run each module combination three times and average accuracies are reported in the table. There are considerable performance gaps among the module combinations (2×2×2×3=24 in total).} \label{tab:module_compare} \end{table} \paragraph{Masking token for missing values.} In \citet{devlin-etal-2019-bert}, a special mask token is used to train the model to capture the associations among input tokens. During the training, the input tokens are randomly replaced by the mask token and the model tries to recover the masked values from its neighbors. Inspired by this, we use the mask token to mitigate the negative ramifications of missing values in the data. When the value is missing, we use either a single masking token (Single) or multiple field-wise masking tokens (Multi) instead of leaving it as blank (None). See Figure~\ref{fig:embedding_process} and Section 3.1 for more details. \begin{figure}[t] \centering \includegraphics[width=\linewidth]{figure3_v3.pdf} \caption{\textbf{Module-wise comparative analysis.} We run each setting three times and average accuracies are reported.} \label{fig:module_compare} \end{figure} \subsection{Results and Analysis} We conduct extensive experiments to assess the effectiveness of each module and to find the optimal combination. % \begin{table}[t] \centering \begin{tabular}{l c} \toprule \textbf{Valid Fields} & \textbf{Acc.} \\ \midrule Store Name & 33.66 \\ + Address & 81.40 \\ + Telephone Number & 91.02 \\ + Business Number & \textbf{91.61} \\ \bottomrule \end{tabular} \caption{\textbf{Analysis on the number of valid fields.} The matching accuracy becomes higher as the number of valid fields grows.} \label{tab:valid_field_num} \end{table} \paragraph{Experiment 1 (Module Combinations).} We evaluate all module combinations (2×2×2×3= 24 in total). The results are shown in Table~\ref{tab:module_compare}. In this experiment, we split the 1M receipt images into test (10K) and train (the rest). We use the database entries (390K) that are associated with the 1M receipts. The models are trained to learn the associations between trainset receipts and database entries. And the trained models are used to predict unobserved associations from the test set receipts. The batch size is set to 32, the number of steps is 40K, and the learning rate is 2e-5. As can be seen in Table~\ref{tab:module_compare}, there are considerable performance gaps among the combinations ranging from 85.6 to 91.6. The best module combination is MBERT-NSD-Multi-Multi. To show the effect of each module more comprehensively, we plot the module-wise performances in Figure~\ref{fig:module_compare}. MBERT has a large performance variance, and the combination of MBERT and NSD seems to be effective. The result also shows that using multiple special tokens (Multi) is effective for mitigating the issues of multiple field concatenation as well as missing values in the data. \paragraph{Experiment 2 (Valid Field Selection).} We also investigate the effects of using multiple fields by changing the number of valid fields during the training. The results in Table~\ref{tab:valid_field_num} show the matching accuracy becomes higher as the number of valid fields grows. This highlights the importance of using multiple fields to differentiate similar entries in the database, leading to a performance improvement in grounding. \begin{table}[t] \centering \begin{tabular}{ l c } \toprule \textbf{Models} & \textbf{Acc.} \\ \midrule Baseline Model & 67.0 \\ Proposed (MBERT-NSD-Multi-Multi) & \textbf{75.3} \\ \bottomrule \end{tabular} \caption{\textbf{Matching accuracies of the daily queries from the real users in \emph{POI Match}.} The proposed matching algorithm outperforms the heavily engineered baseline method by 8\% point of top-1 matching accuracy.} \label{tab:comparison} \end{table} \paragraph{Experiment 3 (Results on \emph{POI Match}).} To find out how effective the proposed system is in our application environment, we evaluate the model on the daily queries from real users in \textit{POI Match}. We gathered 300 queries and manually annotated the correct database entries. To see the practical gains in the real application scenario, we use all database entries (approximately 6 million entries) in this experiment, that is, the model should distinctly distinguish numerous similar entries from the full database. We trained our model with a batch size of 64 for 80K steps. Table~\ref{tab:comparison} shows, the proposed matching model significantly outperforms the baseline model that is currently deployed by 8\% point of top-1 matching accuracy. This performance gap corresponds to approximately 2 million user queries per month. \section{Concluding Remarks and Future Work} In this paper, we propose a new type of grounding system for querying large-scale document-oriented databases with semi-structured natural language. The proposed system utilizes embedding-based retrieval to alleviate several practical concerns in the semi-structured query grounding problem. We examined the proposed system on our application \emph{POI Match} which aims to find the corresponding POI entry for a user input receipt image. Despite various OCR, Parsing, and DB noises, the proposed method successfully matches the receipt image with the corresponding DB entry. In our experiments, the proposed model significantly outperforms the heavily engineered baseline model that has been used in our product for the last few years while requiring much less development and maintenance cost. As future work, testing the proposed grounding pipeline on different applications or domains would help to get a general understanding of each module. Investigating the connections between some recent theoretical analyses on Siamese neural-network-based retrieval and our empirical results would also be interesting. We believe our findings in this work can easily be extended to other real-world applications that are dependent on a similar problem. \section*{Acknowledgements} The authors would like to thank anonymous reviewers for their insightful comments.
{'timestamp': '2022-03-01T02:57:15', 'yymm': '2202', 'arxiv_id': '2202.13959', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13959'}
arxiv
\section{Introduction} \label{sec:intro} {\bf \noindent Code-based cryptography.} Error correcting codes are well known to provide quantum resistant cryptographic primitives such as authentication protocols \cite{S93,HKLPP12}, signatures \cite{CFS01,DST19a} or encryption schemes such as McEliece \cite{M78}. These code-based cryptosystems were built to rely on the following hard problem: finding a close (or far away) codeword to a given word, a task called {\em decoding}. In the case of random linear codes of length $n$, which is the standard case, this problem can be expressed as follows. First, we are given a vector space $\code{C}$ ({\em i.e.} the code) of $\mathbb{F}_q^{n}$ generated by the rows of some random matrix $\vec{G}\in\mathbb{F}_q^{k\times n}$, namely: \begin{equation}\label{eq:def_code} \code{C} \stackrel{\textrm{def}}{=} \{\vec{m}\vec{G} \mid \vec{m} \in \mathbb{F}_q^k\}. \end{equation} The decoding problem corresponds, given $\vec{G}$ (in other words $\code{C}$) and some noisy codeword $\vec{m}\vec{G} + \vec{e}$ where the number of non-zero coordinates of $\vec{e}$ is equal to $t$ (its Hamming weight is $|\vec{e}| = t$), to find the error $\vec{e}$ or what amounts to the same, the original codeword $\vec{m}\vec{G}$. Usually this decoding problem is considered in the regime where the code rate $R \stackrel{\textrm{def}}{=} \frac{k}{n}$ is fixed, but there are also other interesting parameters for cryptographic applications. For instance, the Learning Parity with Noise problem ($\mathsf{LPN}${}) corresponds to the decoding problem where $n$ is the number of samples, $k$ the length of the secret while the error is sampled according to a Bernoulli distribution of fixed rate $t/n$. As the number of samples in $\mathsf{LPN}${} is unlimited, this problem actually corresponds to decoding a random code of rate arbitrarily close to $0$. \iftoggle{llncs}{}{While the security of many code-based cryptosystems relies on the hardness of the decoding problem, it can also be based on finding a ``short'' codeword for the Hamming metric (as in \cite{MTSB12} or in \cite{AHIKV17,BLVW19,YZWGL19} to build collision resistant hash functions). It turns out that decoding and finding short codewords are closely related. It has been shown in \cite{DRT21} (following the original quantum reduction of Regev in the lattice/$\mathsf{LWE}${} case \cite{R05}) that decoding some code $\code{C}$ is quantumly-harder than finding a short codeword in its dual $\code{C}^{\perp}$ (for the standard inner product in $\mathbb{F}_q^{n}$). A reduction from decoding to the problem of finding short codewords is also known but in an $\mathsf{LPN}${} context \cite{AHIKV17,BLVW19,YZWGL19}.} Despite the promising approach of McEliece, there are two drawbacks if one follows it to design a cryptosystem. First, the public data in McEliece is a representation of a code which has to look like random. Assuming this pseudo-randomness property, the security relies on the hardness of the decoding problem. In that case one needs to publish $\Omega(n^{2})$ bits but at the same time, best generic decoding algorithms have a complexity exponential in the number $t$ of errors to correct. Therefore, to reach a security level of $2^{\lambda}$, the public data are of order $\Theta(\lambda^{2})$ if $t = \Theta(n)$ or even worse of the order $\Theta(\lambda^{4})$ if $t = \Theta\left(\sqrt{n}\right)$. On the other hand, in McEliece-like cryptosystems, the owner of the secret key has to know an efficient decoding algorithm for the public code. It turns out that codes for which we know an efficient decoding algorithm are obtained via polynomial evaluations ({\em e.g.} Goppa codes) or short vectors ({\em e.g.} MDPC codes). Thus, the owner of the secret key has to hide the peculiar description of the code he publishes. It leads to the fact that in McEliece-like cryptosystems, the security also relies on the difficulty to distinguish the code that is made public from a random one. This is a second assumption to make in addition to the hardness of the decoding problem. \newline {\bf \noindent Alekhnovich cryptosystem.} In 2003, Alekhnovich \cite{A03} introduced a new approach to design an encryption scheme based on error correcting codes. Unlike McEliece cryptosystem, Alekhnovich truly relies on the hardness of decoding random codes. It starts from a random code $\code{C}$ and proceeds as follows: \begin{itemize} \item \textit{Key Generation.} Let $\vec{e}_{\mathsf{sk}}\in\F2^{n}$ of small Hamming weight. The public key is $(\code{C}, \vec{c} + \vec{e}_{\mathsf{sk}})$ where $\vec{c}\in \code{C}$ and the secret key is $\word{e}_{\mathsf{sk}}$. \vspace{\baselineskip} \item \textit{Encryption.} To encrypt one bit $\beta\in\{0, 1\}$ set: \begin{itemize} \item $\mathsf{Enc}(1) \stackrel{\textrm{def}}{=} \word{u}$ where $\word{u}\in \F2^{n}$ is a uniformly random vector. \item $\mathsf{Enc}(0) \stackrel{\textrm{def}}{=} \vec{c}^{\ast}+\vec{e}$ where $\vec{e}$ is of small Hamming weight and $\vec{c}^{\ast}$ lies in the dual of the code $\code{C}_{\mathsf{pub}}$ spanned by $\code{C}$ and $\vec{c}+\vec{e}_{\mathsf{sk}}$. \end{itemize} \vspace{\baselineskip} \item \textit{Decryption.} The decryption of $\mathsf{Enc}(\beta)$ is $\inner{\mathsf{Enc}(\beta), \vec{e}_{\mathsf{sk}}}$, where $\inner{\cdot,\cdot}$ is the usual inner product on $\F2^{n}$. \end{itemize} The correction of this procedure relies on the fact that \[ \inner{\mathsf{Enc}(0), \vec{e}_{\mathsf{sk}}} = \inner{\vec{c}^{\ast} + \vec{e}, \vec{e}_{\mathsf{sk}}} = \inner{\vec{e}, \vec{e}_{\mathsf{sk}}}, \] where we used that $\vec{e}_{\mathsf{sk}}\in \code{C}_{\mathsf{pub}}$ while $\vec{c}^{\ast}$ lies in its dual. Now, this inner product is equal to $0$ with overwhelming probability as $\vec{e}_{\mathsf{sk}}$ and $\vec{e}$ are of small Hamming weight. On the other hand, $\inner{\mathsf{Enc}(1), \vec{e}_{\mathsf{sk}}}$ is a uniformly random bit. Therefore, contrary to McEliece cryptosystem, the security of Alekhnovich scheme does not depend on hiding the description of a code: \begin{itemize}[label=\textbullet] \item \textit{Key security.} Recovering the private key from public data amounts to decoding the random code $\code{C}$\iftoggle{llncs}{.}{, or finding a short vector in the code spanned by $\code{C}$ and $\vec{c} + \vec{e}_{\mathsf{sk}}$.} \item \textit{Message security.} Recovering the plaintext from the ciphertext is tantamount to \textit{distinguishing} a noisy codeword from a uniformly random vector. \end{itemize} \noindent The message security relies on the \textit{decision} version of the decoding problem. Search and decision versions of the decoding problem are known to be computationally equivalent using Goldreich-Levin theorem \cite{FS96}. However, Alekhnovich cryptosystem suffers from major drawbacks: \begin{enumerate} \item Encrypting one bit amounts to sending $n$ bits; \item The public key size is quadratic in the length of ciphertexts. \end{enumerate} \noindent While the first issue can easily be addressed, the second flaw needs more work, and as is, Alekhnovich cryptosystem is not practical. However, the approach itself was a major breakthrough in code-based cryptography. It was inspired by the work of Ajtai and Dwork \cite{AD97} whose cryptosystem is based on solving hard lattice problems. The latter reference from Ajtai and Dwork is also the inspiration of Regev famous Learning With Errors ($\mathsf{LWE}${}) problem \cite{R05}, which is at the origin of an impressive line of work. As Alekhnovich cryptosystem, the original $\mathsf{LWE}${} cryptosystem was not practical either and, to address this issue, structured versions were proposed, for instance Polynomial-$\mathsf{LWE}${} \cite{SSTX09}, Ring--$\mathsf{LWE}${} \cite{LPR10}, Module--$\mathsf{LWE}${} \cite{LS15}. \newline {\bf \noindent Structured decoding problem.} In the same fashion, for code--based public key encryptions, it has been proposed to restrict to codes that can be represented more compactly to reduce the key sizes. In McEliece setting, the story begins in 2005 with the results of \cite{G05} that suggest to use $\ell$--quasi-cyclic codes, {\em i.e. } codes that are generated by a matrix $\vec{G}$ formed out of $\ell$ blocks: \begin{equation}\label{eq:qc-code} \mat{G} = \begin{pmatrix} \rot\left(\word{a}^{(1)}\right) & \cdots & \rot\left(\word{a}^{(\ell)}\right) \end{pmatrix}, \end{equation} each block being a circulant matrix, {\em i.e. } of the form \[ \rot(\word{a}) \stackrel{\textrm{def}}{=} \begin{pmatrix} a_{0} & a_{1} & \dots & \dots & a_{k-1} \\ a_{k-1} & a_{0} & \dots & \dots & a_{k-2} \\ \vdots & \ddots & \ddots & & \vdots \\ \vdots & & \ddots & \ddots & \vdots \\ a_{1} & a_{2} & \dots & a_{k-1} & a_{0} \end{pmatrix} \text{ with }\word{a} \in \mathbb{F}_q^{k}. \] The key point is that such codes have a large automorphism group $G$, and instead of publishing a whole basis, one can only publish a generating set for the $\mathbb{F}_q[G]$--module structure of the code. That is to say, a family of vectors whose orbit under the action of $G$ spans the code. For instance, in the case of quasi-cyclic codes (\ref{eq:qc-code}), one can publish only the first row of the $\ell$-circulant generator matrix. It can be argued that the quasi--cyclicity could be used to improve the speed-up of generic decoding, but the best known approach in the generic case uses DOOM \cite{S11} which allows to divide the complexity of decoding by at most $\sqrt{\#G}$, the latter complexity remaining exponential with the same exponent. Hence, one can keep the same security parameter, while the size of the public key can be divided by a factor $O(\#G)$. This idea leads to very efficient encryption schemes such as {\sc Bike}{} \cite{AABBBBDGGGMMPSTZ21}, in the McEliece fashion, or {\sc HQC}{} \cite{AABBBDGPZ21a} which is closer to Ring--$\mathsf{LWE}${}. Both proposals use 2-quasi-cyclic codes and have been selected to the third round of NIST competition as alternate candidates. Other structured variants of the decoding problem (referred to as Ring--$\mathsf{LPN}${}) were also proposed with applications to authentication \cite{HKLPP12} or secure MPC \cite{BCGIKS20}.\iftoggle{llncs}{ }{ Note that the idea to use codes equipped with a non trivial ring action has also been used in rank metric \cite{ABDGHRTZABBBO19,AABBBDGZCH19}.} In other words, the security of those cryptosystems now rely on some structured variant of the decoding problem. \newline {\bf \noindent A Polynomial representation.} It turns out that a convenient way of seeing $\ell$-quasi-cyclic codes, is to represent blocks of their generator matrix as elements of the quotient ring ${\mathbb{F}_q[X]}/{(X^{n}-1)}$, via the $\mathbb{F}_q$--isomorphism: \[ \map{\mathbb{F}_q^n}{\fract{\mathbb{F}_q[X]}{(X^{n}-1)}}{\word{a} \stackrel{\textrm{def}}{=} (a_{0}, \dots, a_{n-1})}{ \word{a}(X) \stackrel{\textrm{def}}{=} \displaystyle\sum_{i=0}^{n-1}a_{i}X^{i}.} \] A simple computation shows that the product of two elements of ${\mathbb{F}_q [X]}/{(X^{n}-1)}$ can be represented with the operator $\rot(\cdot)$: \[ \word{u}(X)\word{v}(X) \mod (X^{n}-1) = \word{u}\cdot\rot(\word{v}) = \word{v} \cdot \rot(\word{u}) = \word{v}(X) \word{u}(X) \mod (X^{n}-1). \] From now on, $\word{u}$ can denote either a vector of $\mathbb{F}_q^{n}$ or a polynomial in ${\mathbb{F}_q[X]}/{(X^{n}-1)}$, and the product of two elements $\word{u}\word{v}$ is defined as above. Consider an $\ell$-quasi-cyclic code with a generator matrix $\mat{G}$ in $\ell$-circulant form. Let $\word{s}\in\mathbb{F}_q^{n}$ be a secret word of the ambient space and let $\word{e}\in\mathbb{F}_q^{\ell n}$ be an error vector. Under the above map, the noisy codeword $\word{s}\mat{G} + \word{e}$ is represented by $\ell$ samples of the form $\word{s}\word{a}^{(j)} + \word{e}^{(j)} \in {\mathbb{F}_q[X]}/{(X^{n}-1)}$ and the decoding problem of $\ell$-circulant codes corresponds to recovering the secret $\word{s}$ given $\ell$ samples. This can be seen as a code analogue of the Ring--$\mathsf{LWE}${} problem, with access to a fixed number of samples $\ell$. The rate of the code is $\frac{1}{\ell}$, so increasing the number of samples corresponds to decode a code whose rate goes to $0$. A natural generalization would be to consider multiple rows of circulant blocks. In this situation, the generator matrix $\mat{G}$ is of the form \[ \mat{G} = \begin{pmatrix} \rot(\word{a}^{(1, 1)}) & \cdots & \rot(\word{a}^{(1,\ell)})\\ \vdots & & \vdots\\ \rot(\word{a}^{(m,1)}) & \cdots & \rot(\word{a}^{(m,\ell)})\\ \end{pmatrix} \] and a noisy codeword $\word{s}\mat{G} + \word{e}$ is now represented by $\ell$ samples of the form \[ \sum_{i=1}^{m}\word{s}_{i}\word{a}^{(i, j)} + \word{e}_{j} \in \fract{\mathbb{F}_q[X]}{(X^{n}-1)} \] where $\word{s}$ can be considered as a collection of $m$ secrets $\word{s}_{1}, \dots, \word{s}_{m}$. This would be the code analogue of Module--$\mathsf{LWE}${}, with a rank $m$ module and $\ell$ samples, introduced in \cite{LS15}. Contrary to structured lattice cryptosystems, up to now, no reduction from the search to the decision version of the structured decoding problem was known. This was pointed out by NIST \cite{NIST20}, and was a reason for those code-based cryptosystems to be only considered as alternate candidates for the third round. Actually even before NIST standardization process, this lack of search to decision reduction was already pointed out by the authors of the Ring--$\mathsf{LPN}${} based authentication scheme \textsc{Lapin}{} \cite{HKLPP12}. \newline {\bf \noindent Our contribution.} To handle this lack of search to decision reduction in the code setting, we propose in this article a new generic problem called $\mathsf{FF}$--$\mathsf{DP}${}, for {\em Function Field Decoding Problem}, in the Ring--$\mathsf{LWE}${} fashion. One of the key ideas consists in using function fields instead of number fields, the latter being used in the lattice case. This framework enables us to adapt directly the search to decision reduction of \cite{LPR10} in the case of codes. Frequently in the literature on Ring--$\mathsf{LWE}${}, the search to decision reduction is instantiated with cyclotomic number fields. In the same spirit we present an instantiation with function fields analogues of cyclotomic fields, namely the so-called {\em Carlitz extensions}. As we show, this framework is for instance enough to provide a search to decision reduction useful in the context of \textsc{Lapin}{} \cite{HKLPP12} or for a $q$--ary analogue of Ring--$\mathsf{LPN}${} used for secure multiparty computation \cite{BCGIKS20}. If our reduction does not work for every schemes based on structured codes such as {\sc HQC}{}, we believe that our work paves the way towards a full reduction. \begin{remark} Note that the use of function fields in coding theory is far from being new. Since the early 80's and the seminal work of Goppa \cite{G81}, it is well--known that codes called {\em Algebraic Geometry} (AG) codes can be constructed from algebraic curves or equivalently from function fields and that some of these codes have better asymptotic parameters than random ones \cite{TVZ82}. However, the way they are used in the present work is completely different. Indeed, AG codes are a natural generalization of Reed--Solomon and, in particular, are codes benefiting from efficient decoding algorithms (see for instance surveys \cite{HP95,BP08,CR21}). In the present article, the approach is somehow orthogonal to the AG codes setting since we use function fields in order to introduce generic problems related to structured codes for which the decoding problem is supposed to be hard. \end{remark} {\bf \noindent A function field approach.} Lattice-based cryptography has a long standing history of using number fields and their rings of integers to add some structure and reduce the key sizes. Recall that number fields are algebraic extensions of $\mathbb{Q}$ of the form \[ K \stackrel{\textrm{def}}{=} \fract{\mathbb{Q}[X]}{(f(X))}, \] where $f$ is an irreducible polynomial, and the ring of integers $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ is the integral closure of $\mathbb{Z}$ in $K$, {\em i.e. } it is the subring of $K$ composed of elements which are roots of monic polynomials with coefficients in $\mathbb{Z}$. For instance, cyclotomic extensions are of the form $K = \mathbb{Q}(\zeta_{m}) = {\mathbb{Q}[X]}/{(\Phi_{m}(X))}$ where $\zeta_{m}$ is a primitive $m$-th root of unity and $\Phi_{m}$ is the $m$-th cyclotomic polynomial. The ring of cyclotomic integers has a very specific form, namely $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = \mathbb{Z}[\zeta_{m}]$. One of the most used case is when $m$ is a power of $2$. In this case, setting $m = 2n$, we have $\Phi_{m} = \Phi_{2n} = X^{n}+1$ and $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = {\mathbb{Z}[X]}/{(X^{n}+1)}$. Such rings have been widely used since they benefit from a very fast arithmetic thanks to the fast Fourier transform. In the Ring--$\mathsf{LWE}${} setting, one reduces all the samples modulo a large prime element $q\in\mathbb{Z}$ called the {\em modulus} and hence considers the ring ${(\mathbb{Z}/q\mathbb{Z})[X]}/{(X^{n}+1)}$.\iftoggle{llncs}{}{ Due to inherent considerations of the Euclidean metric, errors are drawn according to a {\em continuous} distribution (e.g a Gaussian distribution) $\chi$ over the Euclidean space $K\otimes_{\mathbb{Q}}\mathbb{R} = {\mathbb{R}[X]}/{(X^{n}+1)}$ and one has to introduce a technical tool called {\em smoothing parameter} to handle the {\em discrete} error distributions used in practice. It should be noted that an equivalent of the smoothing parameter will not be necessary in our case because our error model will remain discrete.} When moving from structured lattices to structured codes, it would be tantalizing to consider the ring ${\mathbb{F}_q[X]}/{(X^{n}-1)}$ as the analogue of ${\mathbb{Z}[X]}/{(X^{n}+1)}$. However, if the two rings have a similar expression they have a fundamental difference. Note for instance that the former is finite while the latter is infinite. From a more algebraic point of view, ${\mathbb{F}_q[X]}/{(X^{n}-1)}$ is said to have {\em Krull dimension} $0$ while ${\mathbb{Z}[X]}/{(X^{n}+1)}$ has {\em Krull dimension $1$}. In particular, the former has only a finite number of ideals while the latter has infinitely many prime ideals. The main idea of the present article is to lift the decoding problem and to see ${\mathbb{F}_q[X]}/{(X^{n}-1)}$ as a quotient ${R}/{I}$ of some ring $R$ of Krull dimension $1$. The ideal $I$ will be the analogue of the {\em modulus}. This setting can be achieved using so-called {\em function fields}. It could be argued that the results of this article could have been obtained without introducing function fields. However, we claim that function fields are crucial for at least three reasons: \begin{enumerate} \item Introducing function fields permits to establish a strong connection between cryptography based on structured lattices involving number fields on the one hand and cryptography based on structured codes on the other hand. \item Number theory has a rich history with almost one hundred years of development of the theory of function fields. We expect that, as number fields did for structured lattices, function fields will yield a remarkable toolbox to study structured codes and cryptographic questions related to them. \item A third and more technical evidence is that a crucial part of the search to decision reduction involves some Galois action. We claim that, even if for a specific instantiation, this group action could have been described in a pedestrian way on the finite ring ${\mathbb{F}_q [X]}/{(X^n - 1)}$, without knowing the context of function fields, such a group action would really look like ``a rabbit pulled out of a hat''. In short, this group action, which is crucial to conclude the search to decision reduction, cannot appear to be something natural without considering function fields. \end{enumerate} It is well--known for a long time that there is a noticeable analogy between the theory of number fields and that of function fields. Starting from the ground, the rings $\mathbb{Z}$ and $\mathbb{F}_q[T]$ share a lot of common features. For instance, they both have an Euclidean division. Now if one considers their respective fraction fields $\mathbb{Q}$ and $\mathbb{F}_q(T)$, finite extensions of $\mathbb{Q}$ yield the number fields while finite separable extensions of $\mathbb{F}_q(T)$ are called {\em function fields} because they are also the fields of rational functions on curves over finite fields. Now, a similar arithmetic theory can be developed for both with rings of integers, orders, places and so on. Both rings of integers are {\em Dedekind domains}. In particular, every ideal factorizes uniquely into a product of prime ideals, and the quotient by any non-zero ideal is always finite. A dictionary summarizing this analogy between number fields and function fields is represented in Table \ref{fig:ff_analogy}. Note that actually, many properties that are known for function fields are only conjectures for number fields. The best example is probably the Riemann hypothesis which has been proved by Weil in the early 1940s in the function field case. \begin{table}[ht] \centering \[ \begin{array}{|c|c|} \hline \text{ Number fields } & \text{ Function fields } \\ \hline \mathbb{Q} & \mathbb{F}_q(T) \\ \mathbb{Z} & \mathbb{F}_q[T] \\ \text{Prime numbers } q \in \mathbb{Z} & \text{Irreducible polynomials } Q \in \mathbb{F}_q[T]\\ & \\ K = \fract{\mathbb{Q}[X]}{(f(X))} & K = \fract{\mathbb{F}_q(T)[X]}{(f(T, X))}\\ & \\ \makecell{\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} \\ = \text{Integral closure of $\mathbb{Z}$} \\ \text{\emph{Dedekind} domain}} & \makecell{\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} \\ = \text{Integral closure of $\mathbb{F}_q[T]$} \\ \text{\emph{Dedekind} domain}} \\ & \\ { \textbf{characteristic 0}} & {\bf \textbf{characteristic} >0}\\ \hline \end{array} \] \caption{A Number-Function fields analogy} \label{fig:ff_analogy} \end{table} With this analogy in hand, the idea is to find a nice function field $K$ with ring of integers $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ and an irreducible polynomial $Q\in\mathbb{F}_q[T]$, called the {\em modulus}, such that ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}} = {\mathbb{F}_q[X]}/{(X^{n}-1)}$. Following the path of \cite{LPR10}, we are able to provide a search to decision reduction for our generic problem $\mathsf{FF}$--$\mathsf{DP}${} when three conditions hold: \begin{enumerate} \item\label{hyp:galois} The function field $K$ is Galois. \item\label{hyp:splitting_modulus} The modulus $Q$ does not ramify in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$, meaning that the ideal $Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ factorizes in product of distinct prime ideals. \item\label{hyp:galois_distribution} The distribution of errors is invariant under the action of the Galois group. \end{enumerate} This framework is enough to provide a search to decision reduction useful in the context of \textsc{Lapin}{} \cite{HKLPP12} or for a $q$--ary analogue of Ring--$\mathsf{LPN}${} used for secure MPC \cite{BCGIKS20}. It should be emphasized that, in the case of \textsc{Lapin}{}, the search to decision reduction requires to adapt the definition of the noise which will remain built by applying independent Bernouilli variables but with a peculiar choice of $\F{2}$--basis of the underlying ring ${\F{2}[X]}/{(f(X))}$. The chosen basis is a {\em normal} basis, {\em i.e. } is globally invariant with respect to the Galois action. This change of basis is very similar to the one performed in lattice based-cryptography when, instead of considering the monomial basis $1, X, \dots, X^{n-1}$ in an order ${\mathbb{Z}[X]}/{(f(X))}$, one considers the canonical basis after applying the Minkowski embedding. Indeed, the latter is Galois invariant. We emphasize that, here again, the function field point of view brings in a Galois action which cannot appear when only considering a ring such as ${\F{2}[X]}/{(f(X))}$. This is another evidence of the need for introducing function fields. \newline {\noindent \bf Outline of the article.} The present article is organised as follows. Section \ref{sec:prereqFF} recalls the necessary background about function fields (definitions and important properties). In Section \ref{sec:FFDP} we present the $\mathsf{FF}$--$\mathsf{DP}${} problem (search and decision versions) as well as our main theorem (Theorem \ref{thm:main}) which states the search to decision reduction in the function field setting.\iftoggle{llncs}{ A proof of this theorem is given in Supplementary Materials for sake of completeness.}{ A proof of this theorem is given in Section \ref{sec:StD}. A reader only interested about the framework of functions fields and our instantiations can safely skip this section.} In Section \ref{sec:carlitz} we give a self contain presentation of Carlitz extensions. They will be used to instantiate our search to decision reduction in Section \ref{sec:applications}, which provides our applications. \section{Prerequisites on function fields}\label{sec:prereqFF} In this section, we list the minimal basic notions on the arithmetic of function fields that are needed in the sequel. A dictionary drawing the analogies has been given in Table~\ref{fig:ff_analogy}. For further references on the arithmetic of function fields, we refer the reader to \cite{S09,R02}. Starting from a finite field $\mathbb{F}_q$, {\em a function field} is a finite extension $K$ of $\mathbb{F}_q(T)$ of degree $n>0$ of the form \[ K = \fract{\mathbb{F}_q(T)[X]}{(P(T, X))} \] where $P(T,X) \in \mathbb{F}_q(T)[X]$ is irreducible of degree $n$. The field $K \cap \overline{\F{}}_{q}$ is referred to as {\em the field of constants} or {\em constant field} of $K$, where $\overline{\F{}}_q$ is the algebraic closure of $\mathbb{F}_q$. In the sequel, we will assume that $\mathbb{F}_q$ is the full field of constants of $K$, which is equivalent for $P(T, X)$ to be irreducible even regarded as a an element of $\overline{\F{}}_q(T)[X]$ (\cite[Cor.~3.6.8]{S09}). Similarly to the number field case, one can define the ring of integers $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ as the the ring of elements of $K$ which are the roots of a monic polynomial in $\mathbb{F}_q[T][X]$. This ring is a {\em Dedekind domain}. In particular, any ideal $\mathfrak{P}$ has a unique decomposition $\mathfrak{P}_1^{e_1}\cdots \mathfrak{P}_r^{e_r}$ where the $\mathfrak{P}_i$'s are prime ideals. In the sequel, we frequently focus on the following setting represented in the diagram below: starting from a prime ideal $\mathfrak{p}$ of $\mathbb{F}_q[T]$ (which is nothing but the ideal generated by an irreducible polynomial $Q(T)$ of $\mathbb{F}_q[T]$), we consider the ideal $\mathfrak P \stackrel{\textrm{def}}{=} \mathfrak p \mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ and its decomposition: \[ \mathfrak{P} = \mathfrak{P}_1^{e_1} \cdots \mathfrak{P}_r^{e_r}. \] \begin{center} \begin{tikzpicture} \matrix (m) [matrix of math nodes,row sep=3em,column sep=4em,minimum width=2em] { \mathfrak{P} \subset \mathcal{O}} \newcommand{\II}{\mathcal{I}_K & K \\ \mathfrak{p} \subset \mathbb{F}_q[T] & \mathbb{F}_q(T) \\}; \path[-] (m-1-1) edge (m-2-1) edge (m-1-2) (m-2-1) edge (m-2-2) (m-1-2) edge (m-2-2); \end{tikzpicture} \end{center} The prime ideals $\mathfrak{P}_{i}$'s are said to {\em lie above} $\mathfrak{p}$. The exponents $e_i$'s are referred to as the {\em ramification indexes}, and the extension is said to be {\em unramified} at $\mathfrak{P}$ when all the $e_i$'s are equal to $1$. Another important constant related to a $\mathfrak{P}_i$ is its {\em inertia degree}, which is defined as the extension degree $f_i \stackrel{\textrm{def}}{=} [\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/\mathfrak{P}_i:\mathbb{F}_q[T]/\mathfrak p]$ (one can prove that $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/\mathfrak{P}_i$ and $\mathbb{F}_q[T]/\mathfrak p$ are both finite fields). The Chinese Remainder Theorem (CRT) induces a ring isomorphism between $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\mathfrak{P}$ and $\prod_{i=1}^{r}\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\mathfrak{P}_{i}^{e_{i}}$. In particular, when the extension is unramified at $\mathfrak{P}$, the quotient $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\mathfrak{P}$ is a product of finite fields. Finally, a well-known result asserts that \begin{equation}\label{eq:fundamental_equality} n = [K:\mathbb{F}_q(T)] = \sum_{i=1}^r e_i f_i. \end{equation} \noindent {\bf Finite Galois extensions.} \iftoggle{llncs}{}{Recall that a finite algebraic field extension $L/K$ is said to be a {\em Galois extension} when the automorphism group \[ {\rm Aut}(L/K) \stackrel{\textrm{def}}{=} \{\sigma \colon L \rightarrow L \mid \sigma \text{ is an isomorphism with } \sigma(a) = a \text{ for all } a\in K\} \] has cardinality $[L:K]$. In that case, we refer to ${\rm Aut}(L/K)$ as the {\em Galois group} of $L/K$ and write ${\rm Gal}(L/K) \stackrel{\textrm{def}}{=} {\rm Aut}(L/K)$. Galois extensions whose Galois group is abelian are called {\em abelian extensions}. Galois extensions have many properties that do not hold in general field extensions. When $L/K$ is a Galois extension, and if $H$ is a subgroup of $G\stackrel{\textrm{def}}{=} {\rm Gal}(L/K)$, then the set \[ L^{H}\stackrel{\textrm{def}}{=} \{ a \in L \mid \sigma(a) = a \text{ for all } \sigma\in H \} \] is a field called the {\em fixed field} of $H$. By definition $L^{G} = K$. Furthermore, the extension $L/L^{H}$ is Galois with Galois group $H$. On the other hand, the extension $L^{H}/K$ may not be Galois in general, but it is the case when $H$ is a normal subgroup of $G$, and ${\rm Gal}(L^{H}/L) = G/H$. This is particularly true when $L$ is an abelian extension.} Consider $K/\mathbb{F}_q(T)$ a Galois function field ({\em i.e. } a function field $K$ which is a Galois extension of $\mathbb{F}_q(T)$), with Galois group $G\stackrel{\textrm{def}}{=} {\rm Gal}(K/\mathbb{F}_q(T))$. Then, $G$ keeps $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ globally invariant. Furthermore, given $\mathfrak{p}$ a prime ideal of $\mathbb{F}_q[T]$, the group $G$ acts transitively on the set $\{\goth{P}_{1},\dots, \goth{P}_{r}\}$ of prime ideals of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ lying above $\mathfrak{p}$: for any $i\neq j$ there exists $\sigma\in{\rm Gal}(K/\mathbb{F}_q(T))$ such that $\sigma(\goth{P}_{i}) = \goth{P}_{j}$. In particular, all the ramification indexes $e_{i}$ ({\em resp.} the inertia degrees $f_{i}$) are equal and denoted by $e$ ({\em resp.} $f$): $\goth{P} \stackrel{\textrm{def}}{=} \mathfrak{p}\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = (\goth{P}_{1}\dots\goth{P}_{r})^{e}$ and \eqref{eq:fundamental_equality} becomes $n = efr$. Another consequence which will be crucial for the applications, is that the action of $G$ on $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ is well--defined on $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$ and simply permutes factors $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}_{i}^{e}$. The {\em decomposition group} of $\goth{P}_{i}$ over $\goth{p}$ is \[ D_{\goth{P}_{i}/\mathfrak{p}}\stackrel{\textrm{def}}{=} \{\sigma \in G \mid \sigma \left(\goth{P}_{i}\right) = \goth{P}_{i}\}. \] It has cardinality $e\times f$. In particular, when $K$ is unramified at $\goth{P}$, the field $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}_{i}$ is $\mathbb{F}_{q^{f}}$ and the action of $D_{\goth{P}_{i}/\mathfrak{p}}$ on it is the Frobenius automorphism: the reduction modulo $\goth{P}_{i}$ yields an isomorphism \begin{equation}\label{eq:decomp_isom} D_{\goth{P}_{i}/\mathfrak{p}} \simeq {\rm Gal}(\mathbb{F}_{q^{f}}/\mathbb{F}_q). \end{equation} Finally, all the decomposition groups of primes above $\goth{p}$ are conjugate: for any $i\neq j$ there exists $\sigma\in G$ such that $D_{\goth{P}_{i}/\mathfrak{p}} = \sigma D_{\goth{P}_{j}/\mathfrak{p}}\sigma^{-1}$. \section{A function field approach for search to decision reduction} \label{sec:FFDP} {\bf \noindent Search and decision problems.} In this section, we introduce a new generic problem that we call $\mathsf{FF}$--$\mathsf{DP}${}, which is the analogue of Ring--$\mathsf{LWE}${} in the context of function fields. Then, we give our main theorem which states the search-to-decision reduction of $\mathsf{FF}$--$\mathsf{DP}${}. Since function fields and number fields share many properties, the present search to decision reduction, that is proven in Section \ref{sec:StD}, will work similarly as in \cite{LPR10}. Consider a function field ${K}/{\mathbb{F}_q(T)}$ with constant field $\mathbb{F}_q$ and ring of integers $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ and let $Q(T)\in\mathbb{F}_q[T]$. Let $\goth{P} \stackrel{\textrm{def}}{=} Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ be the ideal of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ generated by $Q$. Recall that ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ is a finite set. $\mathsf{FF}$--$\mathsf{DP}${} is parameterized by an element $\word{s}\in{\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ called the {\em secret} and $\psi$ be a probability distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ called the {\em error distribution}. \begin{definition} [$\mathsf{FF}$--$\mathsf{DP}${} Distribution]\label{def:FFDP_distribution} A sample $(\vec{a}, \vec{b}) \in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}\times {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ is distributed according to the $\mathsf{FF}$--$\mathsf{DP}${} distribution modulo $\goth{P}$ with secret $\word{s}$ and error distribution $\psi$ if \begin{itemize}[label=\textbullet] \item $\word{a}$ is uniformly distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, \item $\word{b} = \word{a} \word{s} + \word{e} \in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ where $\vec{e}$ is distributed according to $\psi$. \end{itemize} A sample drawn according to this distribution will be denoted by $(\word{a}, \word{b})\leftarrow \ffd{\word{s}, \psi}$. \end{definition} The aim of the search version of the $\mathsf{FF}$--$\mathsf{DP}${} problem is to recover the secret $\word{s}$ given samples drawn from $\ffd{\word{s}, \psi}$. This is formalized in the following problem. \iftoggle{llncs}{\begin{definition}}{\begin{problem}} [$\mathsf{FF}$--$\mathsf{DP}${}, Search version] \label{pb:FFDP_search} Let $\word{s}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, and let $\psi$ be a probability distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. An instance of $\mathsf{FF}$--$\mathsf{DP}${} problem consists in an oracle giving access to independent samples $(\word{a}, \word{b}) \leftarrow \ffd{\vec{s}, \psi}$. The goal is to recover $\word{s}$. \iftoggle{llncs}{\end{definition}}{\end{problem}} \begin{remark} This problem should be related to structured versions of the decoding problem. Indeed, recall from the discussion in the introduction that, using the polynomial representation, the decoding problem of random quasi-cyclic codes corresponds to recovering a secret polynomial $\word{s}(X)\in {\mathbb{F}_q[X]}/{(X^{n}-1)}$ given access to samples of the form $\word{a}\word{s} + \word{e} \in {\mathbb{F}_q[X]}/{(X^{n}-1)}$ where $\word{a}$ is uniformly distributed in ${\mathbb{F}_q[X]}/{(X^{n}-1)}$. This can be rephrased within the $\mathsf{FF}$--$\mathsf{DP}${} framework as follows. Consider the polynomial $f(T, X) \stackrel{\textrm{def}}{=} X^{n}+T-1 \in \mathbb{F}_q(T)[X]$. When $n$ is not divisible by the characteristic of $\mathbb{F}_q$, $f$ is a separable polynomial. Moreover, by Eisenstein criterion $f$ is irreducible. Define the function field $K$ generated by $f$, namely the extension $K\stackrel{\textrm{def}}{=} {\mathbb{F}_q(T)[X]}/{(f(T, X))}$. One can prove that $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ is exactly ${\mathbb{F}_q[T][X]}/{(f(T, X))}$. Now, let $\mathfrak{p}$ be the ideal of $\mathbb{F}_q[T]$ defined by the irreducible polynomial $T$, and let $\mathfrak{P}\stackrel{\textrm{def}}{=} \mathfrak{p}\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = T\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ be the corresponding ideal of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$. Then the following isomorphisms hold \[ \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}{\mathfrak{P}} \simeq \fract{\mathbb{F}_q[T, X]}{(T, X^{n}+T-1)} \simeq \fract{\mathbb{F}_q[X]}{(X^{n}-1)}. \] With this particular instantiation, ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\mathfrak{P}}$ is exactly the ambient space from which the samples are defined in the structured versions of the decoding problem. As a consequence, $\mathsf{FF}$--$\mathsf{DP}${} is a generalization of structured versions of the decoding problem, when considering arbitrary function fields and ideals. \end{remark} For cryptographic applications, we are also interested in the {\em decision} version of this problem. The goal is now to distinguish between the $\mathsf{FF}$--$\mathsf{DP}${} distribution and the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}} \times {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. \iftoggle{llncs}{\begin{definition}}{\begin{problem}} [$\mathsf{FF}$--$\mathsf{DP}${}, Decision version] \label{pb:FFDP_decision} Let $\word{s}$ be drawn uniformly at random in ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ and let $\psi$ be a probability distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. Define $\code{D}_{0}$ to be the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}} \times {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, and $\code{D}_{1}$ to be the $\mathsf{FF}$--$\mathsf{DP}${} distribution with secret $\word{s}$ and error distribution $\psi$. Furthermore, let $b$ be a uniform element of $\{0,1\}$. Given access to an oracle $\code{O}_{b}$ providing samples from distribution $\code{D}_{b}$, the goal of the decision $\mathsf{FF}$--$\mathsf{DP}${} is to recover $b$. \iftoggle{llncs}{\end{definition}}{\end{problem}} \begin{remark} For some applications, for instance to MPC, it is more convenient to have the secret $\word{s}$ drawn from the error distribution $\psi$ instead of the uniform distribution over $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$. In the lattice-based setting, this version is sometimes called $\mathsf{LWE}${} with {\em short secret} or $\mathsf{LWE}${} in {\em Hermite normal form}. However, both decision problems are easily proved to be computationally equivalent, see \cite[Lemma 3]{L11a}. The proof applies directly to $\mathsf{FF}$--$\mathsf{DP}${}. \end{remark} A {\em distinguisher} between two distributions $\code{D}_{0}$ and $\code{D}_{1}$ is a probabilistic polynomial time (PPT) algorithm $\code{A}$ that takes as input an oracle $\code{O}_{b}$ corresponding to a distribution $\code{D}_{b}$ with $b\in \{0, 1\}$ and outputs an element $\code{A}(\code{O}_{b})\in\{0, 1\}$. \iftoggle{llncs}{\ \newline}{Consider the following approach for solving a decision problem between two distributions $\code{D}_{0}$ and $\code{D}_{1}$, pick $b\leftarrow \{0, 1\}$ and answer $b$ regardless of the input. This algorithm solves this problem with probability $1/2$ which is not interesting. The efficiency of an algorithm $\code{A}$ solving a decision problem is measured by the difference between its probability of success and $1/2$. The relevant quantity to consider is the {\em advantage} defined as: \[ {\rm Adv}_{\code{A}}(\code{D}_{0}, \code{D}_{1}) \stackrel{\textrm{def}}{=} \dfrac{1}{2} \left( \mathbb{P}(\code{A}(\code{O}_{b}) = 1 \mid b = 1) - \mathbb{P}(\code{A}(\code{O}_{b}) = 1 \mid b = 0) \right) \] where the probabilities are computed over the internal randomness of $\code{A}$, a uniform $b \in \{0,1\}$ and inputs according to a distribution $\code{D}_{b}$. The advantage of a distinguisher $\code{A}$ measures how good it is to solve a distinguishing problem. Indeed, it is classical fact that: \[ \mathbb{P}(\code{A}(\code{O}_{b}) = b) = \frac{1}{2} + {\rm Adv}_{\code{A}}(\code{D}_{0}, \code{D}_{1}). \] \begin{remark} Even if it means answering $1-\code{A}(\code{O}_{b})$ instead of $\code{A}(\code{O}_{b})$, the advantage can always be assumed to be a positive quantity. \end{remark} \noindent {\bf A module version.} Instead of considering one secret $\word{s}\in\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$, we could use multiple secrets $(\word{s}_{1},\dots,\word{s}_{d})\in \left( \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}\right )^{d}$. This generalization has been considered in lattice-based cryptography under the terminology Module-$\mathsf{LWE}${} \cite{LS15}, where the secret can be thought as an element of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}^{d}$ which is a free $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$-module of rank $d$, before a reduction modulo $\goth{P}$ on each component. This would yield the following definition. \begin{definition} [$\mathsf{MFF}$--$\mathsf{DP}${} Distribution]\label{def:MFFDP_distribution} Let $d\ge 1$ be an integer. A sample $(\word{a}, \word{b}) \in \left(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}\right)^{d}\times \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$ is distributed according to the $\mathsf{MFF}$--$\mathsf{DP}${} distribution modulo $\goth{P}$ with secret $\word{s} \stackrel{\textrm{def}}{=} (\word{s}_{1},\dots, \word{s}_{d})\in \left(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}\right)^{d}$ and error distribution $\psi$ over $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$ if \begin{itemize} \item $\word{a}$ is uniformly distributed over $\left(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}\right)^{d}$, \item $\word{b} = \sum_{i=1}^{d}\word{a}_{i}\word{s}_{i}+\word{e}\in \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$ where $\vec{e}$ is distributed according to $\psi$. \end{itemize} \end{definition} The search and decision problems associated to $\mathsf{MFF}$--$\mathsf{DP}${} can be defined as a natural generalization of Problems \ref{pb:FFDP_search} and \ref{pb:FFDP_decision}. \iftoggle{llncs}{\begin{definition}}{\begin{problem}} [$\mathsf{MFF}$--$\mathsf{DP}${}, Search version] \label{pb:MFFDP_search} Let $\word{s}\in(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P})^{d}$ be a collection of elements of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$ called the secrets, and let $\psi$ be a probability distribution over $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$. An instance of the $\mathsf{MFF}$--$\mathsf{DP}${} problem consists in an oracle giving access to independent samples $(\word{a}, \word{b})$ from the $\mathsf{MFF}$--$\mathsf{DP}${} distribution with secrets $\word{s}$ and error distribution $\psi$. The goal is to recover $\word{s}$. \iftoggle{llncs}{\end{definition}}{\end{problem}} \iftoggle{llncs}{\begin{definition}}{\begin{problem}} [$\mathsf{MFF}$--$\mathsf{DP}${}, Decision version] \label{pb:MFFDP_decision} Let $\word{s}$ be drawn uniformly at random in $(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P})^{d}$ and let $\psi$ be a probability distribution over $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$. Define $\code{D}_{0}$ to be the uniform distribution over $(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P})^{d}\times\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$, and $\code{D}_{1}$ to be the $\mathsf{MFF}$--$\mathsf{DP}${} distribution with secrets $\word{s}$ and error distribution $\psi$. Furthermore, let $b$ be a uniform element of $\{0,1\}$. Given access to an oracle $\code{O}_{b}$ providing samples from distribution $\code{D}_{b}$, the goal of the decision $\mathsf{MFF}$--$\mathsf{DP}${} is to recover $b$. \iftoggle{llncs}{\end{definition}}{\end{problem}} } {\bf \noindent Search to decision reduction.} \iftoggle{llncs}{We are now ready to present our main theorem.}{There is an obvious reduction from the decision to the search version of $\mathsf{FF}$--$\mathsf{DP}${}. Indeed, if there exists an algorithm $\code{A}$ that given access to the $\ffd{\word{s}, \psi}$ distribution is able to recover the secret $\word{s}$, then it yields to a distinguisher between $\ffd{\word{s}, \psi}$ and the uniform distribution. The converse reduction needs more work. However, due to the strong analogy between function and number fields, our proof is in fact essentially the same as in \cite{LPR10,L11a}. More precisely, we have the following theorem.} \begin{theorem}[Search to decision reduction for $\mathsf{FF}$--$\mathsf{DP}${}]\label{thm:main} Let ${K}/{\mathbb{F}_q(T)}$ be a Galois function field of degree $n$ with field of constants $\mathbb{F}_q$, and denote by $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ its ring of integers. Let $Q(T)\in\mathbb{F}_q[T]$ be an irreducible polynomial. Consider the ideal $\mathfrak{P}\stackrel{\textrm{def}}{=} Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$. Assume that $\mathfrak{P}$ does not ramify in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$, and denote by $f$ its inertia degree. Let $\psi$ be a probability distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, closed under the action of ${\rm Gal}({K}/{\mathbb{F}_q(T)})$, meaning that if $\vec{e}\leftarrow\psi$, then for any $\sigma \in {\rm Gal}(K/\mathbb{F}_q(T))$, we have $\sigma(\vec{e})\leftarrow\psi$. Let $\word{s}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. Suppose that we have an access to $\ffd{\vec{s}, \psi}$ and there exists a distinguisher between the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ and the $\mathsf{FF}$--$\mathsf{DP}${} distribution with uniform secret and error distribution $\psi$, running in time $t$ and having an advantage $\varepsilon$. Then there exists an algorithm that recovers $\word{s}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ (with an overwhelming probability in $n$) in time \[ O\left( \frac{n^{4}}{f^{3}}\times \frac{1}{\varepsilon^{2}} \times q^{f \deg(Q)}\times t\right). \] \end{theorem} \begin{remark} We have assumed implicitly in the statement of the theorem that we have an efficient access to the Galois group of ${K}/{\mathbb{F}_q(T)}$ and its action can be computed in polynomial time. \end{remark} \begin{remark} There are many degrees of freedom in the previous statement: choice of the function field $K$ (and on the degree $n$), choice of the polynomial $Q$ (and on $f$ and $\deg(Q)$). For our instantiations, we will often choose the ``modulus'' $Q$ to be a linear polynomial ($\deg(Q) = 1$) and $K$ will be a (subfield of) a cyclotomic function field. \end{remark} \begin{remark} Due to the continuity of error distributions used in lattice-based cryptography, a technical tool called the {\em smoothing parameter} was introduced by Micciancio and Regev in \cite{MR04}. It characterizes how a Gaussian distribution is close to uniform, both modulo the lattice, and is ubiquitously used in reductions. However, in the function field setting, we do not need to introduce such a tool because the error distribution is discrete and already defined on the quotient ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. \end{remark} \iftoggle{llncs}{ }{ \begin{remark} In \cite{LS15}, Langlois and Stehlé proved a search to decision reduction for the module version of $\mathsf{LWE}${}. The idea is to use the distinguisher in order to retrieve the secrets one by one. Their proof applies {\em mutatis mutandis} to $\mathsf{MFF}$--$\mathsf{DP}${}, resulting in a time overhead of $d$, where $d$ denotes the rank of the underlying module, {\em i.e.} the number of secrets. The main change is in the {\em guess and search} step (Step 3 in the proof presented in Section \ref{sec:StD}) where the randomization is applied on only one component of $\word{a}$ to recover one secret, and repeating the process $d$ times (one for each secret). More precisely, for $\mathsf{MFF}$--$\mathsf{DP}${}, the running time claimed in Theorem \ref{thm:main} should be replaced with \[ O\left( d\times \frac{n^{4}}{f^{3}} \times \frac{1}{\varepsilon^{2}} \times q^{f \deg(Q)} \times t \right). \] \end{remark} } \iftoggle{llncs}{ \begin{remark}[$\mathsf{MFF}$--$\mathsf{DP}${}] Instead of considering one secret $\word{s}\in\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$, we could use multiple secrets $(\word{s}_{1},\dots,\word{s}_{d})\in \left( \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}\right )^{d}$. The goal is now to recover the secrets from samples $(\word{a}, \word{b})$ with $\word{a} = (\word{a}_{1},\dots,\word{a}_{d})$ uniformly distributed over $(\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P})^{d}$ and $\word{b} = \inner{\word{a}, \word{s}} + \word{e} = \sum_{i=1}^{d}\word{a}_{i}\word{s}_{i}+\word{e}$ with $\word{e} \leftarrow \psi$. This generalization has been considered in lattice-based cryptography under the terminology Module-$\mathsf{LWE}${} \cite{LS15}, because the secret can be thought as an element of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}^{d}$ which is a free $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$-module or rank $d$, before a reduction modulo $\goth{P}$ on each component. Following \cite[Section 4.3]{LS15}, it is possible to adapt Theorem \ref{thm:main} ; the search to decision only yielding an overhead of $d$ (the number of secrets). The running time would now be \[ O\left( d\times \frac{n^{4}}{f^{3}} \times \frac{1}{\varepsilon^{2}} \times q^{f \deg(Q)} \times t \right). \] \end{remark} }{} \iftoggle{llncs}{ {\noindent \em Sketch of Proof of Theorem \ref{thm:main}.} The proof of this Theorem is very similar to the one for Ring--$\mathsf{LWE}${} and lattices \cite{LPR10}. It uses four steps that we quickly describe. Let $\goth{P} = \goth{P}_{1}\dots\goth{P}_{r}$, where $r = n/f$, be the factorisation of $\goth{P}$ in prime ideals. \begin{description}[align = left,leftmargin=*] \item[Step 1. Worst to Average Case.\label{desc:step1}] In the definition of Problem~\ref{pb:FFDP_decision} the secret $\word{s}$ is supposed to be {\em uniformly} distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, while in the search version the secret is {\em fixed}. This can easily be addressed, for any sample $(\word{a}, \word{b}) \leftarrow \ffd{\word{s}, \psi}$ with fixed secret $\word{s}$, it is enough to pick $\word{s}'\leftarrow {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ and output $(\word{a}, \word{b} + \word{a} \word{s}')$. \newline \item[Step 2. Hybrid argument.\label{desc:step2}] sample $(\word{a}, \word{b})$ is said to be distributed according to the hybrid distribution $\code{H}_{i}$ if it is of the form $(\word{a}', \word{b}' + \word{h})$ where $(\word{a}', \word{b}') \leftarrow \ffd{\word{s}, \psi}$ and $\word{h}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ is uniformly distributed modulo $\goth{P}_{j}$ for $j\le i$ and $\vec{0}$ modulo the other factors. Such an $\word{h}$ can easily be constructed using the Chinese Remainder Theorem. In particular, for $i=0$, $\vec{h}$ is $\vec{0}$ modulo all the factors of $\goth{P}$, therefore $\vec{h}=\vec{0}$ and $\code{H}_{0} = \ffd{\word{s}, \psi}$. On the other hand, when $i=r$, the element $\vec{h}$ is uniformly distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, therefore $\code{H}_{r}$ is {\em exactly} the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. By a hybrid argument, we can turn a distinguisher $\code{A}$ for $\mathsf{FF}$--$\mathsf{DP}${} with advantage $\varepsilon$, into a distinguisher between $(\code{H}_{i_{0}},\code{H}_{i_{0}+1})$ for some $i_{0}$ with advantage $\geq \varepsilon/r$. Everything is analysed as if we knew this index $i_{0}$. In practice we can run $\code{A}$ concurrently with all the $r$ instances. \newline \item[Step 3. Guess and search. \label{desc:step3}] The idea is to perform an exhaustive search in ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$ and to use $\code{A}$ to recover $\widehat{\vec{s}} \stackrel{\textrm{def}}{=} \word{s}\mod\goth{P}_{i_{0}+1}$. Let $\vec{g}_{i_{0}+1} \mathop{=}\limits^{?} \widehat{\vec{s}}$ be our guess and set $\vec{g} \equiv \vec{g}_{i_{0}+1} \mod \goth{P}_{i_{0}+1}$ and $\vec{0}$ otherwise. For each sample $(\vec{a},\vec{b})$ we compute $\vec{a}' \stackrel{\textrm{def}}{=} \vec{a} + \vec{v}$ and $\vec{b}' \stackrel{\textrm{def}}{=} \vec{b} + \vec{h} + \vec{v}\vec{g} = \word{a}' \word{s} + \word{e} + \word{h}'$ where $\word{h}' = \word{h} + \word{v} (\word{g} - \word{s})$ with $\vec{v}\equiv \vec{v}_{i_{0}+1}$ uniform modulo $\goth{P}_{i_{0}+1}$, and $\vec{h}$ uniform modulo the $\goth{P}_{j}$ for $j \leq i_{0}+1$ and $\vec{0}$ otherwise. One can verify that, \[\left\lbrace \begin{array}{ll} \word{h}' \equiv \vec{h}_{j}& \mod \goth{P}_{j} \text{ for } j\le i_{0} \\ \word{h}' \equiv (\vec{g}_{i_{0}+1} - \widehat{\vec{s}}) \vec{v}_{i_{0}+1}\ & \mod \goth{P}_{i_{0}+1} \\ \word{h}' \equiv \vec{0} & \mod \goth{P}_{j} \text{ for } j > i_{0}+1. \\ \end{array}\right. \] If the guess $\vec{g}_{i_{0}+1}$ is correct, $(\word{a}', \word{b}')$ is distributed according to $\code{H}_{i_{0}}$. Otherwise, it is distributed according to $\code{H}_{i_{0}+1}$ because $\word{v}_{i_{0}+1}$ is uniformly distributed over $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}_{i_{0}+1}$ which is a field. The distinguisher will succeed with probability $1/2+\varepsilon/r>1/2$. It suffices to repeat the procedure $\Theta((r/\varepsilon)^{2})$ times, and do a majority voting to know whether the guess $\vec{g}_{i_{0}+1}$ is correct or not. We do that for all the $q^{f\deg(Q)}$ possible guesses. \newline \item[Step 4. Galois action. \label{desc:step4}] Since $K/\mathbb{F}_q(T)$ is Galois, for any $j\neq i_{0}$ we take $\sigma\in{\rm Gal}(K/\mathbb{F}_q(T))$ such that $\sigma(\goth{P}_{j}) = \goth{P}_{i_{0}}$. Now, $(\sigma(\word{a}), \sigma(\word{a})\sigma(\word{s})+\sigma(\word{e})) \leftarrow \ffd{\sigma(\word{s}), \psi}$ because $\psi$ is Galois invariant. The above procedure enables to recover $\sigma(\word{s})\mod \goth{P}_{i_{0}}$. Applying $\sigma^{-1}$ yields $\word{s}\mod \goth{P}_{j}$. Therefore, we are able to recover $\word{s}\mod\goth{P}_{j}$ for any $j$. To compute the full secret $\word{s}$ it remains to use the CRT.\qed \end{description} }{} \iftoggle{llncs}{} {\section{Search to Decision Reductions: Proof of Theorem \ref{thm:main}}\label{sec:StD} \iftoggle{llncs}{ {\bf \noindent Basic definition: advantage.} Consider the following approach for solving a distinguishing problem between two distributions $\code{D}_{0}$ and $\code{D}_{1}$, pick $b\leftarrow \{0, 1\}$ and answer $b$ regardless of the input. This algorithm solves this problem with probability $1/2$ which is not interesting. The efficiency of an algorithm $\code{A}$ solving a decision problem is measured by the difference between its probability of success and $1/2$. The relevant quantity to consider is the {\em advantage} defined as: \[ {\rm Adv}_{\code{A}}(\code{D}_{0}, \code{D}_{1}) \stackrel{\textrm{def}}{=} \dfrac{1}{2} \left( \mathbb{P}(\code{A}(\code{O}_{b}) = 1 \mid b = 1) - \mathbb{P}(\code{A}(\code{O}_{b}) = 1 \mid b = 0) \right) \] where the probabilities are computed over the internal randomness of $\code{A}$, a uniform $b \in \{0,1\}$ and inputs according to a distribution $\code{D}_{b}$. The advantage of a distinguisher $\code{A}$ measures how good it is to solve a distinguishing problem. Indeed, it is classical fact that: \[ \mathbb{P}(\code{A}(\code{O}_{b}) = b) = \frac{1}{2} + {\rm Adv}_{\code{A}}(\code{D}_{0}, \code{D}_{1}). \] \begin{remark} Even if it means answering $1-\code{A}(\code{O}_{b})$ instead of $\code{A}(\code{O}_{b})$, the advantage can always be assumed to be a positive quantity. \end{remark} }{} \iftoggle{llncs}{The proof of Theorem \ref{thm:main} is very similar to the one for Ring-$\mathsf{LWE}${} and lattices. It uses four steps that we describe.}{In this section, we give a proof of Theorem \ref{thm:main}. It is very similar to the one for Ring-$\mathsf{LWE}${} and lattices. It uses four steps that we describe.} Combining them provides the aforementioned result. The main line of proof is as follows. We use an hybrid argument to reduce the search domain, and then proceed to an exhaustive search using the distinguisher to recover $\word{s}$ modulo all the factors of $\goth{P}$. Finally, using the Chinese Remainder Theorem (CRT) one can recover $\word{s}$ completely. The key point here is the action of the Galois group on the primes and that the error distribution is Galois invariant. Let $\goth{P} = \goth{P}_{1}\dots\goth{P}_{r}$ be the decomposition of $\goth{P}$, we have $$ r = n/f $$ where we used the assumptions over $\goth{P}$ and ${K}/{\mathbb{F}_q(T)}$ made in Theorem~\ref{thm:main}, namely that ${K}/{\mathbb{F}_q(T)}$ is a Galois extension of degree $n$ and unramified at $\goth{P}$ with inertia degree $f$. \newline {\bf \noindent Step 1: Worst to Average Case.} Recall that in the definition of Problem~\ref{pb:FFDP_decision} the secret $\word{s}$ is supposed to be {\em uniformly} distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, while in the search version the secret is {\em fixed}. In other words, the decision problem is somehow an {\em average} case problem, while the search version should work in {\em any} case. Fortunately, this can easily be addressed by randomizing the secret. Indeed, for any sample $(\word{a}, \word{b}) \leftarrow \ffd{\word{s}, \psi}$ with fixed secret $\word{s}$, if $\word{s}'\leftarrow {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, then $(\word{a}, \word{b} + \word{a} \word{s}')$ is now a sample from $\ffd{\word{s}+\word{s}', \psi}$ with secret $\word{s}+\word{s}'$ uniformly distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. \newline {\bf \noindent Step 2: Hybrid argument.} Let $\code{A}$ be the distinguisher between the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ and the $\mathsf{FF}$--$\mathsf{DP}${} distribution with uniform secret and error distribution $\psi$, running in time $t$ and having an advantage $\varepsilon$. We use a simple hybrid argument to prove that $\code{A}$ can also distinguish in time $t$ between two consecutive {\em hybrid} distributions with advantage at least $\varepsilon/r$. The factorization of $\goth{P}$ is $\goth{P}_{1}\dots\goth{P}_{r}$. A sample $(\word{a}, \word{b})$ is said to be distributed according to the hybrid distribution $\code{H}_{i}$ if it is of the form $(\word{a}', \word{b}' + \word{h})$ where $(\word{a}', \word{b}') \leftarrow \ffd{\word{s}, \psi}$ and $\word{h}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ is uniformly distributed modulo $\goth{P}_{j}$ for $j\le i$ and $\vec{0}$ modulo the other factors. Such an $\word{h}$ can easily be constructed using the Chinese Remainder Theorem. In particular, for $i=0$, $\vec{h}$ is $\vec{0}$ modulo all the factors of $\goth{P}$, therefore $\vec{h}=\vec{0}$ and $\code{H}_{0} = \ffd{\word{s}, \psi}$. On the other hand, when $i=r$, the element $\vec{h}$ is uniformly distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$, therefore $\code{H}_{r}$ is {\em exactly} the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. \begin{lemma}[Hybrid argument]\label{lem:hybrid} There exists $i_{0}$ such that ${\rm Adv}_{\code{A}}(\code{H}_{i_{0}}, \code{H}_{i_{0}+1}) \ge \frac{\varepsilon}{r}$. \end{lemma} \begin{proof} By definition, ${\rm Adv}_{\code{A}}(\code{H}_{0}, \code{H}_{r}) = \varepsilon$. Furthermore, the following equality holds: \[ {\rm Adv}_{\code{A}}(\code{H}_{0}, \code{H}_{r}) = \sum_{i=0}^{r-1}{\rm Adv}_{\code{A}}(\code{H}_{i}, \code{H}_{i+1}). \] Therefore, it exists $i_{0}\in \llbracket 0, r-1\rrbracket$ such that ${\rm Adv}_{\code{A}}(\code{H}_{i_{0}},\code{H}_{i_{0}+1}) \ge \frac{{\rm Adv}_{\code{A}}(\code{H}_{0}, \code{H}_{r})}{r} = \frac{\varepsilon}{r}$. \end{proof} This hybrid argument has shown the existence of an $i_{0}$ such that $\code{A}$ has an advantage $\varepsilon/r$ for distinguishing distributions $\code{H}_{i_{0}}$ and $\code{H}_{i_{0}+1}$. In what follows, everything is analysed as if we knew this index $i_{0}$. In practice we can run $\code{A}$ concurrently with all the $r$ instances $(\code{H}_{i},\code{H}_{i+1})$'s. Computations on the right index $i_{0}$ will output the secret $\vec{s}$ (which can be verified) as it will be explained afterward. Therefore, our reduction will output $\vec{s}$ with a ``resource overhead'' given by at most a factor $r$. \newline {\bf \noindent Step 3: Guess and search.} Given $i_{0}$ such as in Lemma \ref{lem:hybrid}. The idea is to perform an exhaustive search in ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$ and to use $\code{A}$ to recover $\word{s}\mod\goth{P}_{i_{0}+1}$. \begin{lemma}\label{lem:guess_and_search} Let $\code{A}$ be a distinguisher with advantage $\delta$ between hybrid distributions $\code{H}_{i_{0}}$ and $\code{H}_{i_{0}+1}$, with secret $\word{s}$, running in time $t$. Then there exists an algorithm $\code{B}$ that recovers $\word{s}\mod \goth{P}_{i_{0}+1}$ with overwhelming probability in $n$ in time $O\left(q^{f\deg(Q)} \times \frac{n}{\delta^{2}}\times t \right)$. \end{lemma} \begin{proof} Our algorithm will proceed with a {\em guess and search} technique using the distinguisher $\code{A}$ in hand. The idea is to {\em guess} the value of $\word{s}\mod\goth{P}_{i_{0}+1}$ and transform any sample $(\word{a}, \word{b})\leftarrow\ffd{\word{s}, \psi}$ into a sample of $\code{H}_{i_{0}}$ if the guess is correct, and into a sample of $\code{H}_{i_{0}+1}$ if the guess is incorrect. \noindent {\bf Transformation:} Let $\vec{g}_{i_{0}+1}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$. It will be our guess for $\widehat{\vec{s}}\stackrel{\textrm{def}}{=}\word{s}\mod \goth{P}_{i_{0}+1}$. Let us consider now the following operations \begin{itemize} \item Take $\word{g}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ such that $\word{g}\equiv \vec{g}_{i_{0}+1}\mod \goth{P}_{i_{0}+1}$ and $\word{g}\equiv \vec{0}\mod \goth{P}_{j}$ for $j\neq i_{0}+1$. \item Sample $\vec{h}_{j}\leftarrow {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{j}}$ for $1\le j\le i_{0}$ and take $\word{h}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ such that $\word{h}\equiv \vec{h}_{j}\mod \goth{P}_{j}$ for $1\le j\le i_{0}$ and $\word{h}\equiv \vec{0}\mod \goth{P}_{j}$ for $j\ge i_{0}+1$. \item Sample $\vec{v}_{i_{0}+1}\leftarrow {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$ and take $\word{v}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ such that $\word{v}\equiv \vec{v}_{i_{0}+1}\mod \goth{P}_{i_{0}+1}$ and $\word{v}\equiv \vec{0}\mod \goth{P}_{j}$ for $j\neq i_{0}+1$. \end{itemize} All those operations can be done via the CRT. Now, for each sample $(\word{a}, \word{b}\stackrel{\textrm{def}}{=} \word{a}\word{s} + \word{e})\leftarrow\ffd{\word{s},\psi}$, define $(\word{a}', \word{b}')$ with \[ \word{a}' \stackrel{\textrm{def}}{=} \word{a} + \word{v} \quad\mbox{and}\quad \word{b}' \stackrel{\textrm{def}}{=} \word{b} + \word{h} +\word{v}\word{g}. \] Note that for each sample $(\word{a}, \word{b})$, the corresponding $\word{a}'$ is still uniformly distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$ and $\word{b}'~=~\word{a}'\word{s} + \word{e} + \word{h}'$ with $\word{h}' \stackrel{\textrm{def}}{=} \word{h} + (\word{g}-\word{s})\word{v}$. Furthermore, $\vec{h}$ verifies: \[\left\lbrace \begin{array}{ll} \word{h}' \equiv \vec{h}_{j}& \mod \goth{P}_{j} \text{ for } j\le i_{0} \\ \word{h}' \equiv (\vec{g}_{i_{0}+1} - \widehat{\vec{s}}) \vec{v}_{i_{0}+1}\ & \mod \goth{P}_{i_{0}+1} \\ \word{h}' \equiv \vec{0} & \mod \goth{P}_{j} \text{ for } j > i_{0}+1. \\ \end{array}\right. \] In particular, $\word{h}'$ is uniformly distributed modulo $\goth{P}_{j}$ for $j\le i_{0}$ and $\vec{0}$ modulo $\goth{P}_{j}$ for $j > i_{0}+1$. Now, if the guess is correct, meaning $\vec{g}_{i_{0}+1}=\widehat{\vec{s}}$, then $\word{h}'\equiv 0\mod \goth{P}_{i_{0}+1}$, hence $(\word{a}',\word{b}')$ is distributed according to $\code{H}_{i_{0}}$. On the other hand, if the guess is incorrect, $(\vec{g}_{i_{0}+1}-\widehat{\vec{s}})\neq \vec{0}$ in ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$. But $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ is a Dedekind domain and $\goth{P}_{i_{0}+1}$ is a prime ideal, therefore it is also maximal and ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$ is in fact a {\em field}. Since $\vec{v}_{i_{0}+1}$ is uniformly distributed in ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}_{i_{0}+1}}$, so is $(\vec{g}_{i_{0}+1}-\widehat{\vec{s}}) \vec{v}_{i_{0}+1}$. In particular, $\word{h}'$ is also uniformly distributed modulo $\goth{P}_{i_{0}+1}$. Hence, $(\word{a}',\word{b}')$ is distributed according to $\code{H}_{i_{0}+1}$. The algorithm $\code{B}$ proceeds as follows: for each $(\word{a},\word{b})\leftarrow\ffd{\word{s}, \psi}$, it applies the previous transformation to get a sample $(\word{a}', \word{b}')$, and then uses the distinguisher $\code{A}$. Repeating the procedure $m$ times (for each guess $\vec{g}_{i_{0}+1}$), for $m$ large enough, and doing a majority voting allows to recover $\widehat{\word{s}}$ with overwhelming probability. More precisely, it relies on the use of the Chernoff bound. \begin{proposition}[Chernoff bound] Let $(X_{j})_{1\le j\le m}$ be $m$ independent Bernouilli random variables with parameter $1/2+\delta$. Let $X \stackrel{\textrm{def}}{=} \sum_{j=1}^{m}X_{j}$. Then \[ \mathbb{P}\left(X \le \frac{m}{2}\right) \le e^{-2m\delta^{2}}. \] \end{proposition} Consider $m$ trials of the guess and search procedure, and let $X_{j}$ denote the indicator random variable that the $j$-th run returns the correct value. Since $\code{A}$ has distinguishing advantage $\delta$, $X_{j}$ is a Bernouilli with parameter $\frac{1}{2}+\delta$. After $m$ trials, the procedure fails if and only if more than $m/2$ runs are wrong. By Chernoff bound, the probability that it happens is less than $e^{-2m\delta^{2}}$. Therefore, by choosing $m\ge \ln(\frac{1}{\mu})\frac{1}{2\delta^{2}}$, the above procedure returns the correct guess with probability at least $1-\mu$. Therefore if one sets $\mu = 2^{-\Theta(n)}$ (to get an overwhelming probability of success), it is enough to choose $m$ as $\Theta\left( \frac{n}{\delta^{2}}\right)$. It enables to check if our guess $\widehat{\vec{s}} = \vec{s} \mod \goth{P}_{i_{0}+1}$ is correct or not with overwhelming probability. To recover $\vec{s} \mod \goth{P}_{i_{0}+1}$ it remains to try all the possible guesses $\widehat{\vec{s}} \in {\mathcal{O}_{K}}/{\goth{P}_{i_{0}+1}}$. But the size of ${\mathcal{O}_{K}}/{\goth{P}_{i_{0}+1}}$ is given by $q^{f\deg(Q)}$, which yields the claimed time complexity. \end{proof} {\bf \noindent Step 4: Action of the Galois group.} Until Step $3$, we are able to recover the secret $\word{s}$ modulo one of the factors. In order to recover the full secret, we use the Galois group $G\stackrel{\textrm{def}}{=} {\rm Gal}({K}/{\mathbb{F}_q(T)})$. This last part is {\em crucial} for the reduction to work. Recall that $G$ acts transitively on the set of prime ideals above $\mathfrak{p}$, {\em i.e. } for every $i\neq j$, there exists $\sigma\in G$ such that $\sigma\left( \goth{P}_{i} \right) = \goth{P}_{j}$. \begin{lemma} Fix $\word{s}\in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. Let $1\le i\le r$ and let $\code{A}$ be an algorithm running in time $t$, and recovering $\word{s}\mod \goth{P}_{i}$ by making queries to an oracle for $\ffd{\word{s}, \psi}$. Then there exists an algorithm $\code{B}$ running in time $O\left( t\times r \right)$ that recovers the full secret $\word{s}$. \end{lemma} \begin{proof} We build $\code{B}$ as follows: for every factor $\goth{P}_{j}$ of $\goth{P}$, it chooses $\sigma\in{\rm Gal}({K}/{\mathbb{F}_q(T)})$ such that $\sigma(\goth{P}_{j}) = \goth{P}_{i}$. Then, for each sample $(\word{a}, \word{b})\leftarrow \ffd{\word{s}, \psi}$, it runs $\code{A}$ on the input $(\sigma(\word{a}), \sigma(\word{b}))$ to recover an element $\vec{s}_{j}$ and stores $\sigma^{-1}(\vec{s}_{j})$. Note that ${\rm Gal}({K}/{\mathbb{F}_q(T)})$ keeps the uniform distribution over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. In particular, for every sample $(\word{a}, \word{b})\leftarrow \ffd{\word{s},\psi}$, the corresponding $\sigma(\word{a})$ is also uniformly distributed over ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}}/{\goth{P}}$. Furthermore, $\word{b} = \word{a} \word{s} + \word{e}$ with $\word{e} \leftarrow \psi$. Therefore, $\sigma(\word{b}) = \sigma(\word{a}) \sigma(\word{s}) + \sigma(\word{e})$. But $\psi$ is Galois invariant by assumption, and hence $\sigma(\word{e})$ is also distributed according to $\psi$. In particular, $(\sigma(\word{a}), \sigma(\word{b}))$ is a valid sample of $\ffd{\sigma(\word{s}), \psi}$. Now, our algorithm $\code{A}$ is able to recover $\vec{s}_{j} \stackrel{\textrm{def}}{=} \sigma(\word{s}) \mod \goth{P}_{i}$ in time $t$, and $$\sigma^{-1}(\vec{s}_{j}) = \sigma^{-1}\left(\sigma(\word{s}) \mod \goth{P}_{i}\right) = \word{s} \mod \sigma^{-1}\left(\goth{P}_{i}\right) = \word{s} \mod \goth{P}_{j}.$$ Therefore, we are able to recover $\word{s} \mod \goth{P}_{j}$ for any $1 \leq j \leq r$. To compute the full secret $\vec{s}$ it remains to use the Chinese Remainder Theorem. The running time of this full procedure is given by a $O(t\times r)$ which concludes the proof. \end{proof} } \section{Cyclotomic function fields and the Carlitz module} \label{sec:carlitz} In Section \ref{sec:FFDP}, we introduced the generic problem $\mathsf{FF}$--$\mathsf{DP}${} and noticed that our search to decision reduction\iftoggle{llncs}{}{ given in Section \ref{sec:StD}} needed Galois function fields. In \cite{LPR10}, it was proposed to use cyclotomic number fields to instantiate the Ring--$\mathsf{LWE}${} problem. Here, we propose to instantiate $\mathsf{FF}$--$\mathsf{DP}${} with the function field analogue, namely {\em Carlitz} extensions. We give a self contained presentation of the theory of Carlitz extensions. The interested reader can refer to \cite[ch. 12]{R02}, \cite{NX01} and the excellent survey \cite{Conrad-Carlitz} for further reference. Carlitz extensions are function fields analogues of the cyclotomic extensions of $\mathbb{Q}$. A dictionary summarizing the similarities is given in Table \ref{fig:cyclotomic_carlitz_analogy}. These extensions were discovered by Carlitz in the late 1930s but the analogy was not well known until the work of his student Hayes who studied them in \cite{H74} to give an explicit construction of the abelian extensions of the rational function field $\mathbb{F}_q(T)$ and prove an analogue of the usual Kronecker-Webber theorem which states that any abelian extension of $\mathbb{Q}$ are subfields of cyclotomic number fields. This result was generalized in the following years with the work of Drinfeld and Goss to yield a complete solution to Hilbert twelfth problem in the function field setting. In the number field setting, such an explicit construction is only known for abelian extensions of $\mathbb{Q}$ (cyclotomic extensions), imaginary quadratic number fields (via the theory of elliptic curves with complex multiplication). The first idea that comes to mind when one wants to build cyclotomic function fields is to adjoin roots of unity to the field $\mathbb{F}_q(T)$. However, roots of unity are already {\em algebraic} over $\mathbb{F}_q$. In other words, adding them only yields so--called {\em extensions of constants}. \begin{example} Let $\zeta_{n}$ be an $n$--th root of unity in $\mathbb{F}_q(T)$. Note that it belongs to some {\em finite} extension of $\mathbb{F}_q$. Let $\mathbb{F}_{q^m}$ be the extension of $\mathbb{F}_q$ of minimal degree such that $\zeta_{n}\in \mathbb{F}_{q^m}$ (it can be $\mathbb{F}_q$ itself). Then \[ \mathbb{F}_q(T)[\zeta_{n}] = \mathbb{F}_{q^m}(T), \] and the field of constants of $\mathbb{F}_q(T)[\zeta_{n}]$ is $\mathbb{F}_{q^m}$. \end{example} However, in our reduction setting, such extensions will only increase the size of the search space in Step~$3$. More precisely, if $K$ is an algebraic extension of $\mathbb{F}_q(T)$, the constant field of $K$ is always a subfield of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$ for any prime ideal $\goth{P}$ of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$. But recall that in our search to decision reduction, we need to do an exhaustive search in this quotient $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}$, so we need it to be as small as possible. Henceforth, we cannot afford constant field extensions. For Carlitz extensions, this will be ensured by Theorem~\ref{thm:Carlitz_constant}. \iftoggle{llncs}{ }{ \begin{example} As a matter of example, consider the polynomial $T^{2}+T+1$ over $\F2$. It is irreducible. Let $\zeta_{3}\in\F4$ be one of its roots. It is a cube root of $1$. Now, consider the field extension $K \stackrel{\textrm{def}}{=} \F2(T)(\zeta_{3}) = \F4(T)$ and let $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ be the integral closure of $\F2[T]$ in $K$. The prime ideal $\mathfrak{p}~\stackrel{\textrm{def}}{=}~(T^{2}+T+1)$ of $\F2[T]$ splits into two prime ideals $\goth{P}_{1}$ and $\goth{P}_{2}$ in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$. But $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}_{1} =~\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}_{2} =~\F4 =~\F2[T]/\goth{p}$ and we do not win anything by considering the extension $K/\F2(T)$. \end{example} } \subsection{Roots of unity and torsion} As mentioned in the beginning of this section, it is not sufficient to add roots of unity. One has to go deeper into the algebraic structure that is adjoined to $\mathbb{Q}$. Indeed, the set of all $m$--th roots of unity, denoted by $\mu_{m} \subset \mathbb{C}$, turns out to be an abelian group under multiplication. Moreover, $\mu_{m}$ is in fact {\em cyclic}, generated by any {\em primitive} root of unity. In commutative algebra, abelian groups are {\em $\mathbb{Z}$-modules}. Here the action of $\mathbb{Z}$ is given by exponentiation: $n\in\mathbb{Z}$ acts on $\zeta\in\mu_{m}$ by $n\cdot \zeta \stackrel{\textrm{def}}{=} \zeta^{n}$. This action of $\mathbb{Z}$ can in fact be extended to all $\overline{\mathbb{Q}}^{\times}$. When working with modules over a ring, it is very natural to consider the {\em torsion elements}, {\em i.e. } elements of the module that are annihilated by an element of the ring. The torsion elements in the $\mathbb{Z}$--module $\overline{\mathbb{Q}}^{\times}$ are the $\zeta\in\overline{\mathbb{Q}}^{\times}$ such that $\zeta^{m}=1$ for some $m>0$; these are precisely the roots of unity. In other words, the cyclotomic number fields are obtained by adjoining to $\mathbb{Q}$ torsions elements of the $\mathbb{Z}$--module $\overline{\mathbb{Q}}^{\times}$. Under the analogy summed up in Table \ref{fig:ff_analogy}, replacing $\mathbb{Z}$ by $\mathbb{F}_q[T]$ and $\mathbb{Q}$ by $\mathbb{F}_q(T)$, we would like to consider some $\mathbb{F}_q[T]$--module and adjoin to $\mathbb{F}_q(T)$ the torsion elements. Note that $\mathbb{F}_q[T]$--modules are in particular $\mathbb{F}_q$--vector spaces\iftoggle{llncs}{, hence the action of $\mathbb{F}_q[T]$ should be linear.}{. The natural candidate could be $\overline{\mathbb{F}_q(T)}$ with $\mathbb{F}_q[T]$ acting by multiplication. However, the torsion elements are not very interesting. Indeed if there is some $f \in \overline{\mathbb{F}_q(T)}$ and some $a \in \mathbb{F}_q[T]\setminus \{0\}$ such that $af =0$ then, $f = 0$. Therefore, for the usual action by multiplication, only $0$ is a torsion element. Thus, we need to define {\em another} $\mathbb{F}_q[T]$--module structure, in the same way that we did not consider the natural action of $\mathbb{Z}$ by multiplication.} This new module structure can be defined using so called {\em Carlitz polynomials}: for each polynomial $M\in\mathbb{F}_q[T]$, we define its Carlitz polynomial $[M](X)$ as a polynomial in $X$ with coefficients in $\mathbb{F}_q[T]$, and $M\in\mathbb{F}_q[T]$ will act on $\alpha\in\overline{\mathbb{F}_q(T)}$ by $M\cdot \alpha \stackrel{\textrm{def}}{=} [M](\alpha)$\iftoggle{llncs}{ with $[M](\alpha+\beta) = [M](\alpha)+[M](\beta)$.}{. In the literature, the notation $\alpha^{M}$ can also be found to emphasize the analogy with the action of $\mathbb{Z}$ by exponentiation, but it can be confusing. } \iftoggle{llncs}{}{In the same way that the action of $\mathbb{Z}$ was multiplicative: $(\alpha\beta)^{n} = \alpha^{n}\beta^{n}$, the action of $\mathbb{F}_q[T]$ will be {\em additive}: $[M](\alpha + \beta) = [M](\alpha) + [M](\beta)$.} In other words, $[M](X)$ should be an {\em additive polynomial}. In positive characteristic this can easily be achieved by considering $q$--polynomials, {\em i.e. } polynomials whose monomials are only $q$--th powers of $X$, namely of the form \[ P(X) = p_{0}X + p_{1}X^{q} + \cdots + p_{r}X^{q^{r}}. \] \iftoggle{llncs}{ }{ \begin{remark} $q$--polynomials with coefficients in some finite field $\mathbb{F}_{q^m}$ are also used in coding theory to build so called {\em rank metric codes}. However, here we consider $q$--polynomials with coefficients in $\mathbb{F}_q[T]$. \end{remark} } \subsection{Carlitz polynomials} The definition of Carlitz polynomial will proceed by induction and linearity. Define $[1](X) \stackrel{\textrm{def}}{=} X$ and $[T](X) \stackrel{\textrm{def}}{=} X^{q} +TX$. For $n\ge 2$, define \[ [T^{n}](X) \stackrel{\textrm{def}}{=} [T]([T^{n-1}](X)) = [T^{n-1}](X)^{q} + T[T^{n-1}](X). \] \vspace{\baselineskip} \noindent Then, for a polynomial $M = \sum_{i=0}^{n}a_{i}T^{i}\in\mathbb{F}_q[T]$, define $[M](X)$ by forcing $\mathbb{F}_q$--linearity: \[ [M](X) \stackrel{\textrm{def}}{=} \sum_{i=0}^{n}a_{i}[T^{i}](X). \] \begin{example}We have, \begin{itemize}[label=\textbullet] \item $[T^{2}](X) = [T](X^{q} + TX) = X^{q^{2}}+(T^{q} + T)X^{q} + T^{2}X$ \item $[T^{2}+T+1](X) = [T^{2}](X) + [T](X) + [1](X) = X^{q^{2}}+(T^{q}+T+1)X^{q} + (T^{2}+T+1)X$ \end{itemize} \end{example} By construction, Carlitz polynomials are additive polynomials, and $\mathbb{F}_q$--linear. Furthermore, for two polynomials $M, N\in\mathbb{F}_q[T]$, $[MN](X) = [M]([N](X)) = [N]([M](X))$. In particular, Carlitz polynomials commute with each other under composition law, which is not the case in general for $q$--polynomials. \subsection{Carlitz module} Endowed with this $\mathbb{F}_q[T]$--module structure, $\overline{\mathbb{F}_q(T)}$ is called the {\em Carlitz module}. \begin{definition}For $M\in\mathbb{F}_q[T]$, $M\neq 0$, let $\Lambda_{M} \stackrel{\textrm{def}}{=} \{\lambda \in \overline{\mathbb{F}_q(T)} \mid [M](\lambda) = 0\}$. This is the module of $M$--torsion of the Carlitz module. \end{definition} \begin{example}\label{ex:LambdaT} $\Lambda_{T} = \{\lambda \in \overline{\mathbb{F}_q(T)} \mid \lambda^{q} + T\lambda = 0\} = \{0\} \cup \{\lambda \mid \lambda^{q-1} = -T\}$. \end{example} In the same way that $\mu_{m}$ is an abelian group ({\em i.e. } a $\mathbb{Z}$--module), note that $\Lambda_{M}$ is also a submodule of the Carlitz module: for $\lambda\in\Lambda_{M}$ and $A\in \mathbb{F}_q[T]$, $[A](\lambda) \in \Lambda_{M}$. In particular, $\Lambda_{M}$ is an $\mathbb{F}_q$--vector space. \begin{example} The module $\Lambda_{T}$ defined in Example~\ref{ex:LambdaT} is an $\mathbb{F}_q$--vector space of dimension $1$. In particular, for $\lambda\in\Lambda_{T}$, and $A\in\mathbb{F}_q[T]$, $[A](\lambda)$ must be a multiple of $\lambda$. In fact the Carlitz action of $A$ on $\lambda$ is through the constant term of $A$: writing $A = TB + A(0)$ we have \[ [A](\lambda) = [TB + A(0)](\lambda) = [B](\underbrace{[T](\lambda)}_{=0}) + A(0)[1](\lambda) = A(0)\lambda. \] \end{example} More generally, even if in general $\Lambda_{M}$ is not of dimension $1$ over $\mathbb{F}_q$, it is always a {\em cyclic} $\mathbb{F}_q[T]$--module: as an $\mathbb{F}_q[T]$--module it can be generated by only one element. This is specified in the following theorem. \begin{theorem}[{\cite[Lemma 3.2.2]{NX01}}] There exists $\lambda_{0}\in\Lambda_{M}$ such that $\Lambda_{M} = \{ [A](\lambda_{0}) \mid A\in\mathbb{F}_q[T]/(M) \}$ and the generators of $\Lambda_{M}$ are the $[A](\lambda_{0})$ for all $A$ prime to $M$. The choice of a generator yields a non canonical isomorphism $\Lambda_{M}\simeq \mathbb{F}_q[T]/(M)$ as $\mathbb{F}_q[T]$--modules. \end{theorem} \begin{remark} The previous theorem needs to be related to the cyclotomic case: given the choice of a primitive $m$--th root of unity, there is a group isomorphism between $\mu_m$ and $\mathbb{Z}/m\mathbb{Z}$. Moreover all the $m$--th roots of unity are of the form $\zeta^{k}$ for $k\in\llbracket 0,m-1\rrbracket$ and the generators of $\mu_{m}$ are the $\zeta^{k}$ for $k$ prime to $m$. \end{remark} \subsection{Carlitz extensions} Recall that the cyclotomic number fields are obtained as extensions of $\mathbb{Q}$ generated by the elements of $\mu_m$. In the similar fashion, for a polynomial $M\in\mathbb{F}_q[T]$, let \[ K_{M} \stackrel{\textrm{def}}{=} \mathbb{F}_q(T)(\Lambda_{M}) = \mathbb{F}_q(T)(\lambda_{M}), \] where $\lambda_{M}$ is a generator of $\Lambda_{M}$. One of the most important fact about the cyclotomic number field $\mathbb{Q}(\zeta_{m})$ is that it is a finite Galois extension of $\mathbb{Q}$, with Galois group isomorphic to $(\mathbb{Z}/m\mathbb{Z})^{\times}$. There is an analogue statement for the Carlitz extensions. \begin{theorem}[{\cite[Th.~3.2.6]{NX01}}]\label{thm:Carlitz_Galois} Let $M\in\mathbb{F}_q[T]$, $M\neq 0$. Then $K_{M}$ is a finite Galois extension of $\mathbb{F}_q(T)$, with Galois group isomorphic to $(\mathbb{F}_q[T]/(M))^{\times}$. The isomorphism is given by \[ \map{(\mathbb{F}_q[T]/(M))^{\times}}{{\rm Gal}(K_{M}/\mathbb{F}_q(T))}{A}{\sigma_{A},} \] where $\sigma_{A}$ is completely determined by $\sigma_{A}(\lambda_{M}) = [A](\lambda_{M})$. \end{theorem} \begin{remark} In particular, Carlitz extensions are {\em abelian}. \end{remark} Another important fact about cyclotomic extensions is the simple description of their ring of integers. Namely, for $K = \mathbb{Q}(\zeta_{m})$, we have $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = \mathbb{Z}[\zeta_{m}] = \mathbb{Z}[X]/(\Phi_{m}(X))$ where $\Phi_{m}$ denotes the $m$--th cyclotomic polynomial. This property also holds for Carlitz extensions. \begin{theorem}[{\cite[Th.~2.9]{R02}}] Let $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$ be the integral closure of $\mathbb{F}_q[T]$ in $K_{M}$. Then $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M} =~\mathbb{F}_q[T][\lambda_{M}]$. In particular, let $P(T, X) \in \mathbb{F}_q[T][X]$ be the minimal polynomial of $\lambda_{M}$. Then, \[ K_{M} = \fract{\mathbb{F}_q(T)[X]}{(P(T, X))} \quad \text{and} \quad \mathcal{O}} \newcommand{\II}{\mathcal{I}_{M} = \fract{\mathbb{F}_q[T][X]}{(P(T, X))}. \] \end{theorem} \begin{example}\label{ex:LambdaTbis} Reconsider Example~\ref{ex:LambdaT} and the module $\Lambda_{T} = \{0\} \cup \{ \lambda \mid \lambda^{q-1} = -T\}$. The polynomial $X^{q-1}+T$ is Eisenstein in $(T)$ and therefore is irreducible. Hence, \[ K_{T} = \fract{\mathbb{F}_q(T)[X]}{(X^{q-1}+T)}. \] Moreover it is Galois, with Galois group $(\mathbb{F}_q[T]/(T))^{\times} \simeq \mathbb{F}_q^{\times}$. A non-zero element $a\in\mathbb{F}_q^{\times}$ will act on $f(T,X)\in K_{T}$ by \[ a\cdot f(T, X) \stackrel{\textrm{def}}{=} f(T, [a](X)) = f(T, aX). \] The integral closure of $\mathbb{F}_q[T]$ in $K_{T}$ is \[ \mathcal{O}} \newcommand{\II}{\mathcal{I}_{T} \stackrel{\textrm{def}}{=} \fract{\mathbb{F}_q[T][X]}{(X^{q-1}+T)} \] and \begin{equation}\label{eq:O_T/(T+1)} \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T}}{((T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T})} = \fract{\mathbb{F}_q[T][X]}{(T+1, X^{q-1}+T)} = \fract{\mathbb{F}_q[X]}{(X^{q-1}-1)}. \end{equation} \end{example} Finally, the following theorem characterizes the splitting behaviour of primes in Carlitz extensions. A very similar result holds for cyclotomic extensions. \begin{theorem}[{\cite[Th.~12.10]{R02}}]\label{thm:carlitz_splitting} Let $M\in\mathbb{F}_q[T]$, $M\neq 0$, and let $Q\in\mathbb{F}_q[T]$ be a monic, irreducible polynomial. Consider the Carlitz extension $K_{M}$ and let $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$ denote its ring of integers. Then, \begin{itemize}[label=\textbullet] \item If $Q$ divides $M$, then $Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$ is totally ramified. \item Otherwise, let $f$ be the smallest integer $f$ such that $Q^{f} \equiv 1 \mod M$. Then $Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$ is unramified and has inertia degree $f$. In particular, $Q$ splits completely if and only if $Q\equiv 1 \mod M$. \end{itemize} \end{theorem} Note that in Ring--$\mathsf{LWE}${}, the prime modulus $q$ is often chosen such that $q\equiv 1 \mod m$ so that it splits completely in the cyclotomic extension $\mathbb{Q}(\zeta_{m})$. \begin{example} In the previous example, $T+1 \equiv 1 \mod T$ and therefore $(T+1)$ splits completely in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T}$. Indeed, \[ \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T}}{((T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T})} = \fract{\mathbb{F}_q[X]}{(X^{q-1}-1)} = \prod_{\alpha \in \mathbb{F}_q^{\times}} \fract{\mathbb{F}_q[X]}{(X-\alpha)} \] is a product of $q-1$ copies of $\mathbb{F}_q$. \end{example} It is crucial for the applications that the constant field of $K$ be not too big because, in the search--to--decision reduction, it determines the search space in Step $3$ of the proof of Theorem~\ref{thm:main}. The following non-trivial theorem gives the field of constants of Carlitz extensions. \begin{theorem}[{\cite[Cor.~of ~Th.~12.14]{R02}}]\label{thm:Carlitz_constant} Let $M\in\mathbb{F}_q[T]$, $M\neq 0$. Then $\mathbb{F}_q$ is the full {\em constant field} of $K_{M}$. \end{theorem} The similarities between Carlitz function fields and cyclotomic number fields are summarized in Table \ref{fig:cyclotomic_carlitz_analogy}. \begin{table}[!ht] \centering \[ \begin{array}{|c|c|} \hline \mathbb{Q} & \mathbb{F}_q(T) \\ \mathbb{Z} & \mathbb{F}_q[T] \\ \text{Prime numbers } q \in \mathbb{Z} & \text{Irreducible polynomials } Q\in\mathbb{F}_q[T]\\ & \\ \mu_{m} = \ideal{\zeta} \simeq \mathbb{Z}/m\mathbb{Z} \text{ (groups) }& \Lambda_{M} =\ideal{\lambda}\simeq \mathbb{F}_q[T]/(M) \text{ (modules) }\\ & \\ d \mid m \Leftrightarrow \mu_{d} \subset \mu_{m} \text{ (subgroups) } & D\mid M \Leftrightarrow \Lambda_{D} \subset \Lambda_{M} \text{ (submodules) }\\ & \\ a \equiv b \mod m \Rightarrow \zeta^{a} = \zeta^{b} & A \equiv B \mod M \Rightarrow [A](\lambda) = [B](\lambda)\\ & \\ K = \mathbb{Q}[\zeta] & K = \mathbb{F}_q(T)[\lambda] \\ \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = \mathbb{Z}[\zeta] & \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = \mathbb{F}_q[T][\lambda] \\ & \\ {\rm Gal}(K/\mathbb{Q}) \simeq (\mathbb{Z}/m\mathbb{Z})^{\times} & {\rm Gal}(K/\mathbb{F}_q(T))\simeq (\mathbb{F}_q[T]/(M))^{\times}\\ & \\ \textbf{Cyclotomic} & \textbf{Carlitz}\\ \hline \end{array} \] \caption{\label{fig:cyclotomic_carlitz_analogy} Analogies between cyclotomic and Carlitz} \end{table} \section{Applications}\label{sec:applications} In the current section, we present two applications of our proof techniques. It provides search to decision reductions to generic problems whose hardness assumption has been used to assess the security of some cryptographic designs. The first application concerns Oblivious Linear Evaluation (OLE) which is a crucial primitive for secure multi-party computation. The second one is an authentication protocol called \textsc{Lapin}{}. Both designs rely on the hardness of variants of the so-called Learning Parity with Noise ($\mathsf{LPN}${}) problem. \subsection{$\mathsf{LPN}${} and its structured variants} Let us start this subsection by the definitions of the distribution that is involved in the $\mathsf{LPN}${} problem. \begin{definition}[Learning Parity with Noise ($\mathsf{LPN}${}) distribution] Let $k$ be a positive integer, $\word{s}\in \mathbb{F}_q^k$ be a uniformly distributed vector and $p \in [0, \frac{1}{2})$. A sample $(\vec{a},b)\in\mathbb{F}_q^{k} \times \mathbb{F}_q$ is distributed according to the $\mathsf{LPN}${} distribution with secret $\vec{s}$ if \begin{itemize}[label=\textbullet] \item $\vec{a}$ is uniformly distributed over $\mathbb{F}_q^{k}$; \item $b \stackrel{\textrm{def}}{=} \langle \vec{a},\vec{s} \rangle + e$ where $\inner{ \cdot\ \! , \cdot }$ denotes the canonical inner product over $\mathbb{F}_q^k$ and $e$ is a $q$--ary Bernouilli random variable with parameter $p$, namely $\mathbb{P}(e=0) = 1-p$ and $\mathbb{P}(e=a) = \frac{p}{q-1}$ for $a\in\mathbb{F}_q^{\times}$. \end{itemize} A sample drawn according to this distribution will be denoted $ (\word{a}, \inner{ \word{a}, \word{s} } + e) \leftarrow \DLPN{\word{s}}{p}$. \end{definition} \begin{remark}\label{rem:q-ary Bernouilli} This definition is a generalization of the usual $\mathsf{LPN}${} distribution defined over $\F2$. In this situation, the error distribution is a usual Bernouilli: $\mathbb{P}(e=0) = 1 - p$ and $\mathbb{P}(e=1) = p$. \end{remark} \iftoggle{llncs}{}{ \begin{remark}\label{rem:ntuple_LPN} Sometimes in the literature, the distribution is directly defined for $n$ samples, leading to $(\mat{G}, \vec{s}\cdot \mat{G} + \word{e})$ where $\mat{G}$ is drawn uniformly at random over the space $\mathbb{F}_q^{k \times n}$ of $k \times n$ matrices whose coefficients lie in $\mathbb{F}_q$ and $\word{e} \stackrel{\textrm{def}}{=} (e_1, \dots, e_n)$ where the $e_i$'s are independent Bernouilli random variables with parameter $p$. \end{remark} The security of many cryptosystems in the literature rests on the LPN assumption which informally asserts that it is hard to distinguish a sample $(\word{a}, \inner{ \word{a}, \word{s} } + e) \leftarrow \DLPN{\word{s}}{p}$ from a sample $(\word{a}, t)$ where both $\word{a}$ and $t$ are drawn uniformly at random. \begin{remark}\label{rem:LPN=decoding} Note that, according to Remark~\ref{rem:ntuple_LPN}, when considering a fixed number $n$ of samples, the LPN assumption is nothing but the decision version of the decoding problem, namely distinguishing noisy codewords of a random code from uniformly random vectors. \end{remark} } Similarly to the $\mathsf{LWE}${} problem, structured versions of $\mathsf{LPN}${} have been defined (\cite{HKLPP12,DP12,BCGIKS20}). \begin{definition}[Ring--$\mathsf{LPN}${} distribution] Fix a positive integer $r$, a public polynomial $f(X) \in~\mathbb{F}_q [X]$ of degree $r$ and $\vec{s} \in \mathbb{F}_q[X]/(f(X))$ be a uniformly distributed polynomial. A sample $(\vec{a}, \vec{b})$ is distributed according to the $\mathsf{RLPN}${} distribution with secret $\vec{s}$ if \begin{itemize}[label=\textbullet] \item $\vec{a}$ is drawn uniformly at random over $\mathbb{F}_q[X]/(f(X))$; \item $\vec{b} \stackrel{\textrm{def}}{=} \vec{a}\vec{s}+\vec{e}$ where $\vec{e} \stackrel{\textrm{def}}{=} e_0+ e_1X + \cdots + e_{r - 1}X^{r - 1} \in \mathbb{F}_q[X]/(f(X))$ has coefficients $e_{i}$'s which are independent $q$--ary Bernouilli random variables with parameter $p$. \end{itemize} A sample drawn according to this distribution will be denoted $ (\vec{a},\vec{a}\vec{s}+\vec{e}) \leftarrow \DRLPN{\vec{s}}{p}$. \end{definition} Note that the map \[ \map{\fract{\mathbb{F}_q[X]}{(f(X))}}{\fract{\mathbb{F}_q[X]}{(f(X))}}{\vec{m}(X)}{\vec{a}(X)\vec{m}(X) \mod f(X)} \] can be represented in the canonical basis by an $r \times r$ matrix $\mat{A}$. Using this point of view, one sample of $\mathsf{RLPN}${} can be regarded as $r$ specific samples of $\mathsf{LPN}${}. \iftoggle{llncs}{\ }{ \begin{definition}[Module--$\mathsf{LPN}${} distribution] Fix positive integers $r$ and $d$, a public polynomial $f(X) \in \mathbb{F}_q [X]$ of degree $r$ and $\word{s}$ be uniformly distributed over $(\mathbb{F}_q[X]/(f(X)))^{d}$. A sample $(\word{a}, \word{b})$ is distributed according to the $\mathsf{MLPN}${} distribution with secrets $\word{s}$ if \begin{itemize} \item $\word{a}$ is drawn uniformly at random over $(\mathbb{F}_q[X]/(f(X)))^{d}$; \item $\vec{b} \stackrel{\textrm{def}}{=} \inner{\word{a}, \word{s}} + \vec{e} = \sum_{i=1}^{d}\vec{a}_{i}\vec{s}_{i}+\vec{e}$, where $\vec{e} \stackrel{\textrm{def}}{=} e_0+ e_1X + \cdots + e_{r - 1}X^{r - 1} \in \mathbb{F}_q[X]/(f(X))$ has coefficients $e_{i}$'s which are independent Bernouilli random variables with parameter $p$. \end{itemize} A sample drawn according to this distribution will be denoted $ (\word{a},\vec{b}) \leftarrow \DMLPN{\vec{s}}{p}$ \end{definition} In the above definitions, the noise distribution is chosen independently on each coefficient of $\vec{e}(X)\in\mathbb{F}_q[X]/(f(X))$. One can also consider the situation where the coefficients of $\vec{e}(X)$ are chosen to form a vector of $\mathbb{F}_q^{r}$ of fixed Hamming weight $t$. This point of view is closer to the usual decoding problem, and is the one adopted in \cite{BCGIKS20}. To conclude, note that the choice of the noise in the Ring-- and Module--$\mathsf{LPN}${} distribution is made relatively to the canonical basis ${(X^{i})}_{0\leq i \leq r-1}$ since it seems to be the most natural one. However, one could have made another choice. This will be discussed in the sequel. } \iftoggle{llncs}{}{ \subsection{Relation with decoding problems} According to Remark~\ref{rem:LPN=decoding}, distinguishing $n$ samples of an $\mathsf{LPN}${} distribution $\DLPN{\vec{s}}{p}$ from the uniform distribution is equivalent to distinguishing noisy codewords of a known random code from uniformly random words. It can be regarded as the decision version of the decoding problem for a code of fixed dimension (here the length of the secret $\vec{s}$) and whose length $n$ goes to infinity and hence whose rate goes to zero. Similarly, distinguishing samples from a distribution $\DRLPN{\word{s}}{p}$ and a uniform one is equivalent to the decision version of the decoding problem of structured codes whose basis is block-wise defined as \[ \begin{pmatrix} \mat{A}_1 & \cdots & \mat{A}_m \end{pmatrix} \] where, for any $i \in \llbracket 1,n\rrbracket$, $\mat{A}_i$ is the matrix representation in the canonical basis of $\mathbb{F}_q[X]/(f(X))$ of the multiplication by some random element $\word{a}_i \in \mathbb{F}_q[X]/(f(X))$. In particular, considering the case $f(X) = X^{\ell} - 1$, we recover, the decoding problem for $\ell$--quasi--cyclic codes. \newline } {\bf \noindent Search to decision.} Here we present search to decision reductions in two different settings corresponding to two choices of the modulus $f(X)$ in the Ring--$\mathsf{LPN}${} problem. Both have been used in the literature for specific applications that are quickly recalled. \newline {\bf \noindent A $q$--ary version of \textup{Ring--LPN} with a totally split modulus $f$.} In \cite{BCGIKS20}, the authors introduce Ring--$\mathsf{LPN}${} over the finite field $\mathbb{F}_q$ and with a modulus $f$ which is totally split, {{\em i.e. }} has distinct roots, all living in the ground field $\mathbb{F}_q$. \newline {\bf \noindent Motivation: Oblivious Linear Evaluations for secure Multi Party Computation (MPC).} A crucial objective in modern secure MPC is to be able to generate efficiently many random pairs $(u, r), (v, s)$ such that $u, v, r$ are uniformly distributed over $\mathbb{F}_q$, with the correlation $uv = r+s$. In \cite{BCGIKS20}, the authors propose a construction of such pairs $(\word{u}, \word{r}), (\word{v}, \word{s})$ of elements in a ring $\mathcal{R}$, where $\mathcal R = \mathbb{F}_q[X]/(f(X))$ such that $f$ is split with simple roots in $\mathbb{F}_q$. Using the Chinese remainder Theorem, one deduces $\deg f$ pairs $(u_i, r_i), (v_i, s_i)$ with $u_i, v_i, r_i, s_i \in \mathbb{F}_q$. The pseudo-randomness of $\vec{u},\vec{v}$ rests on the hardness of the Ring--$\mathsf{LPN}${} assumption. \bigskip {\bf \noindent Search to decision reduction in the \cite{BCGIKS20}-case.} Consider the case of Ring--$\mathsf{LPN}${} over $\mathcal R = \mathbb{F}_q[X]/(f(X))$, where \[ f(X) \stackrel{\textrm{def}}{=} \prod_{a \in \mathbb{F}_q^{\times}} (X-a) = X^{q-1}-1. \] Let us re-introduce the Carlitz function field of Examples~\ref{ex:LambdaT} and~\ref{ex:LambdaTbis}, namely \[ K_T = \fract{\mathbb{F}_q(T)[X]}{(X^{q-1} + T)}. \] According to Equation \eqref{eq:O_T/(T+1)} in Example~\ref{ex:LambdaTbis}, we have \[ \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_T}{(T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_T} \simeq \fract{\mathbb{F}_q[X]}{(X^{q-1}-1)}, \] which is precisely the ring we consider for the Ring $\mathsf{LPN}${} version of \cite{BCGIKS20}. Therefore, instantiating our $\mathsf{FF}$--$\mathsf{DP}${} problem with this function field, modulus $T+1$, ideal $\goth{P} \stackrel{\textrm{def}}{=} (T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ and applying Theorem~\ref{thm:main}, we directly obtain the following search to decision reduction. \begin{theorem}[Search to decision reduction for totally-split Ring--LPN{}]\label{thm:StD_LPN} Let $K_{T}$ be the Carlitz extension of $T$--torsion over $\mathbb{F}_q$, and denote by $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T}$ its ring of integers. Consider the ideal $\goth{P}\stackrel{\textrm{def}}{=}~(T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K_{T}}$. Then $\goth{P}$ splits completely in $q-1$ factors $\goth{P}_{1}\dots\goth{P}_{q-1}$ and \[ \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P} \simeq \prod_{i=1}^{q-1}\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/\goth{P}_{i} \simeq \mathbb{F}_q \times \cdots \times \mathbb{F}_q. \] Let $\psi$ denote the uniform distribution over polynomials in $\mathbb{F}_q[X]/(X^{q-1}-1)$ of fixed Hamming weight, or the $q$--ary Bernouilli distribution. Let $\word{s}\in\mathbb{F}_q[X]/(X^{q-1}-1)$. Suppose that we have access to $\ffd{\word{s},\psi}$ and that there exists a distinguisher between the uniform distribution over $\mathbb{F}_q[X]/(X^{q-1}-1)$ and $\ffd{\word{s}, \psi}$ with uniform secret and error distribution $\psi$, running in time $t$ and having advantage $\varepsilon$. Then there exists an algorithm that recovers $\word{s}$ with overwhelming probability (in $q$) in time $$O\left( q^{5}\times \frac{1}{\varepsilon^{2}} \times t\right).$$ \end{theorem} \begin{proof} The only thing that remains to be proved is that the error distribution is Galois invariant. According to Theorem~\ref{thm:Carlitz_Galois} and Example~\ref{ex:LambdaTbis}, the Galois group of $K_T/\mathbb{F}_q(T)$ is isomorphic to $(\mathbb{F}_q[T]/(T))^{\times} \simeq \mathbb{F}_q^{\times}$. Furthermore, we proved that an element $b\in\mathbb{F}_q^{\times}$ acts on $f(T, X)\in K_{T}$ by \[ b\cdot f(T, X) = f(T, [b](X)) = f(T, bX). \] \iftoggle{llncs}{}{ For this example it can actually be understood directly using {\em Kummer theory} (see \cite[Proposition 3.7.3]{S09}). Indeed, $\mathbb{F}_q$, and hence $\mathbb{F}_q(T)$, contains the $(q-1)$--th roots of unity. Moreover, $K_{T}$ is nothing but the extension of $\mathbb{F}_q(T)$ spanned by a primitive $(q-1)$--th root of $-T$. Therefore, it is a {\em Kummer extension} and the action of the Galois group is characterized by $X\mapsto \zeta\cdot X$ for every $(q-1)$--th root of unity $\zeta$. But here, the set of $(q-1)$--th roots of unity is {\em precisely} $\mathbb{F}_q^{\times}$. }The Galois action on $K_T$ and $\mathcal{O}} \newcommand{\II}{\mathcal{I}_T$ induces an action of $\mathbb{F}_q^{\times}$ on \[ \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_T}{(T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_T} \simeq \fract{\mathbb{F}_q[X]}{(X^{q-1}-1)} \] by $b \cdot m(X) \stackrel{\textrm{def}}{=} m(b X)$. Note that, this operation has no incidence on the Hamming weight of $m$: it actually {\em does not change its Hamming support}. Therefore, we easily see here that Galois action keeps the noise distribution invariant. \end{proof} \begin{remark} Note that our search to decision reduction could have been performed here without introducing the function field and only considering the ring $\mathbb{F}_q[X]/(X^{q-1} - 1)$. Recall that the first ingredient of the reduction is to decompose this ring by the Chinese Remainder Theorem. Here it would give the product $\prod_{a \in \mathbb{F}_q^{\times}} \mathbb{F}_q[X]/(X-a)$. The final step of the reduction requires the introduction of a group action which induces a permutation of the factors in $\prod_{a \in \mathbb{F}_q^{\times}} \mathbb{F}_q[X]/(X-a)$. It is precisely what the group action $b \cdot m(X) = m(b X)$ does: it sends the factor $\mathbb{F}_q[X]/(X-a)$ onto $\mathbb{F}_q[X]/(X - b^{-1}a)$. However, introducing this action on the level of $\mathbb{F}_q[X]/(X^{q-1}-1)$ does not look very natural. It turns out that the introduction of function fields permits to interpret this action in terms of a Galois one. \end{remark} \iftoggle{llncs}{ \begin{remark} If we replace the Carlitz extension $K$ by some subfield of invariants under the action of a given subgroup of the Galois group, it is possible to extend the result to the case where $f(X) = \prod_{a \in H}(X-a)$ where $H$ is some subgroup of $\mathbb{F}_q^{\times}$. It is even possible to treat the case where the roots of $f$ form a coset of a given subgroup of $\mathbb{F}_q^{\times}$. \end{remark} } { \noindent {\bf Case H is a strict subgroup of $\mathbb{F}_q^{\times}$.} Now assume the polynomial $f$ has the form \[ f(X) = \prod_{a\in H}(X-a) \] with $H$ being a strict subgroup of $\mathbb{F}_q^{\times}$. To instantiate our search to decision reduction we need to find a group action that keeps the noise distribution invariant. \begin{lemma} There exists a Galois function field $K$ with its ring of integers $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ such that $H=~{\rm Gal}(K/\mathbb{F}_q(T))$ and $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/(T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K} = \mathbb{F}_q[X]/(f(X))$. Moreover, the action of $H$ keeps the Hamming support invariant. \end{lemma} \begin{proof} Consider again the Carlitz extension $K_{T}$. It has a {\em cyclic} Galois group $G\simeq \mathbb{F}_q^{\times}$ of cardinality $q-1$. Let $h \stackrel{\textrm{def}}{=} \#H$. It divides $q-1$. Since $G$ is cyclic, it has a {\em unique} subgroup $N$ of cardinality $\frac{q-1}{h}$. Let $L \stackrel{\textrm{def}}{=} K_{T}^{N}$ be the fixed field of $N$. Since $(T+1)$ splits completely in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{T}$, it also splits completely in any intermediate field. In particular, it splits completely in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{L}\stackrel{\textrm{def}}{=} \mathcal{O}} \newcommand{\II}{\mathcal{I}_{T}^{H}$ the ring of integers of $L$, we have $$ \mathcal{O}} \newcommand{\II}{\mathcal{I}_{L}/(T+1)\mathcal{O}} \newcommand{\II}{\mathcal{I}_{L} \simeq \mathbb{F}_q[X]/(f(X)). $$ Now, since $G$ is {\em abelian}, $N$ is {\em normal} in $G$. In particular, $L/\mathbb{F}_q(T)$ is a Galois extension, with Galois group $G/N \simeq H$. By the same argument as in the previous paragraph, the action of $H$ on $\mathbb{F}_q[X]/(f(X))$ only permutes the factors, but keeps the {\em supports} invariant. In particular, the noise distribution is not moved under the action of $H$. \end{proof} This lemma immediately implies a search to decision reduction analogue to theorem \eqref{thm:StD_LPN}. \begin{remark} When the roots of $f(X)$ do not form a subgroup of $G$, but a {\em coset} $bH$ instead, {\em i.e. } $f(X) = \prod_{\alpha\in bH}(X-\alpha)$, then it suffices to perform a translation by $b$ prior: $X\mapsto bX$ also keeps all the distributions invariant (including the uniform), and $\mathbb{F}_q[X]/(f(X))$ is mapped onto $\mathbb{F}_q[X]/(g(X))$ where $g(X) \stackrel{\textrm{def}}{=} \prod_{\alpha\in H}(X - \alpha)$, which yields the result by seeing the action of $H$ as arising from a Galois action. \end{remark} } {\bf \noindent Ring--$\mathsf{LPN}${} with a modulus $f$ splitting in irreducible polynomials of the same degree.} Another cryptographic design whose security rests on the Ring--$\mathsf{LPN}${} assumption is an authentication protocol named \textsc{Lapin}{} \cite{HKLPP12}. In the conclusion of their article, the authors mention that \begin{center} \begin{minipage}{0.9\textwidth} ``{\em it would be particularly interesting to find out whether there exists an equivalence between the decision and the search versions of the problem similar to the reductions that exist for $\mathsf{LPN}${} and Ring--$\mathsf{LWE}${}}''. \end{minipage} \end{center} For this protocol, the problem is instantiated with the binary field $\F{2}$ and with a modulus polynomial $f$ which splits as a product of $m$ distinct irreducible polynomials \[ f(X) = f_1(X) \cdots f_m(X). \] In this setting and using our techniques, we can provide a search to decision reduction when the $f_i$'s have all the same degree $d$. Furthermore, for the reduction to run in polynomial time, we need to have $d = O(\log (\deg f))$. In this setting, the Chinese Reminder Theorem entails that \[ \fract{\F{2}[X]}{(f(X))} \simeq \prod_{i=1}^m \fract{\F{2}[X]}{(f_i(X))}, \] and the right--hand side is a product of $m$ copies of $\F{2^d}$. Such a product can be realised as follows. Consider a function field $K$ which is a Galois extension of $\F{2}(T)$ with Galois group $G$ and denote by $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ the integral closure of $\F{2}[T]$ in $K$. Suppose that the ideal $(T)$ of $\F{2}[T]$ is unramified in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ with inertia degree $d$. Then $T\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ splits into a product of prime ideals: \[ T\mathcal{O}} \newcommand{\II}{\mathcal{I}_K = \mathfrak{P}_1 \cdots \mathfrak{P}_m \qquad \text{and} \qquad \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{T\mathcal{O}} \newcommand{\II}{\mathcal{I}_K} \simeq \prod_{i=1}^m \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{\mathfrak{P}_i}, \] where, here again, the right--hand side is a product of $m$ copies of $\F{2^d}$. Next, the idea is now to apply Theorem~\ref{thm:main} in this setting. However, there is here a difficulty since for our search to decision reduction to hold, the noise should arise from a Galois invariant distribution. Thus, if we want the noise distribution to be Galois invariant we need to have a Galois invariant $\F{2}$--basis of the algebra $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/T\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$. The first question should be whether such a basis exists. The existence of such a basis can be deduced from deep results of number theory due to Noether \cite{Noether32,C94} and asserting the existence of local normal integral bases at non ramified places. Here we give a pedestrian proof resting only on basic facts of number theory. Since this result also holds for larger finite fields, from now on, the underlying field is not supposed to be $\F2$ anymore. \begin{proposition}\label{prop:base_normale} Let $K/\mathbb{F}_q(T)$ be a finite Galois extension of Galois group $G$ and $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ be the integral closure of $\mathbb{F}_q[T]$ in $K$. Let $Q \in \F{q}[T]$ be an irreducible polynomial such that the corresponding prime ideal is unramified and has inertia degree $d$. Denote by $\mathfrak{P_1} \cdots \mathfrak{P}_m$ the decomposition of the ideal $Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$. Then, $G$ acts on the finite dimensional algebra $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ and there exists $\vec{x} \in \mathcal{O}} \newcommand{\II}{\mathcal{I}_K/Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ such that $(\sigma (\vec{x}))_{\sigma \in G}$ is an $\mathbb{F}_q$--basis of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$. \end{proposition} \begin{proof} Consider the decomposition group $D_{\mathfrak{P}_1/Q}$. As explained Section~\ref{sec:prereqFF} and in particular in Equation (\ref{eq:decomp_isom}), since $Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$ is unramified, this decomposition group is isomorphic to ${\rm Gal} (\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K,\mathbb{F}_q) = {\rm Gal}(\F{q^d},\mathbb{F}_q)$. This entails in particular that $\# D_P = d$. According to the Chinese Remainder Theorem, \[ \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K} \simeq \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{\mathfrak{P}_1} \times \cdots \times \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{\mathfrak{P}_m}. \] Next, from the Normal basis Theorem (see for instance \cite[Thm.~2.35]{LN97}), there exists $\vec{a} \in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_1}$ such that $(\sigma(\vec{a}))_{\sigma \in D_{\mathfrak{P}_1/Q}}$ is an $\mathbb{F}_q$--basis of ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_1}$. Now, let \[ \vec{b} \stackrel{\textrm{def}}{=} (\vec{a},0,\dots,0) \in \prod_{i=1}^m \mathcal{O}} \newcommand{\II}{\mathcal{I}_K/\mathfrak{P_i} \simeq \mathcal{O}} \newcommand{\II}{\mathcal{I}_K / Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K. \] We claim that $(\sigma(\vec{b}))_{\sigma \in G}$ is an $\mathbb{F}_q$--basis of $\mathcal{O}} \newcommand{\II}{\mathcal{I}_K/Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K$. Indeed, denote by $V$ the $\mathbb{F}_q$--span of $\{\sigma(\vec{b}) ~|~ \sigma \in G\}$ and suppose that $V$ is a proper subspace of ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q \mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$. Then, there exists $i \in \llbracket 1,m \rrbracket$ such that \[ V \cap \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{\mathfrak{P}_i} \varsubsetneq \fract{\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}{\mathfrak{P}_i}, \] where we denote by ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_i}$ the subspace $ \{0\} \times \cdots \times \{0\} \times {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_i } \times \{0\} \times \cdots \times \{0\}$ of $\prod_i \mathcal{O}} \newcommand{\II}{\mathcal{I}_K/\mathfrak{P}_i$. Since $G$ acts transitively on the $\mathfrak{P}_i$'s, there exists $\sigma_0 \in G$ such that $\sigma_0(\mathfrak{P}_1) = \mathfrak{P}_i$. Then, $\sigma_0(\vec{b}) \in V \cap \mathcal{O}} \newcommand{\II}{\mathcal{I}_K/\mathfrak{P}_i$ and so does $\sigma \sigma_0(\vec{b})$ for any $\sigma \in D_{\mathfrak{P}_i/P}$. Since $V \cap {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_i} \varsubsetneq {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_i}$, then $\dim_{\mathbb{F}_q}V < d$ while $\# D_{\mathfrak{P}_i/P} = d$. Hence, there exist nonzero elements ${(\lambda_\sigma)}_{\sigma \in D_{\mathfrak{P}_i/P}} \in \mathbb{F}_q^d$ such that \begin{equation}\label{eq:Galois_relation} \sum_{\sigma \in D_{\mathfrak{P}_i/P}} \lambda_{\sigma} \sigma \sigma_0(\vec{b}) = 0. \end{equation} Applying $\sigma_0^{-1}$ to (\ref{eq:Galois_relation}), we get \[ \sum_{\sigma \in D_{\mathfrak{P}_i/P}} \lambda_{\sigma} \sigma_0^{-1} \sigma \sigma_0(\vec{b}) = 0. \] As mentioned in Section~\ref{sec:prereqFF}, we have $\sigma_0^{-1}D_{\mathfrak{P}_i/Q}\sigma_0 = D_{\mathfrak{P}_1/Q}$ and we deduce that the above sum is in ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_1}$ and, since $\vec{a}$ is a generator of a normal basis of $\mathbb{F}_q$, we deduce that the $\lambda_{\sigma}$'s are all zero. A contradiction. \end{proof} The previous proposition asserts the existence of a {\em normal} $\mathbb{F}_q$--basis of the space ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$, {\em i.e. } a Galois invariant basis. For any such basis, ${(\vec{b}_{\sigma})}_{\sigma \in G}$ one can define a Galois noise distribution by sampling linear combinations of elements of this basis whose coefficients are independent Bernouilli random variables. Our Ring--$\mathsf{LPN}${} distribution is hence defined as pairs $(\word{a},\word{b}) \in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K} \times {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K }/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$ such that $\word{a}$ is drawn uniformly at random and $\word{b} = \word{a}\word{s}+\word{e}$ where $\word{e}$ is a noise term drawn from the previously described distribution. \begin{definition}[Galois modulus] Let $r$ and $d$ be positive integers. A polynomial $f(X)\in\mathbb{F}_q[X]$ of degree $r$ is called a Galois modulus of inertia $d$ if there exists a Galois function field $K/\mathbb{F}_q(T)$ and a polynomial $Q(T)\in\mathbb{F}_q[T]$ of degree one such that $\mathbb{F}_q[X]/(f(X)) \simeq \mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}/Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ and the ideal $Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_{K}$ has inertia degree $d$ and does not ramify. \end{definition} This definition entails that for a polynomial $f(X)\in\mathbb{F}_q[X]$ to be a Galois modulus, it needs to factorize in $\mathbb{F}_q[X]$ as a product of distinct irreducible polynomials of same degree $d$. Carlitz extensions permit to easily exhibit many Galois moduli of given inertia $d$. Indeed, let $M(T) \in \mathbb{F}_q[T]$ be any divisor of $T^d-1$ which vanishes at least at one primitive $d$--th root of unity. Set \[ r \stackrel{\textrm{def}}{=} \frac{\#{\left(\fract{\mathbb{F}_q[X]}{(M(X))}\right)}^{\times}}{d}\cdot \] Then, any polynomial $f(X) \in \mathbb{F}_q[X]$ which is a product of $r$ distinct irreducible polynomials of degree $d$ is a Galois modulus. Indeed, $\mathbb{F}_q[X]/(f(X))$ is isomorphic to a product of $r$ copies of $\F{2^d}$ and, since the multiplicative order of $T$ modulo $M(T)$ is $d$, from Theorem~\ref{thm:carlitz_splitting} so does $\mathcal{O}} \newcommand{\II}{\mathcal{I}_M/T\mathcal{O}} \newcommand{\II}{\mathcal{I}_M$. \begin{example}\label{ex:Galois_modulus} The polynomial $f(X) \stackrel{\textrm{def}}{=} X^{63}+X^{7}+1 \in \F2[X]$ is a {\em Galois} modulus of inertia $9$. Indeed, let $M(T) \stackrel{\textrm{def}}{=} T^{6}+T^{3}+1$ and consider $K_{M}$ the Carlitz extension of $M$--torsion. Denote by $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$ the integral closure of $\F2[T]$ in $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$. Then $T^{9} \equiv 1 \mod M$ and $9$ is the smallest integer that has this property. By Theorem \ref{thm:carlitz_splitting}, the ideal $T\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}$ splits into $7$ ideals $\goth{P}_{1},\dots,\goth{P}_{7}$ and has inertia $9$. Hence, $\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M}/(T\mathcal{O}} \newcommand{\II}{\mathcal{I}_{M})\simeq \mathbb{F}_q[X]/(f(X)).$ \end{example} \begin{remark} The polynomial $f(X)$ of Example \ref{ex:Galois_modulus} is also {\em lightness-preserving} in the sense of \cite[Def 2.22]{DP12} which can be used to instantiate Ring-LPN. \end{remark} We are now ready to define a new noise distribution which is Galois invariant for Ring--$\mathsf{LPN}${}. We propose to consider it in \textsc{Lapin}{} as it enables to apply our search to decision reduction. In the following definition, $\code{B}$ denotes a normal basis whose existence is ensured by Proposition~\ref{prop:base_normale}. Note that $\code B$ need not be exactly the normal basis constructed in the proof of Proposition~\ref{prop:base_normale}. This is discussed further, after the statement of Theorem~\ref{thm:stdpenr}. \begin{definition}[Normal Ring--$\mathsf{LPN}${} distribution] Let $r, d$ be positive integers, $p\in [0, \frac{1}{2})$ and let $f(X)\in\mathbb{F}_q[X]$ be a {\em Galois} modulus of degree $r$ with inertia $d$. Denote by $\code{B}\stackrel{\textrm{def}}{=} (\sigma(\word{c})(X))_{\sigma\in G_{f}}$ the normal basis of $\mathbb{F}_q[X]/(f(X))$ where $G_{f}$ is the Galois group of the related function field. A sample $(\word{a}, \word{b})$ is distributed according to the {\em Normal} $\mathsf{RLPN}${} distribution relatively to basis $\code{B}$, with secret $\word{s}$ if \begin{itemize}[label=\textbullet] \item $\word{a}$ is drawn uniformly at random over $\mathbb{F}_q[X]/(f(X))$; \item $\word{b} \stackrel{\textrm{def}}{=} \word{a}\word{s} + \word{e}$, where $\word{e}(X) \stackrel{\textrm{def}}{=} \sum_{\sigma\in G_{f}}e_{\sigma}\sigma(\word{c})(X) \in \mathbb{F}_q[X]/(f(X))$ has coefficients $e_{i}$'s which are independent $q$--ary Bernouilli random variables with parameter $p$. \end{itemize} \end{definition} \begin{theorem}\label{thm:stdpenr} The decision Ring--$\mathsf{LPN}${} is equivalent to its search version for the normal Ring--$\mathsf{LPN}${} distribution. \end{theorem} Let us discuss further the choice of the noise distribution and hence that of a Galois-invariant basis. In \cite{HKLPP12}, the authors discuss the case of Ring--$\mathsf{LPN}${} when the modulus $f$ splits and mention that in this situation, the Ring--$\mathsf{LPN}${} problem reduces to a smaller one by projecting the samples onto a factor ${\mathbb{F}_q[X]}/{(f_i(X))}$ of the algebra ${\mathbb{F}_q[X]}/{(f(X))}$. The projection onto such a factor, reduces the size of the inputs but increases the rate of the noise. It should be emphasized that the Galois invariant basis constructed in the proof of Proposition~\ref{prop:base_normale} yields a noise which is partially cancelled when applying the projection ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K} \rightarrow {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{\mathfrak{P}_i}$, hence, this choice of normal basis might be inaccurate. On the other hand, Proposition~\ref{prop:base_normale} is only an existence result and it turns out actually that a random element of ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$ generates a normal basis with a high probability. Indeed, the existence of such a normal basis can be reformulated as ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$ is a free $\mathbb{F}_q[G]$--module of rank $1$ and a generator $\word{a} \in {\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$ is an $\mathbb{F}_q[G]$--basis of ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$. Now, any other element of $\mathbb{F}_q[G]^{\times} \word{a}$ is also a generator of a normal basis. Consequently, the probability that a uniformly random element of ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$ is a generator of a normal basis is \[ \frac{\# \mathbb{F}_q[G]^\times}{\# \mathbb{F}_q[G]}\cdot \] If for instance, $G$ is cyclic of order $N$ prime to $q$. Then $X^N-1$ splits into a product of distinct irreducible factors $u_1\cdots u_r$ and $\mathbb{F}_q[G] \simeq {\mathbb{F}_q[X]}/{(X^N-1)} \simeq \prod_i {\mathbb{F}_q[X]}/{(u_i(X))}$. In this context, the probability that a uniformly random element of ${\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}/{Q\mathcal{O}} \newcommand{\II}{\mathcal{I}_K}$ generates a normal basis is \[ \frac{\prod_{i=1}^r (q^{\deg u_i}-1)}{q^N}\cdot \] \section*{Conclusion} We introduced a new formalism to study generic problems useful in cryptography based on structured codes. This formalism rests on the introduction of function fields as counterparts of the number fields appearing in cryptography based on structured lattices. Thanks to this new point of view, we succeeded in producing the first search to decision reduction in the spirit of Lyubashevsky, Peikert and Regev's one for Ring-$\mathsf{LWE}${}. We emphasize that such reductions were completely absent in cryptography based on structured codes and we expect them to be a first step towards further search to decision reductions. If one puts into perspective our current assessment with lattice-based cryptography, \cite{LPR10} focuses on cyclotomic number fields, and defined the error distribution to be a Gaussian over $\mathbb{R}^{n}$ through the Minkowski embedding. Furthermore, the modulus $q$ was chosen to split completely. Then, following this result, \cite{LS15} uses a ``switching modulus'' technique in order to relax the arithmetic assumption on the prime modulus, so that it can be arbitrarily chosen. Finally, the search to decision reduction has been proved in \cite{RSW18} to hold even when the extension is not Galois, using the Oracle with Hidden Center Problem (OHCP) technique from \cite{PRS17}. Note that this powerful technique has been used recently to provide a search to decision reduction in the context of NTRU \cite{PS21}. Even though our work does not reflect these recent progresses, we believe, as it was shown by our instantiations, that the introduction of the function field framework paves the way for using these techniques in the code setting in order to get a full reduction applying to cryptosystems such as {\sc HQC}{} or {\sc Bike}. \bibliographystyle{alphaurl} \newcommand{\etalchar}[1]{$^{#1}$}
{'timestamp': '2022-03-01T02:58:06', 'yymm': '2202', 'arxiv_id': '2202.13990', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13990'}
arxiv
\section{Introduction} \vspace{0cm} Network modeling is central to the field of computer networks. Models are useful in researching new protocols and mechanisms, allowing administrators to estimate their performance before their actual deployment in production networks. Network models also help to find optimal network configurations, without the need to test them in production networks. Queuing Theory (QT) \cite{cooper1981queueing} is arguably the most popular modeling technique, where networks are represented as inter-connected queues that are evaluated analytically. This represents a well-established framework that can model complex and large networks. Its main limitation is that it imposes strong assumptions on the packet arrival process, which typically do not hold in real networks~\cite{xu2018experience}. Internet traffic has been extensively analyzed in the past two decades~\cite{traffic1, traffic2, traffic3, traffic4, traffic6} and, despite the community has not agreed on a universal model, there is consensus that in general aggregated traffic shows strong autocorrelation and a heavy-tail~\cite{traffic5}. Another network modeling alternative is computational models (e.g., network simulators), which provide excellent accuracy. State-of-the-art network simulators include a wide range of network, transport, and routing protocols, and are able to simulate realistic scenarios. However, this comes at a very high computational cost that depends linearly on the number of packets being simulated. As a result, they are impractical in scenarios with realistic traffic volumes or large topologies. In addition, and because they are computationally expensive, they do not work well in real-time scenarios. Machine Learning (ML) \cite{mnih2015human} provides a new breed of mechanisms to model complex systems. In particular, Deep Learning (DL) \cite{lecun2015deep} has demonstrated to extract deep knowledge from human-understandable descriptions of a system. This approach has proven to achieve unprecedented accuracy in modeling properties of complex systems, like proteins~\cite{AlphaFold2021}. The main advantage of DL models is that they are \emph{data-driven}. DL models can be trained with real-world data, without making assumptions about the system. This enables to build models with unprecedented accuracy by effectively modeling the entire range of non-linear and multidimensional system characteristics. Computationally, DL is based on linear algebra and can take advantage of massive parallelism leveraging dedicated hardware and compilers. Within the field of DL, Graph Neural Networks (GNN)~\cite{scarselli2008graph} have recently emerged as an effective technique to model graph-structured data. GNNs are tailored to understand the complex relationships between the elements of a graph. The main novelty of GNNs is that their internal architecture is dynamically assembled based on the elements and connections of input graphs, and this enables to learn universal modeling functions that are invariant to graph isomorphism. GNNs are thus able to \emph{generalize} over graphs, which means that they can produce accurate estimates in different graphs not seen during training. As we will show in this paper, this is a critical advantage of GNNs in the context of network modeling. The novel GNN paradigm finally allows the application of ML in domains where data is essentially represented as graphs. As a consequence, at the time of this writing, substantial research efforts are being devoted to applying GNNs to different fields where data is fundamentally represented as graphs, such as chemistry~\cite{gilmer2017neural}, physics~\cite{battaglia2016interaction} and others~\cite{zhou2018graph}~\cite{Lange2020}. We argue that GNNs represent a new network modeling language with attractive advantages and characteristics. GNNs are designed to learn graphs, and computer networks are fundamentally graphs of connected queues. However, GNNs are not a black-box that map data inputs to outputs, it is actually a \emph{modeling tool} that needs to be researched and designed to account for the core behavior of computer networks. In contrast to more classical DL models, where the architecture is basically defined by the number of layers and neurons, GNNs are assembled ad-hoc, based on the elements and connections of the input graphs. These components represent the GNN modeling language, and they need to be carefully designed to reflect the relevant properties of the system being modeled. In this paper, we present RouteNet-Erlang (RouteNet-E), a novel GNN-based architecture designed for performance evaluation of computer networks. RouteNet-E shares the same goals as QT models: it is also able to model a network of queues, with different sizes and scheduling policies, while providing accurate estimates of delay, jitter, and losses. Interestingly, RouteNet-E is not limited to Markovian traffic models as QT, but rather it supports arbitrary traffic models including more complex ones with strong autocorrelation and high variance, which better represent the properties of real-world traffic~\cite{traffic5}. We also show that RouteNet-E overcomes one of the main limitations of existing ML-based models: \textit{generalization}. RouteNet-E is able to make accurate estimates in samples of unseen topologies one order of magnitude larger than those seen during training. We benchmark RouteNet-E against a state-of-the-art QT model, over a wide variety of network samples covering several different traffic models, from basic Poisson, to more realistic and complex models with strong autocorrelation and approximated heavy-tails. Our evaluation results show that the proposed model outperforms the QT benchmark in \emph{all} the network scenarios evaluated, always producing accurate delay predictions with a worst-case error of $6\%$ (for QT is $68\%$). We also show RouteNet-E's remarkable performance in hundreds of random network topologies not seen during training. Lastly, we measure its inference speed, which is in the order of milliseconds, in line with the QT benchmark. All datasets, code, and trained models of RouteNet-E used in this paper are publicly available at~\cite{github-erlang}. \vspace{0cm} \section{Challenges of GNN-based network modeling} \label{sec:challenges} \vspace{0cm} In this section, we describe the main challenges that GNN-based solutions need to address for network modeling. These challenges drove the core design of RouteNet-E. \textbf{Traffic models:} A model is an abstraction of a system able to distill the essential aspects of the system. Networks transport millions of packets and, as a result, network models require a useful abstraction for packets, that is why supporting arbitrary stochastic traffic models is crucial. Experimental observations show that traffic on the Internet has strong autocorrelation and heavy-tails~\cite{traffic5}. In this context, it is well-known that a main limitation of QT is that it fails to provide accurate estimates on realistic Markovian models with continuous state space, or non-Markovian traffic models. To the best of our knowledge, analytical models for queues with general arrival processes are limited to infinite buffers~\cite{Norros94}, or they make some sort of approximation (e.g., asymptotic), which greatly differs from the actual behavior of computer networks. The challenge for GNN-based modeling is, how to design an architecture that can accurately model realistic traffic models? \textbf{Training and Generalization:} One of the main differences between analytical modeling (e.g., QT) and ML-based modeling is that the latter requires training. In ML, training involves obtaining a \emph{representative} dataset with network measurements. The dataset needs to include a broad spectrum of network operational regimes. In practice, this means testing how different congestion levels affect performance metrics (delay, jitter, and losses), evaluating how different queuing policies affect performance or testing different routing policies, among others. Without this, the ML model is unable to learn and provide accurate estimates. Note that this is a common property of all neural network architectures. Generating this training dataset from networks in production is typically unfeasible, as it would require to artificially generate configurations (e.g., queue scheduling, routing) that lead to service disruption. A reasonable alternative is to create these datasets in controlled testbeds, where it is possible to use different traffic models and implement a broad set of configurations. Thus, the GNN model can be trained on samples from this testbed, and then be applied to real networks. Hence, the research challenge is: how to design a GNN able to provide accurate estimates in networks not seen during training? This includes topologies, traffic, and configurations (e.g., queue scheduling, routing) different from those seen in the training network testbed. \textbf{Generalization to larger networks:} From a practical standpoint, the GNN model must also generalize to \emph{larger} networks. Real-world networks include hundreds or thousands of nodes, and building a network testbed at this scale is typically unfeasible. As a result, the GNN model should be able to generalize from small network testbeds to considerably larger networks, by at least a factor of 10x. Generalizing to larger networks \mbox{-- or} graphs, in \mbox{general --} is currently an open research challenge in the field of GNNs. We address this by using domain-specific knowledge from computer networks, and by proposing a novel GNN architecture that can effectively model relevant scale-independent features of networks that affect performance metrics. \textbf{Queues and Scheduling policies:} A fundamental aspect when modeling networks is considering the behavior of queues (e.g., number, size), scheduling policies (e.g., WFQ, DRR), and the mapping of traffic flows to different Quality-of-Service classes if any. QT is a well-established technique, and models have been developed to support a wide range of scheduling policies~\cite{wfqmodel, KAPADIA1984337}. The challenge is, how to represent queues and scheduling policies inside the GNN architecture? \vspace{0cm} \section{Background: GNNs} \label{sec:background} \vspace{0cm} Graphs are used to represent relational information. Particularly, a graph $G \in \{V,E\}$ comprises a set of objects $V$ (i.e., vertices) and some relations between them $E$ (i.e., edges). GNN~\cite{scarselli2008graph} is a family of NNs especially designed to work with graph-structured data. These models dynamically build their internal NN architecture based on the input graph. For this, they use a modular NN structure that represents explicitly the elements and connections of the graph. As a result, they support graphs of variable size and structure, and their graph processing mechanism is invariant to node and edge permutation, which eventually endows them with strong generalization capabilities over graphs -- also known as \textit{strong relational inductive bias}~\cite{battaglia2018relational}. Despite GNN covers a broad family of neural networks with different architectural variants (e.g., \cite{scarselli2008graph, battaglia2016interaction, raposo2017discovering}), most of them share the basic principle of an iterative message-passing phase, where the different elements of the graph exchange information according to their connections, and a final readout phase uses the information encoded in graph elements to produce the final output(s). We refer the reader to \cite{scarselli2008graph, gilmer2017neural, battaglia2018relational} for a more comprehensive background on GNNs. \begin{figure}[!t] \centering \includegraphics[width=0.9\columnwidth]{figures/scheme_GNN_model.pdf} \vspace{0cm} \caption{Black-box representation of RouteNet-E} \label{fig:RouteNet-E-scheme} \vspace{-0.5cm} \end{figure} \vspace{0cm} \section{RouteNet-Erlang}\label{sec:RouteNet-E} \vspace{0cm} This section describes RouteNet-E, a novel GNN-based solution tailored to accurately model the behavior of real network infrastructures. RouteNet-E implements a novel three-stage message passing algorithm that explicitly defines some key elements for network modeling (e.g., traffic models, queues, paths), and offers support for a wide variety of features introduced in modern networking trends (e.g., complex QoS-aware queuing policies, overlay routing). Figure~\ref{fig:RouteNet-E-scheme} shows a black-box representation of the proposed GNN-based network model. The input of RouteNet-E is a network state sample, defined by: a network topology, a set of traffic models (flow-level), a routing scheme (flow-level), a queuing configuration (interface-level). As output, this model produces estimates of relevant performance metrics at a flow-level granularity (e.g., delay, jitter, losses). \vspace{0cm} \subsection{Model Description}\label{sec:model} \vspace{0cm} RouteNet-E has two main building blocks: $(1)$~Finding a good representation for the network components supported by the model -- e.g., traffic models, routing, queue \mbox{scheduling --}, and $(2)$~Exploit scale-independent features of networks, in order to achieve good generalization power to larger networks than those seen during training, which is an important open challenge previously discussed in Section~\ref{sec:challenges}. \vspace{0.1cm} \noindent \textit{1) Representing network components and their relationships:} First, let us define a network as a set of links \mbox{$L = \{l_i: i \in (1,...,n_l)\}$}, a set of queues on $Q = \{q_i: i \in (1,...,n_q)\}$, and a set of source-destination flows $F = \{f_i: i \in (1,...,n_f)\}$. According to the routing configuration, flows follow a source-destination path. Hence, we define flows as sequences with tuples of the queues and links they traverse $f_i=\{(q_{F_q(f_i,0)},l_{F_l(f_i,0)}),...,(q_{F_q(f_i,|f_i|)},$ $l_{F_l(f_i,|f_i|)})\}$, where $F_q(f_i,j)$ and $F_l(f_i,j)$ respectively return the index of the \mbox{$j$-th} queue or link along the path of flow $f_i$. Let us also define $Q_f(q_i)$ as a function that returns all the flows passing through queue $q_i$, and $L_q(l_i)$ as a function that returns the queues injecting traffic into link $l_i$ -- i.e., the queues at the output port to which the link is connected. \begin{figure}[!t] \centering \includegraphics[width=0.9\columnwidth]{figures/arch_overview_v3.pdf} \vspace{0cm} \caption{Schematic representation of the network model implemented by RouteNet-E.} \label{fig:architecture_overview} \vspace{-0.5cm} \end{figure} Following the previous notation, RouteNet-E considers an input graph with three main components: $(i)$ the physical links $L$ that shape the network topology, $(ii)$ the queues $Q$ at each output port of network devices, and $(iii)$ the active flows $F$ in the network, which follow some specific src-dst paths (i.e., sequences of queues and links), and whose traffic is generated from a given traffic model. Figure~\ref{fig:architecture_overview} shows a schematic representation of the network model internally considered by RouteNet-E, which is derived from the several mechanisms that affect performance in real networks. From this model, we can extract three basic principles: \begin{enumerate}[label=(\roman*)] \item The state of flows (e.g., throughput, losses) is affected by the state of the queues and links they traverse (e.g., queue/link utilization). \item The state of queues (e.g., occupation) depends on the state of the flows passing through them (e.g., traffic model). \item The state of links (e.g., utilization) depends on the states of the queues at the output port of the link, and the queue scheduling policy applied over these queues. \end{enumerate} Formally, these principles can be formulated as follows: \begin{align} h_{f_k} &= g_f(h_{q_{k(0)}},h_{l_{k(0)}},...,h_{q_{k(|f_k|)}},h_{l_{k(|f_k|)}}) \label{eq:g_f}\\ h_{q_i} &= g_q(h_{p_1},...,h_{p_m}), \quad q_i \in p_k, k = 1,...,j \label{eq:g_q}\\ h_{l_j} &= g_l(h_{q_1},...,h_{q_m}), \quad q_m \in L_q(l_j) \label{eq:g_l} \end{align} Where $g_f$, $g_q$ and $g_l$ are some unknown functions, and $h_f$, $h_q$ and $h_l$ are latent variables that encode information about the state of flows $F$, queues $Q$, and links $L$ respectively. Note that these principles define a circular dependency between the three network components ($F$, $Q$, and $L$) that must be solved to find latent representations satisfying the equations above. Based on the previous network modeling principles, we define the architecture of RouteNet-E (see Algorithm~\ref{alg:architecure}). Our GNN-based model implements a custom three-stage message-passing algorithm that combines the states of flows, queues and links according to Equations~\eqref{eq:g_f}-\eqref{eq:g_l}, thus aiming to resolve the circular dependencies defined in such functions. First, the hidden states $h_l$, $h_q$, and $h_f$ -- represented as n-element vectors -- are initialized with some features (lines \ref{init-l}-\ref{init-p}), denoted respectively by $x_{l_i}$, $x_{q_j}$ and $x_{f_k}$. In our case, we set the initial features of links ($x_l$) as: $(i)$ the link capacity ($C_i$), and \mbox{$(ii)$ the} scheduling policy at the output port of the link (FIFO, SP, WFQ, or DRR~\cite{shreedhar1996efficient}), using one-hot encoding. For the initial features of queues ($x_q$) we include: $(i)$ the buffer size, $(ii)$ the priority level (one-hot encoding), and $(iii)$ the weight (only for WFQ and DRR). Lastly, the initial flow features ($x_f$) are a descriptor of the traffic model used in the flow ($T_i$). Once the states are initialized, the message-passing phase is iteratively executed $T$ times (loop from line~\ref{init-loop}), where $T$ is a configurable parameter. Each message-passing iteration is in turn divided in three stages, that respectively represent the message passing and update of the hidden states of flows $h_f$ (lines~\ref{mp-path-init}-\ref{mp-path-end}), queues $h_q$ (lines~\ref{mp-queue-init}-\ref{mp-queue-end}), and links $h_l$ (lines~\ref{mp-link-init}-\ref{mp-link-end}). \algnewcommand\algorithmicforeach{\textbf{for each}} \algdef{S}[FOR]{ForEach}[1]{\algorithmicforeach\ #1\ \algorithmicdo} \renewcommand{\algorithmicrequire}{\textbf{Input:}} \renewcommand{\algorithmicensure}{\textbf{Output:}} \begin{algorithm}[!t] \caption{Internal architecture of RouteNet-E} \begin{algorithmic}[1] \Require{$F$, $Q$, $L$, $x_f$, $x_q$, $x_l$} \Ensure{$h^T_q$, $h^T_l$, $h^T_f$, $\hat{y_f}$, $\hat{y_q}$, $\hat{y_l}$} \ForEach {$l \in L$} $h^0_l \gets [x_{l},0...0]$ \EndFor \label{init-l} \ForEach {$q \in Q$} $h^0_q \gets [x_{q},0...0]$ \EndFor \ForEach {$f \in F$} $h^0_f \gets [x_{f},0...0]$ \EndFor \label{init-p} \For{t = 0 to T-1} \label{init-loop} \Comment{\footnotesize Message Passing Phase} \ForEach {$f \in F$} \label{mp-path-init} \Comment{\footnotesize Message Passing on Flows} \ForEach {$(q,l) \in f$} \State $h^t_{f} \gets FRNN(h^t_{f},[h^t_q,h^t_l])$ \label{lin:u-flow} \Comment{\footnotesize Flow: Aggr. and Update} \State $\widetilde{m}^{t+1}_{f,q} \gets h^t_{f} $ \Comment{\footnotesize Flow: Message Generation} \EndFor \State $h^{t+1}_{f} \gets h^{t}_{f} $ \EndFor \label{mp-path-end} \ForEach {$q \in Q$} \label{mp-queue-init} \Comment{\footnotesize Message Passing on Queues} \State $M_q^{t+1} \gets \sum_{f \in Q_f(q)} \widetilde{m}^{t+1}_{f,q}$ \Comment{\footnotesize Queue: Aggregation} \vspace{0.1cm} \State $h^{t+1}_q \gets U_q(h^t_q,M_q^{t+1})$ \Comment{\footnotesize Queue: Update} \State $\widetilde{m}^{t+1}_{q} \gets h^{t+1}_{q} $ \Comment{\footnotesize Queue: Message Generation} \EndFor \label{mp-queue-end} \ForEach {$l \in L$} \label{mp-link-init} \Comment{\footnotesize Message Passing on Links} \ForEach {$q \in L_q(l)$} \State ${h}^{t}_{l} \gets LRNN(h^t_l,\widetilde{m}^{t+1}_{q})$ \label{lin:u-link} \Comment{\footnotesize Link: Aggr. and Update} \EndFor \State $h^{t+1}_l \gets {h}^{t}_{l}$ \EndFor \label{mp-link-end} \EndFor \label{end-loop} \State $\hat{y_f} \gets R_f(h^T_f)$ \label{r-path} \Comment{\footnotesize Readout phase} \State $\hat{y_q} \gets R_q(h^T_q)$ \label{r-queue} \end{algorithmic} \label{alg:architecure} \end{algorithm} \setlength{\textfloatsep}{0.2cm Finally, functions $R_f$ (line~\ref{r-path}) and $R_q$ (line~\ref{r-queue}) represent independent readout functions that can be respectively applied to the hidden states of flows $h_f$ or queues $h_q$. In our experiments in Section~\ref{sec:evaluation}, we use $R_f$ and $R_q$ to predict the flow-level delay, jitter and losses -- as described later in this section. The main motivation to use data-driven methods, such as RouteNet-E, instead of traditional QT is to achieve accurate modeling of complex traffic models that better reflect real-world traffic -- as previously introduced in Section~\ref{sec:challenges}. Hence, in RouteNet-E the representation of the traffic model descriptors ($T_i$) is central to achieve accurate modeling of different traffic patterns, and capturing their intrinsic properties. Particularly, we define $T_i$ as an n-element vector that includes the specific parameters that shape each traffic model. Find more details about the parameters of each model in section~\ref{subsec:sim-setup}. \vspace{0.15cm} \noindent \textit{2) Scaling to larger networks: scale-independent features} \vspace{0.1cm} As previously discussed in Section~\ref{sec:challenges}, generating datasets directly from networks in production would imply testing configurations that may break the correct operation. As a result, GNN-based network models should be typically trained with data from network testbeds, which are usually much smaller than real networks. In this context, it is essential for our GNN to effectively scale to larger networks than those of the training dataset -- by at least a 10x factor. GNNs have shown an unprecedented capability to generalize over graph-structured data~\cite{battaglia2018relational,zhou2018graph}. In the context of generalizing to larger graphs, it is well known that these models keep good generalization capabilities as long as the spectral properties of graphs are similar to those seen during training~\cite{ruiz2020graphon}. In the case of RouteNet-E, its message-passing algorithm can analogously generalize to graphs with similar structures to those seen during the training phase -- e.g., similar number of queues at output ports, or similar number of flows aggregated in queues. In this vein, generating a representative dataset for RouteNet-E in small networks, covering a wide range of graph structures, does not imply any practical limitation to then achieve good generalization properties to larger networks. It can be done by simply adding a broad combination of realistic network samples with a wide variety of traffic models, routing schemes, and queuing policies as in the process described later in section~\ref{subsec:sim-setup}. However, from a practical standpoint, scaling to larger networks often entails a broader definition beyond the topology size and structure. In particular, there are two main properties we can observe as networks become larger: $(i)$ \textit{higher link capacities} (as there is more aggregated traffic in the core links of the network), and $(ii)$ \textit{longer paths} (as the network diameter becomes larger). This requires devising mechanisms to effectively scale on these two features. \vspace{0.1cm} \noindent \textbf{Scaling to larger link capacities:} If we observe the internal architecture of RouteNet-E (Algorithm~\ref{alg:architecure}), we can find that the link capacity $C$ is only represented as an initial feature of links' hidden states $x_{l_i}$. The fact that $C$ is encoded as a numerical feature in the model introduces inherent limitations to scale to larger capacity values. Indeed, scaling to out-of-distribution numerical values is widely recognized as a generalized limiting factor among all neural networks~\cite{engstrom2019exploring,su2019one}. Thus, our approach is to exploit particularities from the network domain to find scale-independent representations that can define link capacities and how they relate to other link-level features that impact performance (e.g., the aggregated traffic in the link), as the final goal of RouteNet-E is to accurately estimate performance metrics (e.g., delay, jitter, losses). Inspired by traditional QT methods, we aim to encode in RouteNet-E the relative ratio between the arrival rates on links (based on the traffic aggregated in the link), and the service times (based on the link capacity), thus enabling the possibility to infer the output performance metrics of our model from scale-independent values. As a result, we define link capacities ($Cap_{link}$) as the product of a \textit{virtual reference link capacity} ($C_{ref}$) and a \textit{scale factor} ($S_{f}$) -- i.e., $Cap_{link} = C_{ref} * S_{f}$. This representation enables to define arbitrary combinations of scale factors and reference link capacities to define the actual capacity of links in networks. Hence, in RouteNet-E we introduce the capacity feature ($C_i$) as a 2-element vector defined as $C_i$$=$$[C_{ref}, S_f]$, which is included in the initial feature vector of links ($x_l$). Note that this feature will eventually be encoded in the hidden states of links ($h_l$). In the internal architecture of RouteNet-E (Algorithm~\ref{alg:architecure}), this factor will mainly affect the update functions of flows and links (lines~\ref{lin:u-flow} and \ref{lin:u-link}), as they are the only ones that process directly the hidden states of links ($h_l$). As a result, the RNNs approximating these update functions can potentially learn to make accurate estimates on any combination of $C_{ref}$ and $S_{f}$ as long as these two features are within the range of values observed \textit{independently} for each of them during the training phase (i.e., $S_{f}\in [s_{f_{min}}, s_{f_{max}}]$ and $C_{ref}\in [C_{{ref}_{min}}, C_{{ref}_{max}}]$). Thus, we exploit this property to devise a custom data augmentation method, where we take samples from small networks with limited link capacities and generate different combinations of $C_{ref}$ and $S_{factor}$ that enable us to scale accurately to considerably larger capacities. Note that in this process, the numerical values seen by RouteNet-E ($C_{ref}$ and $S_{factor}$) are kept in the same ranges both in the training on small networks and the posterior inference on larger networks, thus overcoming the practical limitation of out-of-distribution predictions~\cite{engstrom2019exploring,su2019one}. More details about the proposed data augmentation process are given in Sec.~\ref{subsec:training}. The previous mechanism enables to keep scale-independent features along with the message-passing phase of our model (loop lines \ref{init-loop}-\ref{end-loop} in Algorithm~\ref{alg:architecure}), while it is still needed to extend the scale independence to the output layer of the model. Particularly, in this paper, we use RouteNet-E to predict the flows' delay, jitter, and losses. Note that the distribution of these parameters can also vary for flows traversing links with higher capacities, thus leading again to out-of-distribution values. Based on the fundamentals of QT, we overcome this potential limitation by inferring delays/jitter indirectly from the occupation of queues in the network $O_{q_i}$$\in$$[0,1]$, using the $\hat{y_q}$$=$$R_q(h_q)$ function of RouteNet-E (Algorithm~\ref{alg:architecure}). Then, we infer the flow delay/jitter as a linear combination of the waiting times in queues (inferred from $O_{q_i}$) and the transmission times of the links the flow traverses. Note that a potential advantage with respect to traditional QT models is that the queue occupation estimates produced by RouteNet-E can be more accurate, especially for complex traffic models resembling real-world traffic -- as shown later in our experimental results of Section~\ref{sec:evaluation}. Likewise, for packet loss, RouteNet-E predicts directly the percentage of packets dropped with respect to the packets that were sent by the source of the flow, thus producing a bounded value $D_{f_i}$$\in$$[0,1]$, that is estimated with the $\hat{y_f}$$=$$R_f(h_f)$ function of Algorithm~\ref{alg:architecure}. \noindent \textbf{Scaling to longer paths:} In the internal architecture of RouteNet-E, the path length only affects to the RNN function of line \ref{lin:u-flow} (Algorithm~\ref{alg:architecure}), which collects the state of queues ($h_q$) and links ($h_l$) to update flows' states ($h_f$). The main limitation here is that this RNN can typically see during training shorter link-queue sequences than those it can find then in larger networks, that can potentially have longer paths. As a result, we define $L_{max}$ as a configurable parameter of our model that defines the maximum sequence length supported by this RNN. Then, we split flows exceeding $L_{max}$ into different queue-link sequences that are independently digested by the RNN. To keep the state along with the whole flow, in case it is divided into more than one sequence, we initialize the initial state of the RNN with the output resulting from the previous sequence. \vspace{0cm} \subsection{Simulation Setup} \label{subsec:sim-setup} \vspace{0cm} To train, validate and test RouteNet-E we use as ground truth a packet-level network simulator (OMNeT++ v5.5.1~\cite{varga2001discrete}), where network samples are labeled with performance metrics, including the flows' mean delay, jitter and losses, and queue-level statistics (e.g., occupation, packet loss). To generate these datasets, for each sample we randomly select a combination of input features (traffic model, topology, and queuing configuration) according to the descriptions below: \subsubsection{Traffic models} Traffic is generated using five different models with increasing levels of complexity, which ranges from a basic Poisson generation process to more realistic traffic models with strong autocorrelation and heavy-tails~\cite{traffic5}. We define below the implementation details of these models (except for the well-known Poisson and Constant Bitrate, whose only configurable parameter is the traffic intensity level) \paragraph{On-Off} This model defines two possible states (On or Off). The lengths of On and Off periods are randomly selected $[5, 15]$ seconds. Likewise, during the On period, packets are generated using an exponential distribution. \paragraph{Autocorrelated exponentials}\label{par:acfexp} This model generates autocorrelated exponentially distributed traffic staring from the following auto-regressive (AR) process: $z_{t+1}$=$az_t$$+$$\varepsilon$, $\varepsilon$$\sim$$\text{N}(0,\sigma^2)$ where $a$$\in$$(-1,1)$ controls the level of autocorrelation. The marginal distribution of $z$ is $\text{N}(0,s^2=\sigma^2/(1-a^2))$, so $z$ can be negative. In order to construct positive inter-arrival times, $z$ is mapped by a nonlinear transformation: $\delta_t=F_E^{-1}\left(\lambda,F_N\left(0,s^2,z_t \right)\right)$, where $F_N(0,s^2,\cdot)$ and $F_E(\lambda,\cdot)$ are respectively a CDF of the normal distribution with $\mu=0$ and variance $s^2$=$[3,12]$, and an exponential distribution with parameter $\lambda$=$[40,2000]$. The first transformation changes the distribution from normal to uniform on $(0,1)$, while the second maps it into an exponential distribution. As a result, $\delta_t$ follows an exponential distribution with autocorrelation. Such a model can be interpreted as a copula~\cite{nelsen1999copula}. \paragraph{Modulated exponentials} This model represents an alternative autocorrelated model with higher complexity for QT than the one above and is inspired by observation from~\cite{traffic2}. Particularly, the inter-arrival times are set by a hierarchical model. Inter-arrivals follow an exponential distribution ($\text{Exp}$) whose rate is controlled by the value of a hidden AR model. Formally, we can describe the model as $\delta_t|z_t$$\sim$$\text{Exp}(\lambda_t$=$Ae^{z_t})$, where $A$ is scaling constant and $z$ is an AR model as in the previous traffic model. In all the previous models, average traffic rates on src-dst flows are carefully set to cover low to quite high congestion levels across different samples, where the most congested samples have $\approx$$3\%$ of packet losses. \subsubsection{Queuing configuration} Each forwarding device is configured with a different scheduling policy that depends on the particular scenario of our evaluation (more details in Sec.~\ref{sec:evaluation}). Overall, we use four different queue scheduling policies: First In First Out (FIFO), Strict Priority (SP), Weighted Fair Queueing (WFQ), and Deficit Round Robin (DRR)~\cite{shreedhar1996efficient}. We consider three queues per output port (except for FIFO, with only one queue), and queues have a size of 16 or 32 packets. For WFQ and DRR, we define random queue weights. \subsubsection{Topologies}\label{subsec:topologies} To train the GNN model we used two different real-world topologies: NSFNET (14 nodes)~\cite{hei2004wavelength}, and GEANT (24 nodes)~\cite{barreto2012fast}. Then, we validate the accuracy of RouteNet-E in GBN (17 nodes)~\cite{pedro2011performance}. \vspace{0cm} \subsection{Training} \label{subsec:training} \vspace{0cm} We implement RouteNet-E in TensorFlow. All the datasets, the code, and the trained models are publicly available \cite{github-erlang}. To train the model, we use a custom data augmentation approach that, given a link capacity ($Cap_{link}$), covers a broad combination of $S_f$ and $C_{ref}$ values, in order to eventually make the model generalize over samples with larger link capacities. Particularly, given a link capacity, in some samples, we use low values of $S_f$ with higher values of $C_{ref}$, while in other samples we make it in the opposite way. As an illustrative example, if the model is trained over samples with 1Gbps links, we can represent these capacities in different samples as $Cap_{link}$=$10$*$100Mbps$$=$$1Gbps$, or $Cap_{link}$=$1$*$1Gbps$$=$$1Gbps$. Thus, after training the model should be able to make accurate inferences on samples that combine the maximum $S_f$ and $C_{ref}$ values seen during training -- i.e., $Cap_{link}$=$10$*$1Gbps$$=$$10Gbps$. In practice, this means that the model can be trained with samples with a maximum link capacity of 1 Gbps, and then scale effectively to samples with link capacities up to 10 Gbps. Note that these numbers are just illustrative, while this data augmentation method is sufficiently general to produce in the training dataset wider ranges of $S_f$ and $C_{ref}$ given a maximum link capacity. Thus, it can be potentially exploited to represent combinations leading to arbitrarily larger capacities. \begin{figure}[!t] \centering \includegraphics[width=0.65\columnwidth]{figures/loss.pdf} \vspace{-0.05cm} \caption{Training and evaluation losses over time.} \label{fig:loss} \vspace{0cm} \end{figure} After making some grid search experiments, we set a size of 32 elements for all the hidden state vectors ($h_f$, $h_q$, $h_l$), and $T$=$8$ message-passing iterations. We implement $FRNN$, $LRNN$, and $U_q$ as Gated Recurrent Units (GRU)~\cite{chung2014empirical}, and functions $R_f$ and $R_q$ as 2-layer fully-connected neural networks with ReLU activation functions. Here, it is important to note that the whole neural network architecture of RouteNet-E (Algorithm~\ref{alg:architecure}) constitutes a fully differentiable function, so it is possible to train the model end to end. Hence, all the different functions that shape its internal architecture are jointly optimized during training based on RouteNet-E's inputs (network samples) and outputs (performance metrics). We use a training dataset with 200,000 samples from the NSFNET and GEANT topologies (100,000 samples each), including a variety of traffic model descriptors ($T_i$), routing schemes, and queue scheduling configurations -- following the descriptions in Section~\ref{subsec:sim-setup}. For the validation and test datasets, we generate 2,000 samples from the GBN topology (1,000 samples for each dataset). We train RouteNet-E for 200 epochs -- with 4,000 samples per epoch -- and set the Mean Squared Error (MSE) as loss function, using an Adam optimizer with an initial learning rate of 0.001. Figure~\ref{fig:loss} shows the evolution of the loss during training on delay estimates (for the training and validation samples), which shows stable learning along the whole training process. \vspace{0cm} \section{Baseline: Queuing theory}\label{qt} \vspace{0cm} In this section, we describe the state-of-the-art model we use to benchmark RouteNet-E. QT applied to networking results in a model as a function of graph-structured data. The network is represented as a directed multigraph of queues (buffers) while edges correspond to virtual channels along with the physical link. The general description of Equations~\eqref{eq:g_f}-\eqref{eq:g_l} holds, however, the exact relations are derived analytically from the common assumption that a system is approximated by a Markov chain. This makes it a perfect benchmark for RouteNet-E. In the holistic approach, the network is modeled as a single system, like in Jackson Networks~\cite{Kelly2011} or more general BCMP queuing networks~\cite{bcmp}. For those systems, the product form of the stationary distribution greatly simplifies the solution, however, the assumption of infinite buffers makes those models unrealistic and unable to estimate packet loss ratio. In our approach, all the queues along the path are modeled independently. Further, we assume that arrival to each queue is approximated by the Poisson process. Service times are assumed to be independent and exponentially distributed. Under those assumptions, we can derive analytical results for queue throughput, delay distribution, and blocking probability. The aforementioned model also suffers from circular dependency. Packet loss on a particular queue depends on its load so it also depends on the throughput of other queues feeding this particular one. The throughput, however, depends on packet loss so we end up with circular dependence. We fixed this problem by a \emph{map-reduce} inspired algorithm that also emphasizes the resemblance between GNN and QT. The algorithm consists of there functions: \emph{map\_queues}, \emph{map\_paths} and \emph{reduce}. The \emph{map\_queues} function updates packet loss for each queue, given the total traffic (external demands plus within network transfer). The function also computes the remaining QoS parameters (jitter and delay). The \emph{map\_paths} function updates the traffic knowing the packet loss on every queue. Finally, the \emph{reduce} function aggregates per path delay, jitter, and packet loss. In the first iteration, we assume no packet loss. Given the first approximation, we can compute the loss probability (\emph{map\_queues}) and update the intensities to account for the losses (\emph{map\_paths}). After a few iterations, the algorithm converges to a fixed point and the final values are reduced (\emph{reduce}). Notice how this approach is similar to RouteNet-E forward pass. In QT, we use known analytical relations while in GNN those relations are approximated by a neural network and learned from the data. For an $M/M/1/b$ system, we used known formulas for blocking probabilities and delay distribution to get average delay and jitter. For a network with scheduling, we designed \emph{map\_queues} functions based on the Markov chain model described below. Because scheduling couples the queues, the corresponding \emph{map\_queues} operates on groups of queues assigned to the same link. Let us begin with a strict priority scheduler. Consider $p$ priority class customers arriving at rate $\lambda_i$ and requiring service time with mean $1/\mu_i$. Each class waits in the independent virtual queue limited by $b_i$ and served in non-preemptive FIFO order. Such a system can be modeled as a continuous-time Markov chain on the state space $\mathcal{S}_{SP}=\{(s,q=(q_1,q_2,\ldots,q_p)\}$, where $s$ denotes the priority class currently being served or $0$ if the system is empty. The remaining part of the state: $p$-tuple $q$ encodes the number of customers for each priority. For convenience let us define $q_{i+}\vcentcolon=(q_1,\ldots,q_i+1,\ldots,q_p)$, $q_{i-}\vcentcolon=(q_1,\ldots,q_i-1,\ldots,q_p)$ and $q^0=(0,\ldots,0)$. The model is based on~\cite{KAPADIA1984337} and modified to allow for per-priority class buffer size. Time evolution of the CTMC is characterized by the generator matrix $\bm Q$ whose elements follow the rules: \vspace{-0.05cm} \begin{align} \bm Q&[(0,q),(i,q_{i+})]=\lambda_i\quad 0< i \leq p \label{eq:Qspa}\\ \bm Q&[(s,q),(s,q_{i+})]=\lambda_iI_{q_i<b_i}\quad 0< i \leq p \\ \bm Q&[(s,q^0_{s+}), (0,q^0)]=\mu_s \quad 0< s \leq p\\ \bm Q&[(s,q),(\min\{i:q_i>0\},q_{s-})]=\mu_s\label{eq:Qspz} \end{align} where $I_{A}$ is an indicator function and $\bm Q[.,.]$ denotes entry in generator matrix. If neither rule matches states pair a general rules $\bm Q[s,s']=0, \quad s\neq s'$ and $\bm Q[s,s]=-\sum_{s'\neq s}\bm Q[s,s']$ apply. A similar model can be constructed for WFQ and DRR. Since both scheduling policies approximate an ideal Generalized Processor Sharing the same model is used for WFQ and DRR. The CTMC is similar to \eqref{eq:Qspa}-\eqref{eq:Qspz} with exception that the queue $i$ is served at rate $\mu_i$ if other queues are empty, otherwise the rate scales proportionally to the positive weight $w_i$. State space $\mathcal{S}_{GPS}$ is also simplified and it is formed solely of $p$ tuples $q$ defined as for SP. The resulting CTMC is based on~\cite{wfqmodel} and evolves according to the following generator:\\ \vspace{-0.4cm} \begin{align} \bm Q&[q,q_{i+}]=\lambda_i I_{q_i<b_i}\quad 0< i \leq p\\ \bm Q&[q,q_{i-}]=\frac{I_{q_i>0} w_i}{\sum_{q_i>0} w_i}\mu_i\quad 0< i \leq p \end{align} Given the generator matrix $\bm Q$, we can develop either an analytical solution for queue characteristics as in~\cite{wfqmodel,KAPADIA1984337} or use a direct approach and obtain them numerically. We chose the latter and compute packet loss delay and jitter assuming the CTMC has reached stationary distribution $\bm \pi$ computed from global balance equations (GBE)~\cite{Kelly2011} that form a sparse linear system. We obtained $\bm \pi$ from sparse eigenvalue decomposition via Arnoldi method~\cite{Stewart2000} with a general sparse linear solver as a fallback in case of numerical instabilities. Given the $\bm \pi$, the packet loss ratio for class $i$ ($\bm p_{b}[i]$) is the sum of all state probabilities where queue $i$ is full. The delay is computed from average queue size (with respect to $\bm \pi$) using Little's law. Computation of jitter requires a more sophisticated approach. We pose this as the first passage time problem in CTMC~\cite{Kijima97a}. The delay of a class $i$ customer is the first passage time to any state where the queue $i$ is empty provided that no new customers can arrive so $\lambda_i=0$ for GPS or $\lambda_j=0, j\leq i$ for SP. Its conditional distribution can be calculated from $\bm Q$ using Laplace transform~\cite{Kijima97a}. The final delay distribution and jitter are obtained from the total probability theorem. It is assumed that a packet of class $i$ observing state $s$ at his arrival experiences delay equal to the first passage time from the state just after his arrival $s_{i+}$. From PASTA property, the probability of such an event is $\bm \pi[s]/({1-\bm p_{b}[i]})$, here we condition of the event that packet is not dropped. \vspace{0cm} \section{Evaluation}\label{sec:evaluation} \vspace{0cm} In this section, we evaluate the performance of RouteNet-E in a wide range of relevant scenarios. We seek to understand:\\ 1) Can RouteNet-E model complex traffic models? What is the accuracy with realistic models with strong autocorrelation and heavy-tails?\\ 2) Is RouteNet-E able to understand more complex multi-queue scheduling policies? What is the accuracy compared to QT?\\ 3) Is RouteNet-E able to generalize to unseen network configurations and traffic loads? Also, can it generalize to \emph{larger} networks?\\ 4) How fast is RouteNet-E compared to the QT benchmark? Does it allow for real-time operation? \begin{figure*} \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=\textwidth]{figures/poisson_gnn_0.023_0.066_qt_0.18_0.72.pdf} \caption{Poisson} \label{fig:poisson} \end{subfigure}\hfill \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=\textwidth]{figures/deterministic_gnn_0.046_0.061_qt_0.224_1.pdf} \caption{Constant bitrate} \label{fig:periodic} \end{subfigure}\hfill \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=\textwidth]{figures/onoff_gnn_0.043_0.086_qt_0.231_0.694.pdf} \caption{On-Off} \label{fig:onoff} \end{subfigure} \medskip \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=\textwidth]{figures/k1_gnn_0.032_0.119_qt_0.211_0.744.pdf} \caption{Autocorrelated exponentials} \label{fig:auto_exp} \end{subfigure}\hfill \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=\textwidth]{figures/k2_gnn_0.06_0.082_qt_0.681_0.914.pdf} \caption{Modulated exponentials} \label{fig:mod_exp} \end{subfigure}\hfill \begin{subfigure}{0.30\textwidth} \centering \includegraphics[width=\textwidth]{figures/mixed_gnn_0.035_0.112_qt_0.352_0.692.pdf} \caption{All traffic models multiplexed} \label{fig:all} \end{subfigure} \medskip \vspace{-0.05cm} \caption{CDF of the relative error for RouteNet-E and QT with different traffic models. Top row shows models with discrete state space, bottom row includes continuous state space. Each figure also shows numbers of the mean absolute relative error.} \label{fig:traffic_model} \vspace{-0.4cm} \end{figure*} \subsection{Evaluation Methodology} \vspace{0cm} To analyze the accuracy of RouteNet-E (Sec.~\ref{sec:RouteNet-E}) and benchmark it against the state-of-the-art queuing theory model (Sec.~\ref{qt}), we use the following methodology. In all the experiments the ground-truth is obtained with a packet-level simulator (see Sec.~\ref{subsec:sim-setup} for details). Unless noted otherwise, in each evaluation we perform 50k experiments with a random configuration (src-dst routing, traffic intensity, per-interface scheduling policy, and queue length) and compute the mean average delay, jitter, and losses. Then, we compute the error of RouteNet-E's and QT's estimates. For a fair comparison, we use samples of the GBN topology, which is not included during training (see Sec.~\ref{subsec:training} for training details). Finally, depending on the experiment we use different traffic models (Sec.~\ref{subsec:sim-setup}) and a wide range of realistic topologies. \vspace{0cm} \subsection{Traffic Models}\label{sec:traffic_models} This section focuses on analyzing the accuracy of RouteNet-E in a wide range of traffic models. The experiment is organized such that we add complexity to the traffic model by changing its first and second-order statistics (i.e., variance and autocorrelation). With this, we use challenging models that are good approximations to those seen in Internet links. Figure \ref{fig:traffic_model} shows the CDF of the relative error (in \%) for all the traffic models under evaluation. We plot the error for the delay and jitter estimates of both, RouteNet-E and QT. As we can observe, RouteNet-E achieves excellent results, producing very accurate estimates of delay and jitter in all traffic models, with a worst-case error below $6\%$ for delay and $12\%$ for jitter (mean absolute relative error). As expected, QT results in unacceptable performance in continuous-state traffic models (up to $68\%$ for delay), while it achieves moderate accuracy for discrete-state models. Interestingly, QT shows poor accuracy across all the experiments estimating jitter. The reason for this is that QT assumes independence between queues in the network. Hence, the estimator used for jitter is the sum of the individual delay variance of queues along flow paths, which ignores possible covariance effects between queues. It is remarkable that RouteNet-E is also accurate even with non-Markovian traffic models (On-Off, Figure~\ref{fig:onoff}) and with challenging models that approximate strong autocorrelation (Autocorrelated Exponentials, Figure \ref{fig:auto_exp}). For the latter, it has been shown in the literature that the TCP protocol generates traffic with autocorrelation for a finite range of time-scales~\cite{figueiredo2002autocorrelation}. In this scenario, RouteNet-E estimates the delay with a mean error of $3.24\%$. Figure \ref{fig:mod_exp} plots the accuracy for the Modulated Exponentials model, this emulates observations found at Internet links~\cite{traffic5} by approximating a heavy-tail. In this scenario, RouteNet-E still produces very accurate estimates. It is worth noting that this traffic model could be made even more difficult for QT by increasing both the variance and the autocorrelation factor. The key to RouteNet-E's performance is that it has been trained for such traffic models. As discussed in Section~\ref{sec:RouteNet-E}, we have parameterized the models and trained the GNN to learn the interaction between the traffic, the queues, and the resulting performance metrics. The experiments depicted in Figure \ref{fig:traffic_model} show that RouteNet-E can generalize to traffic, providing good accuracy even for traffic models with parameters not seen in training. RouteNet-E is designed to be an extensive model, adding a new traffic model is as simple as pasteurizing it and including it in training. To showcase this, consider the experiment shown in Figure~\ref{fig:all}, where we run 100k experiments with samples where each src-dst pair uses a \emph{random traffic model} with random parameters. Effectively, we multiplex all traffic models in a single network topology. As the figure shows, RouteNet-E is able to model this scenario in the presence of complex interactions of various multiplexed traffic models. \vspace{0cm} \subsection{Scheduling Policies} \label{subsec:sched_policies} With this experiment, we aim to validate that RouteNet-E is able to model the behavior of queues. For this we use 100K samples of the GBN topology, each router port is configured with three different queues and with a randomly selected scheduling policy (FIFO, WFQ, DRR, SP). For WFQ and DRR, the set of weights is also randomly assigned. Moreover, each src-dst path is assigned a Quality-of-Service class that maps traffic flows to specific queues. In order to provide a fair benchmark with QT, we use only Poisson traffic. Table \ref{tab:sched} summarizes the results, which are grouped for various traffic intensities, from low-loaded to highly-congested scenarios, where the mean packet loss rate is around $3\%$. As we can observe, RouteNet-E outperforms QT, obtaining highly accurate estimates for all the evaluated metrics. \begin{table}[!t] \setlength{\tabcolsep}{2pt} \resizebox{1\columnwidth}{!}{ \centering \begin{tabular}{c|ccc|ccc|ccc|} & \multicolumn{3}{c|}{\textbf{Delay}} & \multicolumn{3}{c|}{\textbf{Jitter}} & \multicolumn{3}{c|}{\textbf{Loss}} \\ \cline{2-10} & \textbf{Low} & \textbf{Med} & \textbf{High} & \textbf{Low} & \textbf{Med} & \textbf{High} & \textbf{Low} & \textbf{Med} & \textbf{High} \\ \cline{2-10} \textbf{RouteNet-E} & $2.0\%$ & $2.2\%$ & $3.3\%$ & $4.8\%$ & $6.2\%$ & $10.6\%$ & $12.61\%$ & $12.7\%$ & $12.66\%$ \\ \textbf{QT} & $13.0\%$ & $17.3\%$ & $25.1\%$ & $49.0\%$ & $53.2\%$ & $59.6\%$ & $61.83\%$ & $59.3\%$ & $57.9\%$ \end{tabular}% } \caption{Results for Scheduling Policies} \label{tab:sched} \vspace{-0.05cm} \end{table} \vspace{0cm} \subsection{Generalization to larger topologies}\label{sec:size_gen} The previous experiments have shown that RouteNet-E achieves remarkable accuracy in performance evaluation under different traffic models (Sec.~\ref{sec:traffic_models}) as well as complex scheduling policies (Sec.~\ref{subsec:sched_policies}). As we have discussed in Section~\ref{sec:challenges}, ML-based network models must generalize to unseen and \emph{larger} networks to become a practical solution. In this vein, RouteNet-E was carefully designed to address this challenge (see Sec.~\ref{sec:model} for details). In this set of experiments, we evaluate RouteNet-E in a wide range of networks considerably larger than the ones seen during training. Specifically, the model has been trained with topologies between 25 and 50 nodes and tested with topologies from 50 to 300 nodes. All these networks have been artificially generated using the Power-Law Out-Degree algorithm described in~\cite{palmer2000generating}, where the ranges of the $\alpha$ and $\beta$ parameters have been extrapolated from real-world topologies of the Internet Topology Zoo repository~\cite{6027859}. Link capacities and the generated traffic volume is scaled accordingly. Figure~\ref{fig:scalability} shows how RouteNet-E generalizes to larger topologies not seen in training. Specifically, the boxplots show the absolute relative error with respect to the topology size. As expected, RouteNet-E obtains better accuracy in topologies that are closer to the ones seen during the training phase (50 to 99 nodes), achieving an average error of $4.5\%$ (green line). As the topology size increases, the average error stabilizes to $\approx 10\%$. Note that this value is even lower than the one obtained by the QT model, which achieves a mean error of $12.6\%$ in samples with Poisson traffic (Fig.~\ref{fig:poisson}). We could not test larger topologies ($>$300) in our cluster (180 nodes), as packet-level simulations -- used for the ground-truth -- are sequential in nature, and, with our traffic configurations, have exponential complexity with respect to the topology size. Generalization is an open challenge in the field of GNN. As discussed in Sec.~\ref{sec:RouteNet-E}, we have addressed this by using domain-specific knowledge and data augmentation. Particularly, we infer delay/jitter from queues' occupation and apply our scale-independent method to generalize to larger topologies. \begin{figure}[!t] \centering \begin{minipage}[t]{.49\columnwidth} \centering \vspace{0cm} \includegraphics[width=\linewidth]{figures/scalability_results.pdf} \vspace{-0.4cm} \captionsetup{width=0.8\linewidth} \captionof{figure}{Absolute relative error vs. topology size.} \label{fig:scalability} \vspace{-0.5cm} \end{minipage}% \hfill \begin{minipage}[t]{.49\columnwidth} \centering \vspace{0cm} \includegraphics[width=\linewidth]{figures/exec_time.pdf} \vspace{-0.4cm} \captionsetup{width=0.8\linewidth} \captionof{figure}{Execution time vs. topology size.} \label{fig:exec_time} \vspace{-0.05cm} \end{minipage} \end{figure} \vspace{0cm} \subsection{Inference Speed} Finally, in this section, we evaluate the inference speed of RouteNet-E. Fast models are especially appealing for network control and management, as they can be deployed in real-time scenarios. For this, we have measured the execution times [Intel(R) Xeon(R) Gold 5220 CPU @ 2.20GHz] of the experiments in the previous section, for both QT and RouteNet-E. The results (Figure~\ref{fig:exec_time}) show that both models operate in the order of milliseconds. In particular, RouteNet-E goes from a few milliseconds for small topologies to a few hundred for the larger ones. \vspace{0cm} \section{Related Work} \vspace{0cm} The use of Deep Learning (DL) for network modeling has recently attracted the interest of the networking community. This idea was initially suggested by \emph{Wang, et al.} \cite{wang2017machine}. The authors survey different techniques and discuss data-driven models that can learn real networks. Initial attempts to instantiate this idea use fully connected neural networks (e.g. \cite{valadarsky2017learning, mestres2018understanding}). Such early attempts do not generalize to networks not seen in training, are not tested with realistic traffic models, and do not model queues. More recent works propose more elaborated neural network models, like Variational Auto-encoders \cite{xiao2018deep} or ConvNN \cite{chen2018deep}. However, they have similar limitations. Finally, some early pioneering works use GNN in the field of computer networks \cite{geyer2019deeptma, rusek2019unveiling, meng2020interpreting}. However, they use a basic GNN architecture that considers a simplified model of the network, ignoring traffic models, queuing policies, and the critical property of generalizing to larger networks. \vspace{0cm} \section{Discussion and Concluding remarks} \vspace{0cm} In this paper, we have presented RouteNet-E, a new tool for network modeling. RouteNet-E has shown remarkable accuracy in all the scenarios, outperforming a state-of-the-art QT model. RouteNet-E also overcomes the main limitation of QT, and it is able to model challenging traffic models. More importantly, the proposed model addresses the main drawback of existing ML-based models, and it is able to provide accurate estimates in larger networks ($\approx$10x). RouteNet-E provides unprecedented accuracy in network performance evaluation. However, in contrast to QT, it does not help understand the behavior of the network being modeled. The knowledge learned by RouteNet-E during training is not human-understandable. This is a common issue for all ML-based models, and substantial research efforts are being devoted to producing explainable ML models \cite{meng2020interpreting}. However, this is still an open research problem. RouteNet-E's performance enables network optimization, planning, and operation in real-time scenarios. It also represents an open-source extensible model. We hope that the community will use it as a baseline to incorporate additional network components, such as other scheduling policies, traffic models, etc. \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-01T02:57:14', 'yymm': '2202', 'arxiv_id': '2202.13956', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13956'}
arxiv
\section{Introduction} In the last thirty years Topological Data Analysis (TDA) developed as a useful mathematical theory for analyzing data, benefiting from the reduction of dimensionality guaranteed by topology \cite{EdHa08,BiDFFaal08,Ca2009}. One of the main tools in TDA is the concept of persistence diagram, which is a collection of points in the real plane, describing the homological changes of the sublevel sets of suitable continuous functions. These changes give important information about the data of interest, focusing on some of their most relevant properties. Persistence diagrams can be used in the presence of noise, since a well-known stability theorem states that these topological descriptors change in a controlled way when we know that the functions expressing the filtrations we are interested in change in a controlled way with respect to the sup-norm \cite{CSEdHa07}. Furthermore, $L^p$-stability of persistence diagrams with respect to the sup-norm have been proved in \cite{CoEdHaMi10}. Unfortunately, in many applications the sup-norm of the noise is not guaranteed to be small, and hence these results cannot be directly applied. In particular, these results cannot be directly used when data are affected by impulsive noise. Analogously, in the discrete setting of TDA the presence of outliers in cloud points can drastically affect the corresponding persistence diagrams. The problem of managing outliers has been studied by several authors by different techniques. In \cite{FaLeRiWaBaSi14} an approach based on confidence sets has been introduced. A method inspired from the $k$-nearest neighbors regression and the local median filtering has been used in \cite{BuChDeFaOuWa15}, while the concept of bagplot has been applied in \cite{AdAg19}. In \cite{ViFuKuSrBh20} an approach based on reproducing kernels has been proposed. In our paper we start exploring a different probabilistic approach, in the topological setting. The main idea is that studying the properties of data is a process that should be primarily based on the analysis of the observers that are asked to examine the data, since we cannot ignore that different observers can differently judge the same data. This approach has been initially proposed in \cite{BeFrGiQu19} and requires both the definition of the space of Group Equivariant Non-Expansive Operators (GENEOs) and the development of geometrical techniques to move around in this space \cite{CoFrQu22}. In other words, in this model we should not wonder how we have to manage the data but rather how we have to manage the observers (i.e., GENEOs) analyzing the data. As an initial step in this direction, in this paper we show how GENEOs can be used to get stability of persistence diagrams of 1D-signals in the presence of impulsive noise. GENEOs have been studied in \cite{FrJa16} as a new tool in TDA, since they allow for an extension of the theory that is not invariant under the action of every homeomorphism of the considered domain. This is important in applications where the invariance group is not the group of all homeomorphisms, such as the ones concerning shape comparison. Interestingly, GENEOs are also deeply related to the foliation method used to define the matching distance in 2-dimensional persistent homology \cite{CeDFFeal13,CeEtFr19} and can be seen as a theoretical bridge between TDA and Machine Learning \cite{BeFrGiQu19}. Furthermore, these operators make available lower bounds for the natural pseudo-distance $d_G(\varphi_1,\varphi_2) := \inf\limits_{g\in G} \|\varphi_1-\varphi_2\circ g\|_\infty$, associated with a group $G$ of self-homeomorphisms of the domain of the signals $\varphi_1,\varphi_2$ \cite{FrJa16}. In our paper, we prove that GENEOs can control the expected value of the perturbation of persistence diagrams caused by uniformly distributed impulsive noise, when data are represented by $L$-Lipschitz functions from $\mathbb{R}$ to $\mathbb{R}$. In order to do that, we choose a ``mother'' bump function $\psi$, i.e. a continuous function that is non-negative, upper bounded by $1$ and compactly supported, and we assume that our noise is made up of finite bumps each obtained by translating, heightening and/or widening $\psi$. The function $\hat\varphi=\varphi+R$ represents the corrupted data, where the noise is given by the function $R=\sum\limits_{i=1}^k a_i\psi(b_i(x-c_i))$ for some $a_i,b_i,c_i\in\mathbb{R}$, with $b_i>0$, and some positive integer $k$. In this situation, trying to use a convolution to approximate our starting data is not effective, because even if it does contract the bumps, it does not cut them, and hence does not improve the sup-norm distance from the original data. A classical approach for the removal of impulsive noise is the one of using a median filter\cite{Va08}. Although this approach would be quite efficient in the discrete case, let us remark that in our setting we are considering continuous functions. The analogous of the median for the continuous case would be defined as the interval of those values $m$ such that $$\int\limits_{-\infty}^{m} f(x)dx=\int\limits_{m}^{+\infty} f(x)dx$$ where $f$ is a density of probability. However, this operator is not stable: a small alteration of the starting function could lead to a significant change of the median. The operators we consider in this paper are $F^\delta=\max (\varphi(x-\delta),\varphi(x+\delta))$ and $F_\varepsilon=\min (\varphi(x-\varepsilon),\varphi(x+\varepsilon))$. The main idea is that $F^\delta$ cuts the noise ``directed downwards'' and $F_\varepsilon$ the noise ``directed upwards'', and hence their composition should be able to eliminate all the bumps. These operators are GENEOs with respect to isometries of the real line. We prove that moving in the space of GENEOs by taking suitable values for $\varepsilon$ and $\delta$, we can get quite close to restoring the original function $\varphi$, depending on how the bumps are positioned. The closer the bumps are to being Dirac delta functions and the further they are from each other, the better our approximation can be. On the ground of this result, we finally get an estimate of the expected value $E(\|F^{\delta} \circ F_\varepsilon (\hat\varphi)-\varphi\|_\infty)$. The paper is structured as follows. In Section 2 the mathematical background is laid. The case we consider and our notation are explained in Section 3. In Section 4 we prove the results that are needed in order to demonstrate our main result. In Section 5 the main theorem giving us a probabilistic upper bound is formulated. In Section 6 some examples and experiments are presented in order to better illustrate the use of our results. A brief discussion concludes the paper. \section{Mathematical setting} In this section we will recall some basic concepts we will use in this paper. \subsection{Representing data as real functions} Let us consider a set $\varPhi$ of bounded functions from a set $X$ to $\mathbb{R}$, which will represent the data we wish to compare. We shall call $\varPhi$ the set of \emph{admissible measurements} on $X$. We endow $\varPhi$ with the topology induced by the sup-norm $\|\cdotp\|_{\infty}$ and the corresponding distance $D_\varPhi$. A pseudo-metric $D_X$ can be defined on $X$ by setting $D_X(x_1,x_2)=\sup\limits_{\varphi\in\varPhi}\lvert \varphi(x_1)-\varphi(x_2)\rvert$ for every $x_1,x_2\in X$. We recall that a pseudo-metric on a set $X$ is a distance $d$ without the property $d(x,y)=0\implies x=y$. We will consider the topological space $(X,\tau_{D_X})$ where $\tau_{D_X}$ is the topology induced by $D_X$. A base for this topology is given by the open balls $\{B(x,r):=\{x'\in X:D_X(x,x')<r\}$ with $x\in X$, $r\in\mathbb{R}\}$. The choice of this topology makes every function in $\varPhi$ a continuous functions. As shown in \cite{BeFrGiQu19}, this fact enables us to use persistence diagrams in the study of $\varPhi$. \subsection{GENEOs as operators acting on data} We are interested in considering transformations of data. Let $\mathrm{Homeo}_\varPhi(X)$ be the set of $\varPhi$-preserving homeomorphisms from $X$ to $X$ with respect to the topology $\tau_{D_X}$, meaning that every $g$ in $\mathrm{Homeo}_\varPhi(X)$ is a homeomorphism of $X$ such as both $\varphi \circ g$ and $\varphi \circ g^{-1}$ belong to $\varPhi$ for every $\varphi$ in $\varPhi.$ Let $G$ be a subgroup of $\mathrm{Homeo}_\varPhi(X)$. $G$ represents the set of transformations on data for which we will require equivariance to be respected. Under the previously stated assumptions we call the ordered pair $(\varPhi,G)$ a \emph{perception pair}. We can now introduce the concept of GENEO. \begin{definition} Let $(\varPhi,G)$ and $(\Psi,H)$ be perception pairs and assume that a homomorphism $T:G \to H$ is given. A function $F:\varPhi \to \Psi$ is called a \emph{Group Equivariant Non-Expansive Operator (GENEO) from $(\varPhi,G)$ to $(\Psi,H)$ with respect to $T$} if the following properties hold: \begin{enumerate} \item (Group Equivariance) $F(\varphi \circ g) =F(\varphi) \circ T(g)$ for every $\varphi \in \varPhi,g \in G$; \item (Non-Expansivity) $D_\Psi(F(\varphi_1),F(\varphi_2))\leq D_\varPhi(\varphi_1,\varphi_2)$ for every $\varphi_1,\varphi_2\in\varPhi$. \end{enumerate} \end{definition} Let us now consider the set $\mathcal{F}_{\mathrm{all}}$ of all GENEOs from $(\varPhi,G)$ to $(\Psi,H)$ with respect to $T:G\to H$. The space $\mathcal{F}_{\mathrm{all}}$ is endowed with the extended pseudo-metric $D_{\mathcal{F}_{\mathrm{all}}}$, defined by setting $D_{\mathcal{F}_{\mathrm{all}}}(F_1,F_2)=\sup_{\varphi\in\varPhi} D_\Psi(F_1(\varphi),F_2(\varphi))$ for every $F_1,F_2\in\mathcal{F}_{\mathrm{all}}$. The word \emph{extended} refers to the possibility that $D_{\mathcal{F}_{\mathrm{all}}}$ takes an infinite value. The following result can be proven \cite{BeFrGiQu19}: \begin{theorem} If $(\varPhi,D_\varPhi)$,$(\Psi,D_\Psi)$ are compact and convex then the metric space $(\mathcal{F}_{\mathrm{all}},D_{\mathcal{F}_{\mathrm{all}}})$ is compact and convex. \end{theorem} If a non-empty set $\mathcal{F}\subseteq \mathcal{F}_{\mathrm{all}}$ is fixed, we can define the following pseudo-distance $D_{\mathcal{F},\varPhi}$ on $\varPhi$: \begin{definition} For any $\varphi_1,\varphi_2$ in $\varPhi$ we set $$D_{\mathcal{F},\varPhi}(\varphi_1,\varphi_2)=\sup_{F\in\mathcal{F}} \|F(\varphi_1)-F(\varphi_2)\|_\infty.$$ \end{definition} This pseudo-distance allows us to compare data by taking into account how agents operate on data. Notice how, if $G$ becomes larger, the natural pseudo-distance $d_G$ becomes harder to compute but this new pseudo-distance $D_{\mathcal{F},\varPhi}$ becomes easier to evaluate. In order to find a lower bound for $D_{\mathcal{F},\varPhi}$ it is useful to introduce the notion of persistence diagram. \subsection{Persistence Diagrams} We will now recall some basic definitions and results in persistent homology. The interested reader can find more details in \cite{EdHa08}. Let us consider an ordered pair $(X,\varphi)$ where $X$ is a topological space and $\varphi:X\to\mathbb{R}$ is a continuous function. For any $t\in\mathbb{R}$ we can set $X_t:=\varphi^{-1}(\left]-\infty,t\right])$. If $u<v$ the inclusion $i_{u,v}:X_u\to X_v$ induces a homomorphism $i^k_{u,v}:H_k(X_u)\to H_k(X_v)$ between the $k$\textsuperscript{th} homology groups of $X_u$ and $X_v$. We can define the \emph{$k$\textsuperscript{th} persistent homology group}, with respect to $\varphi$ and computed at the point $(u,v)$, as $PH_k(u,v):=i^k_{u,v}(H_k(X_u))$. Moreover, we can define the \emph{$k$\textsuperscript{th} persistent Betti numbers function} $r_k(u,v)$ as the rank of $PH_k(u,v)$. The $k$\textsuperscript{th} persistent Betti numbers function can be represented by the $k$\textsuperscript{th} persistence diagram. This diagram is defined as the multi-set of all the ordered pairs $(u_j, v_j),$ where $u_j$ and $v_j$ are the times of birth and death of the $j$\textsuperscript{th} $k$-dimensional hole in $X$, respectively. We call \emph{time of birth} of a hole the first time at which the homology class appears, and \emph{time of death} the first time at which the homology class merges with an older one. When a hole never dies, we set its time of death equal to $\infty$. We also add to this set all points of the form $(w,w)$ for $w\in\mathbb{R}$. In Figure~\ref{filtration} the filtration of the set $X:=\left[0,\frac{3}{4}\pi\right]$ given by the function $\varphi(x)=2\sin x$ is illustrated. In this example, the topology on $X$ is the one defined by the space $\varPhi$ of admissible functions given by all functions $a\sin(x+b)$ with $a,b\in \mathbb{R}$. The reader can easily check that this topology coincides with the Euclidean topology. The persistence diagram in degree $k=0$ of the function $\varphi$ is displayed in Figure~\ref{pd}. \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{t_is_below0.jpg} & \includegraphics[width=4.8cm]{t_is_1.jpg} \\ \includegraphics[width=4.8cm]{t_is_1,6.jpg} & \includegraphics[width=4.8cm]{t_is_above2.jpg} \\ \end{tabular} \caption{How the sublevel sets change with respect to the filtration induced by $\varphi$.} \label{filtration} \end{center} \end{figure} \begin{figure}[t] \begin{center} \includegraphics[width=4.8cm]{dgm_esempio.jpg} \end{center} \caption{Persistence diagram of the function $2\sin x$ on $\left[0,\frac{3}{4}\pi\right]$. The point $(0,\infty)$ describes the existence of a connected component that is born at zero and never dies. The point $(\sqrt{2},2)$ claims that there is a connected component born at $\sqrt{2}$ that dies (merges with the other one) at 2. The trivial points on the diagonal $u=v$ are not displayed.} \label{pd} \end{figure} \subsection{Comparing Persistence Diagrams} Persistence diagrams can be efficiently compared by means of a suitable metric $d_{\mathrm{match}}$. In order to define it, we first define the pseudo-distance $$\delta((x,y),(x',y'))= \min\{\max\{\lvert x-x'\rvert,\lvert y-y'\rvert\},\max\{\lvert x-y\rvert/2,\lvert x'-y'\rvert/2\}\}$$ for all $(x,y),(x',y')\in\{(x,y)\in\mathbb{R}$ with $x\leq y\}\cup\{(x,\infty)$ with $x\in\mathbb{R}\}$ by agreeing that $\infty-y=\infty, y-\infty=-\infty$ for $y\not=\infty, \infty-\infty=0, \infty/2=\infty, \lvert\pm\infty\rvert =\infty, \min\{\infty,c\} = c,\max\{\infty, c\} = \infty$. If two persistence diagrams $D,D'$ are given, we can set $$d_{\mathrm{match}}(D,D')=\inf\limits_{\sigma\in\Sigma} \sup\limits_{P\in D} \delta(P,\sigma(P))$$ where $\Sigma$ represents the set of all bijections between the multisets $D,D'$. For every degree $k$ we can now define a new pseudo-metric: $$D_{\mathcal{F},\varPhi}^{\mathrm{match}}(\varphi_1,\varphi_2)=\sup_{F\in\mathcal{F}} d_{\mathrm{match}}(D_{F(\varphi_1)},D_{F(\varphi_2)})$$ where $D_{F(\varphi_1)},D_{F(\varphi_2)}$ are the persistence diagrams at degree $k$ of the functions $F(\varphi_1),F(\varphi_2)$, respectively. In this paper we will limit ourselves to considering data represented as functions from $\mathbb{R}$ to $\mathbb{R}$, and we recall that for this kind of data persistence diagrams are non-trivial only in degree $k=0$ (i.e., when persistent homology is used to count connected components). For this reason, in the following we will always assume $k=0$. \section{Our model} \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{INTRO_PHI.jpg} & \includegraphics[width=4.8cm]{DGM_INTRO_PHI.jpg} \\ \includegraphics[width=4.8cm]{INTRO_HATPHI.jpg} & \includegraphics[width=4.8cm]{DGM_INTRO_HATPHI.jpg} \\ \end{tabular} \caption{How drastically impulsive noise can influence persistence diagrams.} \end{center} \end{figure} In this paper we will be mainly interested in the set $\mathrm{Lip}_L$ of all $L$-Lipschitz functions from $\mathbb{R}$ to $\mathbb{R}$, for some fixed constant $L\in\mathbb{R}$, and in the set $C^0(\mathbb{R})$ of all functions from $\mathbb{R}$ to $\mathbb{R}$ that are continuous with respect to the Euclidean topology. We will set $X=\mathbb{R}$ and consider the perception pairs $(\mathrm{Lip}_L,G)$, $(C^0(\mathbb{R}),G)$, where $G$ is the group of the Euclidean isometries of $\mathbb{R}$. We will assume our noise to be made up of a finite number of copies of a ``mother'' nonnegative continuous bump function $\psi:\mathbb{R}\to\mathbb{R}$, such that $\mathrm{supp}(\psi)\subseteq\left]-\sigma,\sigma\right[$ for some $\sigma>0$ and $\|\psi\|_\infty\leq 1$. We recall that the support of a function is the closure of the set of points where $f$ is non-vanishing. After fixing two positive real numbers $\eta,\beta$, the noise we will be adding is a function $R$ belonging to the space $\mathcal{R}_{\eta,\beta}$ that contains the null function and all functions of the form $\sum\limits_{i=1}^k a_i\psi(b_i(x-c_i))$, where $k$ is a positive integer and $a_i,b_i,c_i$ are real numbers such that $\lvert c_i-c_j\rvert\ge\eta$ for $i\not=j$ and $b_i\ge\beta$ for every index $i$. For any $R\in\mathcal{R}_{\eta,\beta}$ we define $S(R):=\bigcup\limits_{i=1}^k \left]c_i-\frac{\sigma}{\beta},c_i+\frac{\sigma}{\beta}\right[$ and remark that if $x\not\in S(R)$ then $R(x)=0$. Our purpose will be the one of recovering $\varphi\in\mathrm{Lip}_L$ as well as possible from the function $\hat\varphi=\varphi+R$. An example of such situation is depicted in Figure~\ref{corruptedphi}. \begin{figure}[t] \begin{tabular}{c c c} \includegraphics[width=4cm]{phi.jpg} & \includegraphics[width=4cm]{noise.jpg} & \includegraphics[width=4cm]{noisy_phi.jpg} \end{tabular} \caption{In the figure on the left we have our original function $\varphi$, in the middle a noise function R and in the right figure the corrupted function $\hat\varphi:=\varphi+R$.}\label{corruptedphi} \end{figure} The following result will be of use. \begin{proposition}\label{propcomp} Let $F_1,F_2$ be GENEOs from $(C^0(\mathbb{R}),G)$ to $(C^0(\mathbb{R}),G)$ with respect to the trivial homomorphism $T=\mathrm{id}:G\to G$. Then $F_1\circ F_2$ is a GENEO from $(C^0(\mathbb{R}),G)$ to $(C^0(\mathbb{R}),G)$ with respect to $T$. \end{proposition} \begin{proof} For every $\varphi \in C^0(\mathbb{R}),g \in G$ we have that \begin{align*} F_1 \circ F_2(\varphi \circ g)&=F_1(F_2(\varphi \circ g)) \\ &=F_1(F_2(\varphi) \circ g) \\ &=F_1(F_2(\varphi)) \circ g \\ &=(F_1 \circ F_2)(\varphi) \circ g. \end{align*} Therefore, $F_1\circ F_2$ is $G$-equivariant. Moreover, for any $\varphi_1,\varphi_2 \in C^0(\mathbb{R})$ \begin{align*} D_{C^0(\mathbb{R})}(F_1 \circ F_2(\varphi_1)),F_1\circ F_2(\varphi_2))&=D_{C^0(\mathbb{R})}(F_1(F_2(\varphi_1)),F_1(F_2(\varphi_2))) \\ &\le D_{C^0(\mathbb{R})}(F_2(\varphi_1)),F_2(\varphi_2)) \\ &\le D_{C^0(\mathbb{R})}(\varphi_1,\varphi_2). \end{align*} It follows that $F_1\circ F_2$ is non-expansive. \end{proof} \section{Cutting off the noise by GENEOs} We start by introducing two families of GENEOs from $(C^0(\mathbb{R}),G)$ to $(C^0(\mathbb{R}),G)$ with respect to the identical homomorphism. \begin{definition} Let $\varphi \in \mathrm{Lip}_L$ and $\varepsilon>0$. For all $x\in\mathbb{R}$ we define: \begin{enumerate} \item $F^\varepsilon(\varphi)(x)=\max (\varphi(x-\varepsilon),\varphi(x+\varepsilon))$; \item $F_\varepsilon(\varphi)(x)=\min (\varphi(x-\varepsilon),\varphi(x+\varepsilon))$. \end{enumerate} \end{definition} \begin{proposition} The maps $F^\varepsilon$ and $F_\varepsilon$ are GENEOs from $(C^0(\mathbb{R}),G)$ to $(C^0(\mathbb{R}),G)$ with respect to the identical homomorphism. \end{proposition} \begin{proof} We start by proving that $F^\varepsilon$ is $G$-equivariant. Let $g$ be the translation $x \mapsto x+k$ with $k \in \mathbb{R}$, then \begin{align*} F^\varepsilon(\varphi \circ g) &=\max\{\varphi((x+k)-\varepsilon),\varphi((x+k)+\varepsilon)\} \\ &=\max\{\varphi((x-\varepsilon)+k),\varphi((x+\varepsilon)+k)\} \\ &=F^\varepsilon(\varphi) \circ g. \end{align*} Let $g$ be the symmetry $x \mapsto -x$, then \begin{align*} F^\varepsilon(\varphi \circ g) &=\max\{\varphi((-x)-\varepsilon),\varphi((-x)+\varepsilon)\} \\ &=\max\{\varphi(-(x+\varepsilon)),\varphi(-(x-\varepsilon))\} \\ &=\max\{\varphi(x+\varepsilon),\varphi(x-\varepsilon)\} \circ g \\ &=F^\varepsilon(\varphi) \circ g. \end{align*} Since every isometry in $G$ can be written as the composition of a symmetry and a translation, our statement follows. Furthermore, for any $x\in\mathbb{R}$ \begin{align*} &\lvert F^\varepsilon(\varphi_1)(x)-F^\varepsilon(\varphi_2)(x)\rvert= \\ &=\lvert\max\{\varphi_1(x-\varepsilon),\varphi_1(x+\varepsilon)\}-\max\{\varphi_2(x-\varepsilon),\varphi_2(x+\varepsilon)\}\rvert \\ &\le\max\{\lvert\varphi_1(x-\varepsilon)-\varphi_2(x-\varepsilon)\rvert,\lvert\varphi_1(x+\varepsilon)-\varphi_2(x+\varepsilon)\rvert\} \\ &\le\max\{\|\varphi_1-\varphi_2\|_\infty,\|\varphi_1-\varphi_2\|_\infty\} \\ &=\|\varphi_1-\varphi_2\|_\infty. \end{align*} It follows that $\|F^\varepsilon(\varphi_1)-F^\varepsilon(\varphi_2)\|_\infty\le\|\varphi_1-\varphi_2\|_\infty$, and hence $F^\varepsilon$ is non-expansive. We observe that $\min\{a,b\}=-\max\{-a,-b\}$, and hence $F_\varepsilon(\varphi)=-F^\varepsilon(-\varphi)$ for every $\varphi\in C^0(\mathbb{R})$. Moreover, the map taking $\varphi$ to $-\varphi$ is a GENEO from $(C^0(\mathbb{R}),G)$ to $(C^0(\mathbb{R}),G)$ with respect to the identical homomorphism. Therefore, Proposition~\ref{propcomp} guarantees that $G$-equivariance and non-expansivity also hold for $F_\varepsilon$. \end{proof} Since Proposition~\ref{propcomp} shows that the composition of GENEOs is still a GENEO, the operator $F^{\delta} \circ F_\varepsilon$ is a GENEO from $(C^0(\mathbb{R}),G)$ to $(C^0(\mathbb{R}),G)$ with respect to the identical homomorphism. We want now to prove that if a function $\hat\varphi$ is obtained by adding impulsive noise to a function $\varphi$ then the value of $$\|F^\delta \circ F_\varepsilon (\hat\varphi)-\varphi\|_\infty$$ is bounded, and possibly small, provided that $\delta$ and $\varepsilon$ are suitably chosen. The main idea is that the operator $F_\varepsilon$ cuts the noise ``directed upwards'' and $F^\delta$ cuts the noise ``directed downwards''. In order to proceed, we need two lemmas. \begin{lemma} \label{lemma1} Let $R\in C^0(\mathbb{R},\mathbb{R})$, $\varphi\in \mathrm{Lip}_L$ for some $L\in\mathbb{R}$, and set $\hat\varphi:=\varphi+R$. Then for any $\varepsilon>0$ and $\delta>0$ \begin{description} \item[$\mathrm{i)}$] $-L\varepsilon+F_\varepsilon(R)\leq F_\varepsilon(\hat\varphi)-\varphi \leq L\varepsilon+F_\varepsilon(R)$; \item[$\mathrm{ii)}$] $-L\delta+F^\delta(R)\leq F^\delta(\hat\varphi)-\varphi \leq L\delta+F^\delta(R)$; \item[$\mathrm{iii)}$] $-L(\delta+\varepsilon)+F^\delta\circ F_\varepsilon(R)\leq F^\delta\circ F_\varepsilon(\hat\varphi)-\varphi \leq L(\delta+\varepsilon)+F^\delta\circ F_\varepsilon(R)$. \end{description} \end{lemma} \begin{proof} Since $\varphi$ is Lipschitz of constant $L$ we have that for any value $x\in\mathbb{R}$ $\lvert\varphi(x-\varepsilon)-\varphi(x)\rvert\leq L\varepsilon$ and $\lvert\varphi(x+\varepsilon)-\varphi(x)\rvert\leq L\varepsilon$. Therefore, \begin{align*} F_\varepsilon(\hat\varphi)(x)&=F_\varepsilon(\varphi+R)(x) \\ &=\min\{\varphi(x-\varepsilon)+R(x-\varepsilon),\varphi(x+\varepsilon)+R(x+\varepsilon)\} \\ &\leq\min\{\varphi(x)+L\varepsilon+R(x-\varepsilon),\varphi(x)+L\varepsilon+R(x+\varepsilon)\} \\ &=\varphi(x)+L\varepsilon+\min\{R(x-\varepsilon),R(x+\varepsilon)\} \\ &=\varphi(x)+L\varepsilon+F_\varepsilon(R)(x). \end{align*} Analogously, $F_\varepsilon(\hat\varphi)(x)\geq\varphi(x)- L\varepsilon+F_\varepsilon(R)(x)$. The same steps applied to $F^\delta$ yield the second statement of the lemma. As for the last claim we can see that: \begin{align*} &F^\delta\circ F_\varepsilon(\hat\varphi)(x) \\ &=\max\{F_\varepsilon(\hat\varphi)(x-\delta),F_\varepsilon(\hat\varphi)(x+\delta)\} \\ &\leq\max\{\varphi(x-\delta)+L\varepsilon+F_\varepsilon(R)(x-\delta),\varphi(x+\delta)+L\varepsilon+F_\varepsilon(R)(x+\delta)\} \\ &\leq\max\{\varphi(x)+L\delta+L\varepsilon+F_\varepsilon(R)(x-\delta),\varphi(x)+L\delta+L\varepsilon+F_\varepsilon(R)(x+\delta)\} \\ &=\varphi(x)+L\delta+L\varepsilon+\max\{F_\varepsilon(R)(x-\delta),F_\varepsilon(R)(x+\delta)\} \\ &=\varphi(x)+L\delta+L\varepsilon+F^\delta\circ F_\varepsilon(R)(x). \end{align*} Analogously, we can prove the lower bound. \end{proof} Henceforth we will assume that any summation on an empty set of indexes is the null function. \begin{lemma} \label{lemma2} Let $R\in\mathcal{R}_{\eta,\beta}$ and $\lambda\ge\frac{\sigma}{\beta}$. If $\lambda\le\rho\le\frac{\eta}{2}-\lambda$ then \begin{description} \item[$\mathrm{a)}$] $F_\rho(R)(x)=\sum\limits_{a_i<0} \left[a_i\psi(b_i(x-\rho-c_i))+a_i\psi(b_i(x+\rho-c_i))\right]\leq0$ \item[$\mathrm{b)}$] $F^\rho(R)(x)=\sum\limits_{a_i>0} \left[a_i\psi(b_i(x-\rho-c_i))+a_i\psi(b_i(x+\rho-c_i))\right]\geq0$ \end{description} for all $x\in\mathbb{R}$. Moreover $F_\rho(R),F^\rho(R)(x)\in\mathcal{R}_{2\lambda,\beta}$. \end{lemma} \begin{proof} We will suppose without loss of generality that $c_i<c_{i+1}$ for all $i=1,\dots,k-1$ and $a_i\not=0$ for all indexes $i$. We want to show that at least one of $x-\rho$ and $x+\rho$ must always be outside of $\bigcup\limits_{i=1}^k \left]c_i-\lambda,c_i+\lambda\right[$. If by contradiction both $x-\rho$ and $x+\rho$ were in the same $\left]c_i-\lambda,c_i+\lambda\right[$ then we would have $\rho<\lambda$, against our hypotheses. Moreover $x-\rho$ and $x+\rho$ cannot belong to different intervals $\left]c_i-\lambda,c_i+\lambda\right[$ and $\left]c_j-\lambda,c_j+\lambda\right[$ for $i<j$: if by contradiction $x-\rho\in\left]c_i-\lambda,c_i+\lambda\right[$ and $x+\rho\in\left]c_j-\lambda,c_j+\lambda\right[$ for some $i<j$ then $2\rho=x+\rho-(x-\rho)> (c_j-\lambda)-(c_i+\lambda)\geq c_j-c_i-2\lambda\geq \eta-2\lambda$, and hence we would have $\rho>\frac{\eta}{2}-\lambda$, against our hypotheses. Since $\left]c_i-\frac{\sigma}{\beta},c_i+\frac{\sigma}{\beta}\right[\subseteq\left]c_i-\lambda,c_i+\lambda\right[$, it follows that at least one among the values $R(x-\rho)$ and $R(x+\rho)$ must always be zero. Let us now set $I^-_i:=\left](c_i-\rho)-\lambda,(c_i-\rho)+\lambda\right[$ and $I^+_i:=\left](c_i+\rho)-\lambda,(c_i+\rho)+\lambda\right[$. These two intervals must be disjoint, since $(c_i+\rho-\lambda)-(c_i-\rho+\lambda)=2\rho-2\lambda\ge0$. Let us now consider $\{I^-_1,I^+_1,\ldots,I^-_k,I^+_k\}$. We will now prove that any two distinct elements from this set must be disjoint. Since we have just proven that $I^-_i\cap I^+_i=\emptyset$ for $i=1,\dots,k$, the following holds in the case $i<j$: \begin{enumerate} \item $I^+_i\cap I^+_j=\emptyset$, since $c_j+\rho-\lambda-(c_i+\rho+\lambda)\geq c_j-c_i-2\lambda\ge\eta-2\lambda\ge0$; \item $I^-_i\cap I^-_j=\emptyset$, since $c_j-\rho-\lambda-(c_i-\rho+\lambda)\geq c_j-c_i-2\lambda\ge\eta-2\lambda\ge0$; \item $I^+_i\cap I^-_j=\emptyset$, since $c_j-\rho-\lambda-(c_i+\rho+\lambda)\geq c_j-c_i-2\rho-2\lambda\ge\eta-2\left(\frac{\eta}{2}-\lambda\right)-2\lambda=0$; \item $I^+_j\cap I^-_i$, since $c_j+\rho-\lambda-(c_i-\rho+\lambda)\geq c_j-c_i+2\rho-2\lambda\ge\eta+2\lambda-2\lambda\ge0$. \end{enumerate} Let us now fix $k\in\{1,\dots,k\}$. Since $\mathrm{supp}(a_k\psi(b_k(x-c_k)))\subseteq\left]c_k-\lambda,c_k+\lambda\right[$, then $\mathrm{supp}(a_k\psi(b_k(x-\rho-c_k)))\subseteq I^-_k$ and $\mathrm{supp}(a_k\psi(b_k(x+\rho-c_k)))\subseteq I^+_k$. Hence, for any $x\in\mathbb{R}$ we have that \begin{align*} F_\rho(R)(x)&=\min\{R(x-\rho),R(x+\rho)\} \\ &= \begin{cases} 0 &\mbox{if } x\notin\bigcup\limits_{i=1}^k (I_i^-\cup I_i^+) \\ a_j\psi(b_j(x+\rho-c_j)) &\mbox{if } x\in I^-_j \text{ and } a_j<0 \\ a_j\psi(b_j(x-\rho-c_j)) &\mbox{if } x\in I^+_j \text{ and } a_j<0. \end{cases} \end{align*} This means that $$F_\rho(R)(x)=\sum\limits_{a_i<0} \left[a_i\psi(b_i(x-\rho-c_i))+a_i\psi(b_i(x+\rho-c_i))\right]\leq0.$$ Now, given $c_i+\rho$ and $c_j-\rho$ centers of bumps of $F_\rho(R)$, we have that $$\lvert(c_i+\rho)-(c_j-\rho)\rvert\geq\min\{\eta-2\rho,2\rho\}\geq2\lambda.$$ It follows that $F_\rho(R)\in\mathcal{R}_{2\lambda,\beta}$. By noticing that $F^\rho(R)=-F_\rho(-R)$ we get the second part of the thesis. \end{proof} Let us remark that, in particular, if $\lambda=2\frac{\sigma}{\beta}$ then $F_\rho(R),F^\rho(R)\in\mathcal{R}_{4\frac{\sigma}{\beta},\beta}$. We observe that in order to exist a $\rho$ that satisfies the hypotheses of Lemma~\ref{lemma2}, the inequality $\eta\ge4\lambda$ must hold. We are now actually ready to prove a key result in our paper. \begin{theorem} \label{Upper Bound} Given $\theta,\beta,L\in\mathbb{R}$, let ${\bar R}\in\mathcal{R}_{\theta,\beta}$, $\varphi\in \mathrm{Lip}_L$ and set $\hat\varphi:=\varphi+{\bar R}$. If $2\frac{\sigma}{\beta}\le\varepsilon\le\frac{\theta}{2}-2\frac{\sigma}{\beta}$ then for any $\frac{\sigma}{\beta}\le\delta\le\frac{1}{2}\min\{\theta-2\varepsilon,2\varepsilon\}-\frac{\sigma}{\beta}$ the following inequality holds: $$\|F^{\delta} \circ F_\varepsilon (\hat\varphi)-\varphi\|_\infty\leq L(\varepsilon+\delta).$$ \end{theorem} \begin{proof} Let $x\in\mathbb{R}$. Firstly, let us notice that the condition $2\frac{\sigma}{\beta}\le \varepsilon\le \frac{\theta}{2}-2\frac{\sigma}{\beta}$ implies that $\frac{\sigma}{\beta}\le \frac{1}{2}\min\{\theta-2\varepsilon,2\varepsilon\} - \frac{\sigma}{\beta}$. From Lemma~\ref{lemma1} we know that $$-L(\delta+\varepsilon)+F^\delta\circ F_\varepsilon({\bar R})(x)\leq F^\delta\circ F_\varepsilon(\hat\varphi)(x)-\varphi(x) \leq L(\delta+\varepsilon)+F^\delta\circ F_\varepsilon({\bar R})(x).$$ Let us now prove that $F^\delta\circ F_\varepsilon({\bar R})(x)=0$. By applying Lemma~\ref{lemma2} with $\eta:=\theta$, $\lambda:=2\frac{\sigma}{\beta}$, $\rho:=\varepsilon$ and $R:={\bar R}$ we get $$F_\varepsilon({\bar R})(x)=\sum\limits_{a_i<0} \left[a_i\psi(b_i(x-\varepsilon-c_i))+a_i\psi(b_i(x+\varepsilon-c_i))\right]\le0.$$ Let us remark that $F_\varepsilon({\bar R})\in\mathcal{R}_{4\frac{\sigma}{\beta},\beta}$. Moreover, \begin{enumerate} \item $F^\delta\circ F_\varepsilon({\bar R})(x)=\max\{F_\varepsilon({\bar R})(x-\delta),F_\varepsilon({\bar R})(x+\delta)\}\le0$ since both terms are negative; \item $F^\delta \circ F_\varepsilon({\bar R})(x)=F^\delta(F_\varepsilon({\bar R}))(x)\ge0$. \end{enumerate} These inequalities follow from Lemma~\ref{lemma2}, by setting $\eta:=4\frac{\sigma}{\beta}$, $\lambda:=\frac{\sigma}{\beta}$, $\rho:=\delta$ and $R:=F_\varepsilon({\bar R})$. Therefore, we have proved that $\lvert F^\delta\circ F_\varepsilon(\hat\varphi)(x)-\varphi(x)\rvert\leq L(\delta+\varepsilon$) for any $x\in\mathbb{R}$. It follows that $\|F^{\delta} \circ F_\varepsilon (\hat\varphi)-\varphi\|_\infty\leq L(\varepsilon+\delta)$. \end{proof} Let us remark that Theorem~\ref{Upper Bound} works under the (only) implicit assumption that $\theta\ge8\frac{\sigma}{\beta}$. In our setting this should not be restrictive since it means that the noise added is made up of scattered, thin bumps, without any reference to the height of the bumps: this is what we expect when considering additive impulsive noise. \begin{corollary} \label{coroll2} Given $\theta,\beta,L\in\mathbb{R}$, let $R\in\mathcal{R}_{\theta,\beta}$, $\varphi\in \mathrm{Lip}_L$, and set $\hat\varphi:=\varphi+R$. If $\theta\ge8\frac{\sigma}{\beta}$, then $$\left\|F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}} \left(\hat\varphi\right)-\varphi\right\|_\infty\leq 3L\frac{\sigma}{\beta}.$$ \end{corollary} \begin{proof} The claim follows from Theorem~\ref{Upper Bound} by taking $\varepsilon:=2\frac{\sigma}{\beta}$ and $\delta:=\frac{\sigma}{\beta}.$ \end{proof} Corollary~\ref{coroll2} and the well known stability of persistence diagrams with respect to the max-norm \cite{CSEdHa07} immediately imply the following result, which is of interest in TDA (the symbol $d_{\mathrm{match}}$ denotes the usual bottleneck distance between persistence diagrams). \begin{corollary} \label{coroll3} Given $\theta,\beta,L\in\mathbb{R}$, let $R\in\mathcal{R}_{\theta,\beta}$, $\varphi\in \mathrm{Lip}_L$, and set $\hat\varphi:=\varphi+R$. If $\theta\ge8\frac{\sigma}{\beta}$, and $D$ and $D'$ are the persistence diagrams in degree $0$ of the filtering functions $\varphi$ and $F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)$, respectively, then $$d_{\mathrm{match}}(D,D')\le 3L\frac{\sigma}{\beta}.$$ \end{corollary} % % \section{Our main result} We are now ready to prove our main result. We start by stating a lemma concerning the probability $p$ that any two distinct points in a randomly chosen set of cardinality $k$ in an interval of length $\ell$ have a distance greater than $\eta$. A proof of the following lemma is provided in \cite{2001026}: for the reader's convenience, we report it here. \begin{lemma}\label{lemma3} Let $X_{1},\dots,X_{k}$, with $k\ge 2$, be independent random variables, uniformly distributed on the interval $[0,\ell]$, for some $\ell>0$. Let $$M:=\min_{1\le i,j\le k\atop i\neq j}\lvert X_{i}-X_{j}\rvert$$ be the minimal distance between two distinct random variables. Then we have $$P(M>\eta)= \begin{cases} 1 & \text{if } \eta\le 0,\\ \left(1-\frac{(k-1)\eta}{\ell}\right)^{k} & \text{if } 0<\eta<\frac{\ell}{k-1}, \\ 0 & \text{if } \eta\ge\frac{\ell}{k-1}. \end{cases} $$ \end{lemma} \begin{proof It suffices to consider the case $0<\eta<\frac{\ell}{k-1}$. By symmetry, we have \begin{align}\nonumber P(M>\eta)&=k!\,P((M>\eta)\cap(X_{1}<X_{2}<\cdots<X_{k})) \intertext{(since $X_{1},\dots,X_{k}$ are uniformly distributed)}\label{a1} &=k!\,\frac{\text{Leb}(S)}{\ell^{k}} \end{align} where $S=\{x\in[0,\ell]^{k}\mid x_{1}<x_{2}-\eta<x_{3}-2\eta<\cdots<x_{k}-(k-1)\eta\}$ and $\text{Leb}$ denotes the Lebesgue measure. Setting $y_{i}=x_{i}-(i-1)\eta$ for $i=1,\dots,k$, we have that $\text{Leb}(S)=\text{Leb}(S')$ where $$S'=\{y\in[0,\ell-(k-1)\eta]^{k}\mid y_{1}<y_{2}<\cdots<y_{k}\}.$$ On the other hand, again by symmetry, we have $$\text{Leb}(S')=\frac{\text{Leb}([0,\ell-(k-1)\eta]^{k})}{k!}=\frac{(\ell-(k-1)\eta)^{k}}{k!}$$ and plugging this last identity into \eqref{a1} we get the thesis. \end{proof} We can now prove the following result, concerning the expected value of the error $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty$. \begin{theorem} \label{main_result} Let us choose a function $\varphi\in\mathrm{Lip}_L$, a non-negative continuous function $\psi:\mathbb{R}\to\mathbb{R}$ with $\|\psi\|_\infty\leq 1$ and $\mathrm{supp}(\psi)\subseteq\left]-\sigma,\sigma\right[$ for some $\sigma>0$, two positive numbers $\beta$ and $\ell$, and an integer $k\ge 2$. For $i=1,\ldots,k$, let us fix $a_i\in\mathbb{R}$ and $b_i\ge\beta$, and set $\bar\alpha:= \max\lvert a_i\rvert$. Moreover, let $c_{1},\dots,c_{k}$ be independent random variables, uniformly distributed on the interval $[0,\ell]$. Let us consider the random variable $\hat\varphi:=\varphi+R$, where $R(x):=\sum\limits_{i=1}^{k}a_i\psi(b_i(x-c_i))$ for any $x\in \mathbb{R}$. If $\frac{\sigma}{\beta}< \frac{\ell}{8(k-1)}$, then $$E\left(\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty\right)\le 3 L\frac{\sigma}{\beta}+k\bar\alpha\left(1-\left(1-8\frac{(k-1)}{\ell}\frac{\sigma}{\beta}\right)^{k}\right).$$ \end{theorem} \begin{proof} By setting $\delta=\frac{\sigma}{\beta}$ and $\varepsilon=2\frac{\sigma}{\beta}$ in statement $\mathrm{iii)}$ of Lemma~\ref{lemma1}, we have that $$\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty\leq3L\frac{\sigma}{\beta}+\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(R) \right\|_\infty.$$ Since the operator $F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}$ is non-expansive and $F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\mathbf{0})=\mathbf{0}$, it follows that $$\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(R) \right\|_\infty\leq\left\|R \right\|_\infty\leq k\bar\alpha\left\|\psi \right\|_\infty\leq k\bar\alpha.$$ Therefore, $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty\leq3L\frac{\sigma}{\beta}+k\bar\alpha$. If we apply Lemma~\ref{lemma3} with $\eta=8\frac{\sigma}{\beta}$, we obtain that ${R}\in\mathcal{R}_{8\frac{\sigma}{\beta},\beta}$ with probability $p:=\left(1-8\frac{(k-1)}{\ell}\frac{\sigma}{\beta}\right)^{k}$. If ${R}\in\mathcal{R}_{8\frac{\sigma}{\beta},\beta}$, we can apply Theorem~\ref{Upper Bound} by setting $\delta=\frac{\sigma}{\beta}$, $\varepsilon=2\frac{\sigma}{\beta}$ and $\theta=8\frac{\sigma}{\beta}$, and hence we obtain that $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty\le 3 L\frac{\sigma}{\beta}$ with probability at least $p$. Since $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty\le 3 L\frac{\sigma}{\beta}+k\bar\alpha$ in any case, it follows that \begin{align*} E\left(\left\|F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty\right)&\le 3 L\frac{\sigma}{\beta}p+\left(3 L\frac{\sigma}{\beta}+k\bar\alpha\right)\left(1-p\right)\\ &= 3 L\frac{\sigma}{\beta}+k\bar\alpha\left(1-p\right). \end{align*} \end{proof} Theorem~\ref{main_result} and the well known stability of persistence diagrams with respect to the max-norm \cite{CSEdHa07} immediately imply the following result, which is of interest in TDA (the symbol $d_{\mathrm{match}}$ denotes the usual bottleneck distance between persistence diagrams). \begin{corollary} \label{main_corollary} Let us make the same assumptions of Theorem~\ref{main_result}. Let $D$ and $D'$ be the persistence diagrams in degree $0$ of the filtering functions $\varphi$ and $F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)$, respectively. If $\frac{\sigma}{\beta}< \frac{\ell}{8(k-1)}$, then $$E\left(d_{\mathrm{match}}(D,D')\right)\le 3 L\frac{\sigma}{\beta}+k\bar\alpha\left(1-\left(1-8\frac{(k-1)}{\ell}\frac{\sigma}{\beta}\right)^{k}\right).$$ \end{corollary} This result shows that the use of suitable GENEOs can make TDA (relatively) stable also in the presence of impulsive noise, under the assumptions we have considered in this paper. % \section{Examples and experiments} We will now validate our approach based on GENEOs by giving two examples and illustrating some experimental results. \subsection{Examples} In order to verify how our approach works, we will set $\tau_n:=\left(1-\frac{1}{n}\right)2\frac{\sigma}{\beta}+\frac{1}{n}\left(\frac{\theta}{2}-2\frac{\sigma}{\beta}\right)$ and consider the upper bound $\left\|F^{\frac{\tau_n}{2}} \circ F_{\tau_n} \left(\hat\varphi\right)-\varphi\right\|_\infty\leq \frac{3}{2}L\tau_n$, obtained by applying Corollary~\ref{coroll2}. We observe that $\tau_n\ge 2\frac{\sigma}{\beta}$ for every index $n$, and $\lim\limits_{n\to+\infty}\tau_n=2\frac{\sigma}{\beta}$. We will examine two examples that use the GENEOs $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$ and show how our method based on such operators and the method based on convolutions differ, as for their capability in removing additive impulsive noise. Moreover, we will compare the actual error $\left\|F^{\frac{\tau_n}{2}} \circ F_{\tau_n} \left(\hat\varphi\right)-\varphi\right\|_\infty$ to its upper bound $ \frac{3}{2}L\tau_n$, by running several simulations. The convolutions that will be applied in our examples use the functions $T_h:\mathbb{R}\to\mathbb{R}$ defined by setting $$T_h(x):= \begin{cases} \frac{h}{2} &\mbox{if } -\frac{1}{h}\le x\le\frac{1}{h}\\ 0 &\mbox{otherwise} \end{cases}$$ for $h>0$. We will see that, although the convolution with such functions is also a GENEO, it will not be able to efficiently remove the noise. Our noise function $R$ will be constructed starting from the mother function $\psi$ defined by setting $\psi(x):=e^{1-\frac{1}{1-x^2}}$ for $x\in\left]-1,1\right[$ and $\psi(x):=0$ for $x\notin\left]-1,1\right[$. Using the notation introduced in the previous sections, we will set $\sigma=1.1$, thus satisfying the condition $\mathrm{supp}(\psi)\subseteq\left]-\sigma,\sigma\right[$. The impulsive noise will be added in an interval $\left[-{{\ell}},{{\ell}}\ \right]$. The following parameters are considered, with these respective uniform distributions: \begin{itemize} \item $k \sim \mathrm{Unif}_{\{1,\ldots,10\}}$ \item $a_i \sim \mathrm{Unif}_{\left]-100,100\right[}$ for $i=1,\ldots,k$ \item $b_i \sim \mathrm{Unif}_{\left]0,100\right[}$ for $i=1,\ldots,k$ \item $c_i \sim \mathrm{Unif}_{\left]-{{\ell}}+\frac{\sigma}{\beta},{{\ell}}-\frac{\sigma}{\beta}\right[}$ for $i=1,\ldots,k$. \end{itemize} We set $\beta:=\min\limits_{i=1,\ldots,N} b_i$, $\bar\alpha:=\max\limits_{i=1,\ldots,N} \lvert a_i\rvert$, and $\eta:=\min\limits_{i\not=j} \lvert c_i-c_j\rvert$. After producing random values for the parameters $N,a_i,b_i,c_i$, our algorithm checks whether $\eta>8\frac{\sigma}{\beta}$, otherwise it generates another set of parameters. \subsubsection{First example} Let us consider the function $$\varphi(x):= \begin{cases} \sin x &\mbox{if } -4\pi\le x\le4\pi \\ 0 &\mbox{otherwise} \end{cases}$$ for $x\in\mathbb{R}$. We observe that $\varphi\in\mathrm{Lip}_L$, for $L=1$. We will add noise in the interval $[-4\pi,4\pi]$ (meaning ${{\ell}}=4\pi$) and visualize the results in such an interval. Figure~\ref{fig_ex_1} illustrates how the function $\hat\varphi$ looks like compared to $\varphi$. \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES1_HAT_PHI.jpg} \caption{Example 1: Comparison between $\varphi$ and $\hat\varphi$.} \label{fig_ex_1} \end{figure} We will start by considering how well the convolution $\hat\varphi*T_n$ can approximate the original function $\varphi$, when $n$ goes from $3$ to $100$. From Figure~\ref{table_ex_1_A}, it is immediately apparent that the max-norm distance between $\hat\varphi*T_n$ and $\varphi$ remains quite large. \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{ES1_CONVZERO_N3.jpg} & \includegraphics[width=4.8cm]{ES1_CONVZERO_N5.jpg} \\ \includegraphics[width=4.8cm]{ES1_CONVZERO_N20.jpg} & \includegraphics[width=4.8cm]{ES1_CONVZERO_N100.jpg} \\ \end{tabular} \caption{Example 1: Denoising via convolution with $T_h$ ($h=n$).} \label{table_ex_1_A} \end{center} \end{figure} If we apply a convolution with $T_\frac{1}{n}$, for $3\le n\le 100$, we get the results displayed in Figure~\ref{table_ex_1_B}, showing that all information represented by the function $\varphi$ is progressively destroyed. \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{ES1_CONVINF_N3.jpg} & \includegraphics[width=4.8cm]{ES1_CONVINF_N5.jpg} \\ \includegraphics[width=4.8cm]{ES1_CONVINF_N20.jpg} & \includegraphics[width=4.8cm]{ES1_CONVINF_N100.jpg} \\ \end{tabular} \caption{Example 1: Denoising via convolution with $T_h$ ($h=\frac{1}{n}$).} \label{table_ex_1_B} \end{center} \end{figure} In contrast, if we apply the operator $F^{\frac{\tau_n}{2}} \circ F_{\tau_n} \left(\hat\varphi\right)$, for $n=3,5,20,100$, we get the results displayed in Figure~\ref{table_ex_1_C}. As we can see, this operator is much more efficient in removing the bumps and restoring the function $\varphi$. \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{ES1_GENEO_N3.jpg} & \includegraphics[width=4.8cm]{ES1_GENEO_N5.jpg} \\ \includegraphics[width=4.8cm]{ES1_GENEO_N20.jpg} & \includegraphics[width=4.8cm]{ES1_GENEO_N100.jpg} \\ \end{tabular} \caption{Example 1: Denoising via the proposed GENEO $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$.} \label{table_ex_1_C} \end{center} \end{figure} As a matter of fact, when we apply a convolution with the function $T_h$ and check the corresponding errors via the sup-norm, we get the results displayed in Figure~\ref{table_ex_1_D}. Since $\lim\limits_{h\to+\infty}\hat\varphi*T_{h}=\hat\varphi$ and $\lim\limits_{h\to+\infty}\hat\varphi*T_{\frac{1}{h}}=0$, we get that the errors tend to $\|\hat\varphi-\varphi\|_\infty=\max\limits_{i=1,\ldots,N} \lvert a_i\rvert=\bar\alpha$ and $\|\varphi\|_\infty$, respectively. \begin{figure}[t] \begin{center} \begin{tabular}{c c} \includegraphics[width=4.8cm]{ES1_CONVZERO_ERR.jpg} & \includegraphics[width=4.8cm]{ES1_CONVINF_ERR.jpg} \end{tabular} \end{center} \caption{Example 1: Error made by applying a convolution with $T_n$ (left) or $T_\frac{1}{n}$ (right).} \label{table_ex_1_D} \end{figure} In contrast, if we apply the operator $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$, we get the results displayed in Figure~\ref{fig_ex_1_E}, showing that the upper bound for the error stated in Corollary~\ref{coroll2} is quite tight. As we can expect, we get the best denoising by replacing $\tau_n$ with $2\frac{\sigma}{\beta}$ (see Figure~\ref{fig_ex_1_F}). \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES1_GENEO_ERR.jpg} \caption{Example 1: Error made by using the GENEO $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$.} \label{fig_ex_1_E} \end{figure} \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES1_GENEO_BEST100.jpg} \caption{Example 1: Denoising via $F^\frac{\sigma}{\beta} \circ F_{2\frac{\sigma}{\beta}}$.} \label{fig_ex_1_F} \end{figure} Finally, we executed 1000 simulations. In each of them we have produced a function $\hat\varphi$ by adding random impulsive noise to the function $\varphi$, then we have applied $F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}}$ to $\hat\varphi$, in order to see how tight the upper bound in Corollary~\ref{coroll2} is to the actual error $\|F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\|_\infty$. The same parameters as in the beginning of this example have been used. As we can see in Figure~\ref{histo1} the overestimation committed by our upper bound is often quite close to zero, relatively to the Lipschitz constant $L$ of the function $\varphi$. \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES1_HISTOGRAM.jpg} \caption{Example 1: Histogram counting the number of cases in each of ten bins, concerning the overestimation value $3L\frac{\sigma}{\beta}-\|F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\|_\infty$ obtained in our simulations. Most of the cases belong to the first bin, containing the functions $\varphi$ for which $0\le 3L\frac{\sigma}{\beta}-\|F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\|_\infty\le 0.02$.} \label{histo1} \end{figure} This suggests that such an upper bound is quite accurate. \subsubsection{Second example} Let us consider the function $$\varphi(x):= \begin{cases} \frac{1}{1000}(x-5)(x-3)(x+1)(x+4)(x+5) &\mbox{if } -5\le x\le5 \\ 0 &\mbox{otherwise} \end{cases}$$ for $x\in\mathbb{R}$. The coefficient $\frac{1}{1000}$ was chosen in order to get that the Lipschitz constant $L$ is comparable to the one of the previous example. In this example $L=\frac{27}{25}$. Figure~\ref{fig_ex_2} illustrates how the function $\hat\varphi$ looks like compared to $\varphi$. \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES2_HAT_PHI.jpg} \caption{Example 2: Comparison between $\varphi$ and $\hat\varphi$.} \label{fig_ex_2} \end{figure} We will start by considering how well the convolution $\hat\varphi*T_n$ can approximate the original function $\varphi$, when $n$ goes from $3$ to $100$. From Figure~\ref{table_ex_2_A}, it is immediately apparent that the max-norm distance between $\hat\varphi*T_n$ and $\varphi$ remains quite large. \vskip 5cm \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{ES2_CONVZERO_N3.jpg} & \includegraphics[width=4.8cm]{ES2_CONVZERO_N5.jpg} \\ \includegraphics[width=4.8cm]{ES2_CONVZERO_N20.jpg} & \includegraphics[width=4.8cm]{ES2_CONVZERO_N100.jpg} \\ \end{tabular} \caption{Example 2: Denoising via convolution with $T_h$ ($h=n$).} \label{table_ex_2_A} \end{center} \end{figure} If we apply a convolution with $T_\frac{1}{n}$, for $3\le n\le 100$, we get the results displayed in Figure~\ref{table_ex_2_B}, showing that all information represented by the function $\varphi$ is progressively destroyed. \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{ES2_CONVINF_N3.jpg} & \includegraphics[width=4.8cm]{ES2_CONVINF_N5.jpg} \\ \includegraphics[width=4.8cm]{ES2_CONVINF_N20.jpg} & \includegraphics[width=4.8cm]{ES2_CONVINF_N100.jpg} \\ \end{tabular} \caption{Example 2: Denoising via convolution with $T_h$ ($h=\frac{1}{n}$).} \label{table_ex_2_B} \end{center} \end{figure} In contrast, if we apply the operator $F^{\frac{\tau_n}{2}} \circ F_{\tau_n} \left(\hat\varphi\right)$, for $n=3,5,20,100$, we get the results displayed in Figure~\ref{table_ex_2_C}. As we can see, this operator is much more efficient in removing the bumps and restoring the function $\varphi$. When we apply a convolution with the function $T_h$ and check the corresponding errors via the sup-norm, we get the results displayed in Figure~\ref{table_ex_2_D}. As already seen, since $\lim\limits_{h\to+\infty}\hat\varphi*T_{h}=\hat\varphi$ and $\lim\limits_{h\to+\infty}\hat\varphi*T_{\frac{1}{h}}=0$ we get that the errors tend to $\|\hat\varphi-\varphi\|_\infty=\max\limits_{i=1,\dots,k} \lvert a_i\rvert=\bar\alpha$ and $\|\varphi\|_\infty$, respectively. \begin{figure}[t] \begin{center} \begin{tabular}{r c} \includegraphics[width=4.8cm]{ES2_GENEO_N3.jpg} & \includegraphics[width=4.8cm]{ES2_GENEO_N5.jpg} \\ \includegraphics[width=4.8cm]{ES2_GENEO_N20.jpg} & \includegraphics[width=4.8cm]{ES2_GENEO_N100.jpg} \\ \end{tabular} \caption{Example 2: Denoising via the proposed GENEO $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$.} \label{table_ex_2_C} \end{center} \end{figure} \begin{figure}[t] \begin{center} \begin{tabular}{c c} \includegraphics[width=4.8cm]{ES2_CONVZERO_ERR.jpg} & \includegraphics[width=4.8cm]{ES2_CONVINF_ERR.jpg} \end{tabular} \end{center} \caption{Example 2: Error made by applying a convolution with $T_n$ (left) or $T_\frac{1}{n}$ (right).} \label{table_ex_2_D} \end{figure} In contrast, if we apply the operator $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$, we get the results displayed in Figure~\ref{fig_ex_2_E}, showing that the upper bound for the error stated in Corollary~\ref{coroll2} is quite tight. As we can expect, we get the best denoising by replacing $\tau_n$ with $2\frac{\sigma}{\beta}$ (see Figure~\ref{fig_ex_2_F}). \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES2_GENEO_ERR.jpg} \caption{Example 2: Error made by using the GENEO $F^{\frac{\tau_n}{2}} \circ F_{\tau_n}$.} \label{fig_ex_2_E} \end{figure} \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES2_GENEO_BEST100.jpg} \caption{Example 2: Denoising via $F^\frac{\sigma}{\beta} \circ F_{2\frac{\sigma}{\beta}}$.} \label{fig_ex_2_F} \end{figure} Finally, we again executed 1000 simulations, using the same methodology as in the previous case, this time considering the polynomial presented at the beginning of this example. As we can see in Figure~\ref{histo2} the overestimation committed by our upper bound is often quite close to zero, relatively to the Lipschitz constant $L$ of the polynomial $\varphi$. \begin{figure}[t] \centering \includegraphics[width=4.8cm]{ES2_HISTOGRAM.jpg} \caption{Example 2: Histogram counting the number of cases in each of ten bins, concerning the overestimation value $3L\frac{\sigma}{\beta}-\|F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\|_\infty$ obtained in our simulations. Most of the cases belong to the first two bins, containing the functions $\varphi$ for which $0\le 3L\frac{\sigma}{\beta}-\|F^{\frac{\sigma}{\beta}} \circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\|_\infty\le 0.24$.} \label{histo2} \end{figure} \subsection{Experiments} In order to check how good the upper bound stated in Theorem~\ref{main_result} is, we have made the following experiment. In a first step, we have fixed $\ell=20$ and $\sigma=1.1$, and assumed as given the parameters $L>0$, $N\in\mathbb{N}$, $\alpha>0$, $\beta>0$, $k\in\mathbb{N}$, $a_1,\ldots,a_k\in]0,\alpha[$, $b_1,\ldots,b_k>\beta$, $c_1,\ldots,c_k\in]0,\ell[$. Firstly, we have used the parameters $L>0$, $N\in\mathbb{N}$ to generate a random $L$-Lipschitz function $\varphi$ in the following way. We have randomly chosen and sorted in ascending order $N$ points $x_1,\ldots,x_N$ in the open interval $]0,\ell[$, with uniform distribution. Hence we have obtained the following decomposition: $]0,\ell[=]0,x_1]\cup]x_1,x_2]\cup\ldots\cup]x_N,\ell[$. We have defined our Lipschitz function $\varphi$ to be $0$ outside $]0,\ell[$. After setting $(x_0,y_0)=(0,0)$ and $(x_{N+1},y_{N+1})=(\ell,0)$, for $i\in \{1,\ldots,N+1\}$ the value $y_i$ of the function at $x_i$ has been randomly chosen, with uniform distribution in an interval that allows for an $L$-Lipschitz extension to $[0,\ell]$ of the function, i.e., $\left[\max\{y_{i-1}-L(x_i-x_{i-1}),-L(\ell-x_i)\},\min\{y_{i-1}+L(x_i-x_{i-1}),L(\ell-x_i)\}\right]$. Finally, the graph of the Lipschitz function $\varphi$ on $[0,\ell]$ has been obtained by connecting each point $(x_{i-1},y_{i-1})$ to $(x_i,y_i)$ with a segment, for $i\in \{1,\ldots,N+1\}$. We observe that $\varphi$ constructed this way is an $L$-Lipschitz function. Secondly, we have used the parameters $\alpha>0$, $\beta>0$, $k\in\mathbb{N}$, $a_1,\ldots,a_k\in]0,\alpha[$, $b_1,\ldots,b_k>\beta$, $c_1,\ldots,c_k\in]0,\ell[$ to generate a noise function as follows. We have considered the mother function $\psi$ defined by setting $\psi(x):=e^{1-\frac{1}{1-x^2}}$ for $x\in\left]-1,1\right[$ and $\psi(x):=0$ for $x\notin\left]-1,1\right[$. For each $L$-Lipschitz function $\varphi$ produced in the previously described way, we have considered the function $\hat\varphi=\varphi+\sum\limits_{i=1}^k a_i\psi(b_i(x-c_i))$. In Figures~\ref{fig_L_functions_k_3} and \ref{fig_L_functions_k_7} some examples of the functions we have produced are displayed, for $N=3$ and $N=7$, respectively. In each figure, the functions are displayed without noise (left) and with added noise (right). \begin{figure}[t] \begin{center} \begin{tabular}{c c} \includegraphics[width=4.8cm]{fig6ESK3.jpg} & \includegraphics[width=4.8cm]{fig6ESK3HAT.jpg} \end{tabular} \end{center} \caption{Five examples of the functions we have produced for $N=3$. In each figure, the functions are displayed without noise (left) and with added noise (right).} \label{fig_L_functions_k_3} \end{figure} \begin{figure}[t] \begin{center} \begin{tabular}{c c} \includegraphics[width=4.8cm]{fig6ESK7.jpg} & \includegraphics[width=4.8cm]{fig6ESK7HAT.jpg} \end{tabular} \end{center} \caption{Five examples of the functions we have produced for $N=7$. In each figure, the functions are displayed without noise (left) and with added noise (right).} \label{fig_L_functions_k_7} \end{figure} In a second step, we have fixed $\ell=20$ and $\sigma=1.1$ once again, and considered a probabilistic model assuming that $\alpha$, $\beta$, $L$ are given and the values $N$, $k$, $a_i$, $b_i$, $c_i$ are random variables. In this setting, we have compared the noise $\|\hat\varphi-\varphi\|_\infty$ with the probabilistic upper bound stated in Theorem~\ref{main_result} and the value $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty$, representing the reduced noise that we can obtain by applying our method. In order to average our results, for each triplet $(\alpha,\beta,L)$ with $\alpha\in\{50, 55, 60, \ldots, 100\}$, $\beta\in\{3, 4, 5, \ldots, 13\}$, and $L\in\{1,2, \ldots, 10\}$, we have randomly generated $100$ examples of an $L$-Lipschitz function $\varphi$ and its noisy version $\hat\varphi$, by randomly choosing the parameters $N$, $k$, $a_i$, $b_i$, $c_i$ according to the following distributions: \begin{itemize} \item $N \sim \mathrm{Unif}_{\{1,\ldots,10\}}$ \item $k \sim \mathrm{Unif}_{\{1,\ldots,10\}}$ \item $a_i \sim \mathrm{Unif}_{\left]0,\alpha\right[}$ for $i=1,\ldots,k$ \item $b_i \sim \mathrm{Unif}_{\left]\beta,20\right[}$ for $i=1,\ldots,k$ \item $c_i \sim \mathrm{Unif}_{\left]3\frac{\sigma}{\beta},\ell-3\frac{\sigma}{\beta}\right[}$ for $i=1,\ldots,k$. \end{itemize} Then for the chosen values of each one of the three variables $\alpha,\beta,L$, we have computed the mean, with respect to the other two variables, of the average of the noise $\|\hat\varphi-\varphi\|_\infty$ and the average of the reduced noise $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi \right\|_\infty$ obtained by our method, both evaluated for $(\varphi,\hat\varphi)$ varying in the set of cardinality $100$ that we have produced. We have also computed the mean of the probabilistic upper bound stated in Theorem~\ref{main_result} with respect to the same two variables. The results are displayed in Figures~\ref{fig_HISTOGRAM_VARALPHA_PROB}, \ref{fig_HISTOGRAM_VARBETA_PROB}, and \ref{fig_HISTOGRAM_VARL_PROB}. We remind the reader that $\alpha$ and $\beta$ respectively express the maximum height and the thinness of the noise bumps, while $L$ is a Lipschitz constant for each function $\varphi$ we are interested in. These results illustrate the effectiveness of the use of GENEOs in the reduction of impulsive noise. \begin{figure}[t] \begin{center} \includegraphics[width=7cm]{plot_varAlpha_new.jpg} \end{center} \caption{Plots of the means of the averaged values of $\|\hat\varphi-\varphi\|_\infty$ (yellow), the means of $3 L\frac{\sigma}{\beta}+k\alpha\left(1-\left(1-8\frac{(k-1)}{\ell}\frac{\sigma}{\beta}\right)^{k}\right)$ (brown), and the means of the averaged values of $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\right\|_\infty$ (blue) for $\beta\in\{3, 4, 5, \ldots, 13\}$ and $L\in\{1,2, \ldots, 10\}$, when $\alpha$ varies in the set $\{50, 55, 60, \ldots, 100\}$.} \label{fig_HISTOGRAM_VARALPHA_PROB} \end{figure} \begin{figure}[t] \begin{center} \includegraphics[width=7cm]{plot_varBeta_new.jpg} \end{center} \caption{Plots of the means of the averaged values of $\|\hat\varphi-\varphi\|_\infty$ (yellow), the means of $3 L\frac{\sigma}{\beta}+k\alpha\left(1-\left(1-8\frac{(k-1)}{\ell}\frac{\sigma}{\beta}\right)^{k}\right)$ (brown), and the means of the averaged values of $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\right\|_\infty$ (blue) for $\alpha\in\{50, 55, 60, \ldots, 100\}$ and $L\in\{1,2, \ldots, 10\}$, when $\beta$ varies in the set $\{3, 4, 5, \ldots, 13\}$.} \label{fig_HISTOGRAM_VARBETA_PROB} \end{figure} \begin{figure}[t] \begin{center} \includegraphics[width=7cm]{plot_varL_new.jpg} \end{center} \caption{Plots of the means of the averaged values of $\|\hat\varphi-\varphi\|_\infty$ (yellow), the means of $3 L\frac{\sigma}{\beta}+k\alpha\left(1-\left(1-8\frac{(k-1)}{\ell}\frac{\sigma}{\beta}\right)^{k}\right)$ (brown), and the means of the averaged values of $\left\| F^{\frac{\sigma}{\beta}}\circ F_{2\frac{\sigma}{\beta}}(\hat\varphi)-\varphi\right\|_\infty$ (blue) for $\alpha\in\{50, 55, 60, \ldots, 100\}$ and $\beta\in\{3, 4, 5, \ldots, 13\}$, when $L$ varies in the set $\{1,2, \ldots, 10\}$.} \label{fig_HISTOGRAM_VARL_PROB} \end{figure} \section{Conclusion} In our paper we have proved a stability property for persistence diagrams of functions from $\mathbb{R}$ to $\mathbb{R}$, in the presence of impulsive noise. This property shows that TDA can also be of use when noise drastically changes the topology of the sublevel sets of the filtering functions we are considering, and stresses some new possible interaction between TDA and the theory of GENEOs. The experimental section shows that our approach is indeed able to remove the impulsive noise, in most of the cases. It would be interesting to check the possibility of extending our method to real-valued functions defined on $n$-dimensional domains, by selecting suitable GENEOs. We plan to devote our research to this topic in the future.
{'timestamp': '2022-04-26T02:25:37', 'yymm': '2202', 'arxiv_id': '2202.14021', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.14021'}
arxiv
\section{A Call for An Overhaul of CQELS Framework} \section{Introduction and Motivation} CQELS was proposed as one of the first RDF stream processing engines to solve the data integration problem for sensor data, Internet of Things, and the Web of data~\cite{Danh:2011}. The key feature of this data integration approach is the semantic interoperabiliy enabled by RDF data models. The framework has been used in various industry and research applications both as open source and commercial software The recent advances in \textit{machine learning} (ML) with \textit{deep neural network} (DNN) leads to the enormous amount of data in various formats, and in many cases from multimodal stream data with high accuracy. Therefore, the existing framework is no longer suitable for the new application scenarios and requires significant extensions. Towards this goal, in \system, we integrate a number of new stream data types such as video streams, LiDARs, and support more hardwares such as ARM and mobiles~\cite{Anh:2018,Manh:2019}. Moreover, we provide data fusion operations in our engines~\cite{Danh:2021,Manh:2021}. For example, the operation for object detection DNNs~\cite{Joseph:2015, Shaoqing:2015} returns a set of bounding boxes and object classes given an image or video frames. Thus, \system is designed as a DNN-based data stream fusion framework. Along with the new feature for different data sources, the CQELS-QL query language has evolved from supporting event query patterns~\cite{Minh:2015,Daniele:2016} to probabilistic reasoning in~\cite{Danh:2021,Manh:2021}. To implement such complex features and also to support for future demand in research, we bring the existing CQELS framework to the next level with new architecture and design. The new design is driven by requirements from use cases and research problems from various research projects (e.g. DFG COSMO\footnote{https://gepris.dfg.de/gepris/projekt/453130567?language=en} and BMBF BIFOLD\footnote{https://bifold.berlin/}) and industry partners. For example, application scenarios in edge intelligence~\cite{Zhi:2019,Shuiguang:2020} and industry 4.0 from DellEMC, Siemens and Bossh motivate us to build \emph{autonomous processing kernels} powered by CQELS~\cite{Manh:2019,Manh:2021}. Such systems deal with city-scale camera deployments which have become ubiquitous in smart cities and traffic monitoring with a continuously increasing in size and utilization of their deployments. For instance, the British Security Industry Association estimates that there are between 4 to 5.9 millions CCTV cameras in the UK~\cite{cctv}. To this end, the new design of CQELS framework has to deal with not only the new level of complexity of data sources, processing operations and deployment settings, but also with significantly larger processing scale in terms of throughput and volume. \section{CQELS 2.0 Framework for Semantic Stream Fusion} Semantic stream reasoning (SSR)~\cite{Danh:2021} enables the data fusion of multimodal stream data such as camera and LiDARs via declarative rules. Such rules can be written in SPARQL-based or Answer Set Programming (ASP) syntax. And the stream data flow between data fusion operations can be represented as standardized data formats, e.g, RDF Star. SSR generalizes the data model and processing operations of the previous CQELS engines, hence, CQELS 2.0 framework uses SSR formalisation and abstractions to facilitate the architecture design and implementation. Figure~\ref{fig:concept} illustrates the conceptual design of CQELS 2.0 framework that comprises several components. The~\name{Feature Extractor} component extracts the features of interest from the incoming information streams and maps them to the symbolic representation. The feature data is described with a~\emph{neuro-symbolic stream model}~\cite{Danh:2021} and its semantic is enriched via linked knowledge graphs. The~\name{Reasoning Programs Producer} component takes responsibility to generate \emph{semantic stream reasoning programs}~\cite{Danh:2021} which specify the fusion pipeline and the decision logic to choose the most likely state of the world at each evaluation. The reasoning program is evaluated by the \name{Reasoner} component, which employs an ASP solver. There are two types of reasoning rules: \emph{hard rules} and \emph{soft rules}. The hard rule is used for background knowledge given by (non-monotonic) common-sense and domain knowledge that is regarded as "always true". The soft rules expresses association hypotheses with weights corresponding to probability degrees of these rules. The weights of the rules are determined by the \name{Learning Agent} component in the starting phase. \begin{figure}[ht!] \centering \includegraphics[width=1\textwidth]{figures/SSR-ssr.jpg} \caption{The overview of conceptual design of CQELS 2.0} \label{fig:concept} \end{figure} The workflow of the framework is as follows. For the setup, the symbolic training samples are constructed from the labeled data and are fed to the \name{Learning Agent} component. The \name{Learning Agent} component computes a vector of weights for the soft rules which are stored as rule templates and passes them to the \name{Reasoning Programs Producer} component. For each training iteration, a \emph{feedback stream} returns the reasoning results back to \name{Learning Agent} component. The \name{Learning Agent} component adjusts the weights of the soft rules until the answer sets (returned as feedback streams) describe the most likely ground truth. \section{Provisional Features} In this section, we present the details of a provisional feature of \system that can be used to solve the \emph{multiple object tracking} (MOT) problem~\cite{Bernardin:2008}. In computer vision, MOT algorithms are normally programmed in C/C++ or Python. With \system, we will show that the widely used tracking-by-detection approach~\cite{Ciaparrone:2019} for the MOT problem can be emulated in a declarative fashion with rules and queries. The key operations in tracking-by-detection approaches (e.g., SORT~\cite{Bewley:2016}, DEEPSORT~\cite{Wojke:2017}) are as following: 1) detection of objects (using DDN-based detector), 2) propagating object states (e.g., location and velocity) into future frames, 3) associating current detection with existin \begin{figure}[ht!] \centering \includegraphics[width=1.\textwidth]{figures/SSR-runex.jpg} \caption{A Semantic Visual Stream Snapshot. The red boxes are detected bounding boxes and the yellow boxes are tracked bounding boxes.} \label{fig:example} \end{figure} Figure~\ref{fig:example} illustrates the SORT algorithm~\cite{Bewley:2016} which is a simple object tracking algorithm based on DNN detectors such as SSD~\cite{Liu:2016} or YOLO~\cite{Redmon:2017}. To associate resultant detections with existing targets, SORT uses a Kalman filter~\cite{Bishop:2001} to predict the new locations of targets in the current frame. At time point 2, the red boxes $b_1$ and $b_3$ are newly detected, and the yellow boxes $b_2$ and $b_4$ are predicted by a Kalman filter based on the tracked boxes from the previous frame. Then, the SORT algorithm computes an associative cost matrix between detections and targets based on the intersection-over-union (IOU) distance between each detection and all predicted bounding boxes from the existing tracklets. In case some detection is associated with a target, the detected bounding box is used to update the target state via the Kalman filter. As in frame 2, the tracklets $trk_1$ and $trk_2$ are set to the two new bounding boxex $b_1$ and $b_2$ which are associated with predicted boxes $b_3$ and $b_4$ respectively. Otherwise, the target state is simply predicted without correction using the linear velocity model. For example, at time point 3, the detector misses detecting the white car due to an occlusion, however, the tracklet 2 is till assigned to box $b_7$ which contains part of the white car. With the Feature Extractor component (see. Figure~\ref{fig:concept}), \system extracts the detection boxes from input video frames and represent them as RDF facts. The data abstraction is modelled using the neural symbolic stream modelling practice (presented in~\cite{Danh:2021}), which extends the standardised Semantic Sensor Network Ontology (SSN)~\cite{Armin:2019} to model video streams and intermediate processing states. The extension includes various vocabularies to specify the semantics of camera sensors, video frames, and tensors as shown in Figure~\ref{fig:abstract}. \begin{figure}[ht!] \centering \includegraphics[width=1\textwidth]{figures/ssn1} \caption{Data abstraction of Neural-Symbolic stream with Semantic Sensor Network Ontology} \label{fig:abstract} \end{figure} With the above data abstraction, \system consumes the video data stream that is observed by a camera (as a ${Sensor}$) as \emph{a stream of observations}. Each observation is a video frame. These video frames are represented as instances of the class ${Image2D}$ that inherits from the generic ${Observation}$ class of SSN. The detection of a video frame or a tracklet are represented as SSN $Sampling$ which are processed by a DNN model or a CV algorithm represented as a \emph{Procedure}. \begin{lstlisting}[ caption={Semantic Stream Serialization with RDF$^*$}, label={rdf:frame2}, language=SPARQL, numbers=left, captionpos=b, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor},] //time point/frame 2 <<:image2 a :Image2D>> a sosa:Observation; sosa:madeBySensor :cam1; sosa:resultTime 2. <<:det1 :det :b1>> a :Detection; sosa:resultTime 2; sosa:hasSimpleResult 'car'; :score '0.8'; :isDetectionOf :image2; sosa:usedProcedure :Yolo. <<:det1 :det :b3>> a :Detection; sosa:resultTime 2; sosa:hasSimpleResult 'car'; :score '0.7'; :isDetectionOf :image2; sosa:usedProcedure :Yolo. <<:trk1 :trk :b2>> a :Tracklet; sosa:resultTime 2; sosa:usedProcedure :KalmanFilter. <<:trk2 :trk :b4>> a :Tracklet; sosa:resultTime 2; sosa:usedProcedure :KalmanFilter. \end{lstlisting} For example, Listing~\ref{rdf:frame2} illustrates the the symbolically representation in RDF* format\footnote{\url{https://w3c.github.io/rdf-star/cg-spec/editors$\_$draft.html}} of the frame 2 in the stream snapshot in Figure~\ref{fig:example} Line 5 denotes that the detection model generates an output consisting of a bounding box $b_1$, object type $car$ and confidence score $0.8$. Line 13 presents that the box $b_2$ is predicted by a Kalman filter and is tracked by tracklet 1. To emulate these MOT algorithms, \system represents these association hypotheses by hard rules and soft rules that are translated into an optimization problem solved by an ASP Solver. To formalise the reasoning process on semantic representations of stream data, we use a temporal semantic model that allows us to reason about the properties and features of objects. The model accounts for the laws of the physical world and commonsense, which allow the system to handle incomplete information (e.g., if we do not see objects appearing in observations, or camera reads are missing). Using the above RDF representations, we allow RDF\&SPARQL developers to write soft rules with SHACL rule language\footnote{SHACL Advanced Features} along with the extension of CQEL-QL. The extension we made here is replacing SPARQL CONSTRUCT with the corresponding CONSTRUCT of CQELS-QL which extends SPARQL with the window operators over RDF Stream. Moreover, extending SHACL for expressing ASP-like rules is aligned with the recent proposal for assigning SHACL to negation stable semantics~\cite{Medina:2020}. Note that we extend CQESL-QL syntax in~\cite{Danh:2011} with the keyword "NAF" to express the default negation of ASP. For example, the soft rule 1 in Listing~\ref{soft-rule1} is used to trigger the event a car enters the "Field of View" of a camera and the car starts being tracked. \begin{lstlisting}[ caption={Soft rule 1 - detect vehicles entering Field of View}, label={soft-rule1}, captionpos=b, language=SPARQL, numbers=left, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor}, escapeinside=||,] ssr:rule_w_1 a sh:NodeShape; sh:rule [ a sh:CQELSRule ; sh:prefixes ssr: ; sh:construct |"""| CONSTRUCT {<<?O :enters <ssr:FoV>> @ ?T.} WHERE { STREAM <:ssr> { <<?Dt :det ?B >> @ ?T; :score ?S. ?B sosa:isSampleOf ?O ; a :car. FILTER (?S > 0.8) } NAF STREAM <:ssr> window[5 sec] { ?O :inFOV ssr:FoV. } } |"""| ; ] ; \end{lstlisting} To associate a detected bounding box $B$ with an object $O$, we use soft rules that assert the triple <<B sosa:isSampleOf O>> based on {\em explained spatial, temporal, and visual appearance evidences}. Such rules can be used to represent {\em hypotheses}\/ on temporal relations among detected objects in video frames following a tracking trajectory. When the object's movement is consistent with the constant velocity model, e.g., the Kalman filter used in SORT~\cite{Bewley:2016}, and there is a detection associated with its trajectory, the fact <<B sosa:isSampleOf O>> is generated by rule~\ref{soft-rule2}. Here, $iou(B_1,B_2)$ states the IOU (intersection over union) condition of the bounding boxes $B_1$ and $B_2$ satisfy. \begin{lstlisting}[ caption={Soft rule 2 - emulation of SORT algorithm~\cite{Bewley:2016}.}, label={soft-rule2}, captionpos=b, language=SPARQL, numbers=left, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor}, escapeinside=||,] ssr:rule_w_2 a sh:NodeShape ; sh:rule [ a sh:CQELSRule ; sh:prefixes ssr: ; sh:construct |"""| CONSTRUCT { ?B1 sosa:isSampleOf ?O. } WHERE{ STREAM <:ssr>{ <<?Dt :det ?B2 >> @ ?T; :score ?S. <<?Trk :trk ?B1 >> @ ?T. ?Trk :trklet ?O. FILTER (?S>0.8 && iou (?B1,?B2) > 0.8) } } |"""| ; ] ; \end{lstlisting} \begin{lstlisting}[ caption={Soft rule 3 - emulation of DEEPSORT algorithm~\cite{Wojke:2017}.}, label={soft-rule3}, captionpos=b, language=SPARQL, numbers=left, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor}, escapeinside=||,] ssr:rule_w_3 a sh:NodeShape ; sh:rule [ a sh:CQELSRule ; sh:prefixes ssr: ; sh:construct |"""| CONSTRUCT { ?B1 sosa:isSampleOf ?O. } WHERE{ STREAM <:ssr> @?Te window[5 sec] { ?Trk2 :trk ?B2 } STREAM <:ssr>{ <<?Trk1 :trk ?B1 >> @ ?T. <<?B1 :vMatch ?B2 >> :score ?S. ?B2 sosa:isSampleOf ?O. ?Trk2 :ends ?Te. FILTER {?T<?Te+3 && ?S>0.8 } } } |"""| ; ] ; \end{lstlisting} Furthermore, we can also emulate DeepSORT~\cite{Wojke:2017} via the soft rule~\ref{soft-rule3} that can search for supporting evidences to link a newly detected bounding box from an occluded tracklet using visual appearance associations, e.g. frames 2 and 4 of Figure~\ref{fig:example}. For this, we search for pairs of bounding boxes from recently occluded tracklets w.r.t. visual appearance. As the search space of possible matches is large, we limit it by filtering the candidates based on their temporal and spatial properties. To this end, we use rules with windows to reason about disconnected tracklets that have bounding boxes visually matched within a window of time points that are aligned with DeepSORT's gallery of associated appearance descriptors for each tracklet. Based on this gallery of previously tracked boxes, the appearance-based discriminative metrics are computed to recover the identities after long-term occlusion, where the motion is less discriminative. Hence, to connect a newly detected bounding box $B_1$ that has a visual appearance match with another bounding box $B_2$ (represented by the fact <<$B_1$ :vMatch $B_2.$>> in line 13) of a discontinued tracklet $T_2$ (represented by <<$Trk_2$ :ends $T_e$>> in line 15) that ended 3 time points before. \section{System Architecture Overview} In this section, we present a specific architecture of \system for the conceptual design in Figure~\ref{fig:concept}. CQELS framework provides a platform-independent infrastructure to implement RDF-Stream Processing (RSP) engines for computing continuous queries expressed in CQELS-QL. The first version of CQELS accepts RDF streams as input and returns RDF streams or relational streams in the SPARQL format as output. \system allows creating RDF streams by annotating extracted features from other data streams. The output RDF streams can be fed into any RSP engine, and the relational stream can be used by other relational stream processing systems. \begin{figure}[ht!] \centering \includegraphics[width=1\textwidth]{figures/SSR-cqels2.jpg} \caption{System architecture of \system.} \label{fig:cqels20} \end{figure} Figure~\ref{fig:cqels20} illustrates the overview architecture of \system. In general, \system consists of three subsystems. Subsystem \circled{1}, the RDF stream processing processor, extends the stream processing primitives of its previous version~\cite{Danh:2011} to accelerate the grounding phase of stream reasoning. For example, multiway joins are used to accelerate the incremental ground techniques~\cite{Danh:2018}. The second subsystem~\circled{2} is the semantic stream reasoning component as presented in Section 2. Finally, subsystem~\circled{3} is a stream adaptive federator, which is described as follows. Thanks to the platform-agnostic design of its execution framework~\cite{Danh:2015}, the core components are abstract enough to be seamlessly integrated with different RDF libraries in order to port the resulting system to different hardware platforms. For scalability, CQELS employs Storm\footnote{Storm. https://storm.apache.org/} and HBase\footnote{Hbase. http://hbase.apache.org/.} as underlying software stacks for coordinating parallel execution processes to build an RSP engine on the cloud computing infrastructure, called CQELS Cloud~\cite{Danh:2013}. To tailor the RDF-based data processing operations on edge devices (e.g, ARM CPU, Flash-storage), CQLES can be integrated in RDF4Led~\cite{Anh:2018}, a RISC style RDF engine for lightweight edge devices, to build Fed4Edge~\cite{Manh:2019}. The whole Fed4Edge is smaller than 10MB and needs only 4--6 MB of RAM to process millions of triples on various small devices such as BeagleBone,\footnote{https://beagleboard.org/bone} Raspberry PI.\footnote{https://www.raspberrypi.org/} Therefore, \system includes an adaptive federation mechanism to enable the coordination of different hardware resources to process query processing pipelines by cooperatively delegating partial workloads to their peer agents. The Adaptive Federator acts as the query rewriter, which adaptively divides the input query into sub queries. The rewriter then pushes down the operators as close to the streaming nodes as possible by following the predicate pushdown practice in common logical optimisation algorithms. The metadata subscribed by the other CQELS instances is stored locally. Similar to~\cite{Dell:2017}, such metadata allows the endpoint services of a CQELS engine to be discovered via the Adaptive Federator. When the Adaptive Federator sends out a subquery, it notifies the Stream Input Handler to subscribe and listens to the results returning from the subquery. On the other hand, the Stream Output Handler sends out the subqueries to other nodes or sends back the results to the requester. Similar to cloud integration with CQELS Cloud~\cite{Danh:2013}, this federation design also covers elastic-scale delopment by using the new development of Apache Flink under BIFOLD project. In particular, we use the EMMA compiling and parallelizing for data flow systems in ~\cite{Gabor:2021} to scale and optimize our processing pipelines in the cloud infrastructure. This will lay the foundation for an integration of the adaptive optimizer with the cloud-based stream scheduler and operation allocations. With the support of the above subscription and discovery operations, a stream processing pipeline written in CQELS-QL can be deployed across several sites distributed in different locations: e.g., weather stations provide environmental sensory streams in various locations on earth. Each autonomous CQELS node gives access to data streams fed from the streaming nodes connecting to it. Such stream nodes can ingest a range of sensors, such as air temperature, humidity and carbon monoxide. When the stream data arrives, this CQELS node can partially process the data at its processing site and then forward the results as mapping or RDF stream elements to its parent node. \section{Related Work} In Computer Vision, a DNN-based system heavily depends on expert knowledge about the data distribution of the targeted scenario for fitting it to the proper model. However, many factors can seriously interfere with its performance, such as occlusion, illumination, fuzziness, or noise interference (cf. Figure \ref{fig:example}). To jointly deal with those factors in the same pipeline, one has to encode the joint distributions via cascading DNN models and/or manually tuned lists of parameters based on the association hypotheses that emerged from the data and empirical analysis. In fact, like our method, traditional ones such as the Joint Probabilistic Data Association Filter (JPDAF) \cite{Rezatofighi:2015} and Hypothesis Tracking (MHT) \cite{Kim:2015} use multiple hypotheses. These methods perform data association on a frame-by-frame basis. The JPDAF generates a single state hypothesis by weighting individual measurements with their association likelihoods. In MHT, all possible hypotheses are tracked, but pruning schemes must be applied for tractability. Hence, considerable domain knowledge is needed for translating them to a specific optimization problem. Moreover, heuristic tricks and parameters tuning that are only useful for a certain application and dataset. To remedy the shortcomings of such a traditional programming approach, our reasoning programs offer not only modularity and portability, but also provide a logical basis for explaining the outputs they produce. In the knowledge representation community, the closest work to ours is \cite{Suchan:2019}, which expresses the probability optimisation problems of MOT in ASP using weak constraints. Apart from our highlighted advantages (i.e supporting weight learning and more efficient with multi-shot solving) against this approach at the beginning of the paper, our approach with semantic reasoning rules is more compact and more flexible with {\em window-based search}. For instance, it is easy for our approach to incorporate additional DNNs to the DeepSORT tracking logic with additional rules which are not trivial to do with~\cite{Suchan:2019}. Moreover, ~\cite{Suchan:2019} and other approaches surveyed in~\cite{Aditya:2019} have aforementioned shortcomings in using ASP or ILP solvers with the one-shot solving mechanism. On the nature of input data, while the work in ~\cite{Aditya:2019} only considered still images, we aim at visual streams to exploit the temporal relation and semantic information among a series of visual data, e.g video frames to apply the multi-shot solving mechanism. Similarly, DeepProbLog~\cite{Robin:2018} and NeurASP~\cite{Zhun:2020} also integrate DNNs with rules; however, their focus is on static data while ours is dealing with stream data processed by neural networks to achieve performance and scalability via deriving incremental and parallel algorithms based on succinct natures of the stream data. Investigating how the latter can be transferred to these approaches remains for future work. For instance, a tighter integration of our learning algorithm with the inner DNN learning loops is the next foreseeable step in our development of SSR. Along this line, extending our framework with online learning and feedback of rules to the DNNs is suggestive; the latter is conceptually straightforward under temporal stratification. \section{Conclusion} In this paper, we presented \system, the second version of \textbf{C}ontinuous \textbf{Q}uery \textbf{E}valuation over \textbf{L}inked \textbf{S}treams. \system is a platform-agnostic federated execution framework towards semantic stream fusion. In this version, we introduced a novel neural-symbolic stream reasoning component that enables specifying deep neural network (DNN) based data fusion pipelines via logic rules with learnable probabilistic degrees as weights. As a platform-agnostic framework, \system can be implemented for devices with different hardware architectures (from embedded devices to cloud infrastructures). Moreover, this version also includes an adaptive federator that allows CQELS instances on different nodes in a network to coordinate their resources to distribute processing pipelines by delegating partial workloads to their peers via subscribing continuous queries. \section{CQELS 2.0 Framework for Semantic Stream Fusion} Semantic stream reasoning (SSR)~\cite{Danh:2021} enables the data fusion of multimodal stream data such as camera and LiDARs via declarative rules. Such rules can be written in SPARQL-based or Answer Set Programming (ASP) syntax. And the stream data flow between data fusion operations can be represented as standardized data formats, e.g, RDF Star. SSR generalizes the data model and processing operations of the previous CQELS engines, hence, CQELS 2.0 framework uses SSR formalisation and abstractions to facilitate the architecture design and implementation. Figure~\ref{fig:concept} illustrates the conceptual design of CQELS 2.0 framework that comprises several components. The~\name{Feature Extractor} component extracts the features of interest from the incoming information streams and maps them to the symbolic representation. The feature data is described with a~\emph{neuro-symbolic stream model}~\cite{Danh:2021} and its semantic is enriched via linked knowledge graphs. The~\name{Reasoning Programs Producer} component takes responsibility to generate \emph{semantic stream reasoning programs}~\cite{Danh:2021} which specify the fusion pipeline and the decision logic to choose the most likely state of the world at each evaluation. The reasoning program is evaluated by the \name{Reasoner} component, which employs an ASP solver. There are two types of reasoning rules: \emph{hard rules} and \emph{soft rules}. The hard rule is used for background knowledge given by (non-monotonic) common-sense and domain knowledge that is regarded as "always true". The soft rules expresses association hypotheses with weights corresponding to probability degrees of these rules. The weights of the rules are determined by the \name{Learning Agent} component in the starting phase. \begin{figure}[ht!] \centering \includegraphics[width=1\textwidth]{figures/SSR-ssr.jpg} \caption{The overview of conceptual design of CQELS 2.0} \label{fig:concept} \end{figure} The workflow of the framework is as follows. For the setup, the symbolic training samples are constructed from the labeled data and are fed to the \name{Learning Agent} component. The \name{Learning Agent} component computes a vector of weights for the soft rules which are stored as rule templates and passes them to the \name{Reasoning Programs Producer} component. For each training iteration, a \emph{feedback stream} returns the reasoning results back to \name{Learning Agent} component. The \name{Learning Agent} component adjusts the weights of the soft rules until the answer sets (returned as feedback streams) describe the most likely ground truth. \section{System Architecture Overview} In this section, we present a specific architecture of \system for the conceptual design in Figure~\ref{fig:concept}. CQELS framework provides a platform-independent infrastructure to implement RDF-Stream Processing (RSP) engines for computing continuous queries expressed in CQELS-QL. The first version of CQELS accepts RDF streams as input and returns RDF streams or relational streams in the SPARQL format as output. \system allows creating RDF streams by annotating extracted features from other data streams. The output RDF streams can be fed into any RSP engine, and the relational stream can be used by other relational stream processing systems. \begin{figure}[ht!] \centering \includegraphics[width=1\textwidth]{figures/SSR-cqels2.jpg} \caption{System architecture of \system.} \label{fig:cqels20} \end{figure} Figure~\ref{fig:cqels20} illustrates the overview architecture of \system. In general, \system consists of three subsystems. Subsystem \circled{1}, the RDF stream processing processor, extends the stream processing primitives of its previous version~\cite{Danh:2011} to accelerate the grounding phase of stream reasoning. For example, multiway joins are used to accelerate the incremental ground techniques~\cite{Danh:2018}. The second subsystem~\circled{2} is the semantic stream reasoning component as presented in Section 2. Finally, subsystem~\circled{3} is a stream adaptive federator, which is described as follows. Thanks to the platform-agnostic design of its execution framework~\cite{Danh:2015}, the core components are abstract enough to be seamlessly integrated with different RDF libraries in order to port the resulting system to different hardware platforms. For scalability, CQELS employs Storm\footnote{Storm. https://storm.apache.org/} and HBase\footnote{Hbase. http://hbase.apache.org/.} as underlying software stacks for coordinating parallel execution processes to build an RSP engine on the cloud computing infrastructure, called CQELS Cloud~\cite{Danh:2013}. To tailor the RDF-based data processing operations on edge devices (e.g, ARM CPU, Flash-storage), CQLES can be integrated in RDF4Led~\cite{Anh:2018}, a RISC style RDF engine for lightweight edge devices, to build Fed4Edge~\cite{Manh:2019}. The whole Fed4Edge is smaller than 10MB and needs only 4--6 MB of RAM to process millions of triples on various small devices such as BeagleBone,\footnote{https://beagleboard.org/bone} Raspberry PI.\footnote{https://www.raspberrypi.org/} Therefore, \system includes an adaptive federation mechanism to enable the coordination of different hardware resources to process query processing pipelines by cooperatively delegating partial workloads to their peer agents. The Adaptive Federator acts as the query rewriter, which adaptively divides the input query into sub queries. The rewriter then pushes down the operators as close to the streaming nodes as possible by following the predicate pushdown practice in common logical optimisation algorithms. The metadata subscribed by the other CQELS instances is stored locally. Similar to~\cite{Dell:2017}, such metadata allows the endpoint services of a CQELS engine to be discovered via the Adaptive Federator. When the Adaptive Federator sends out a subquery, it notifies the Stream Input Handler to subscribe and listens to the results returning from the subquery. On the other hand, the Stream Output Handler sends out the subqueries to other nodes or sends back the results to the requester. Similar to cloud integration with CQELS Cloud~\cite{Danh:2013}, this federation design also covers elastic-scale delopment by using the new development of Apache Flink under BIFOLD project. In particular, we use the EMMA compiling and parallelizing for data flow systems in ~\cite{Gabor:2021} to scale and optimize our processing pipelines in the cloud infrastructure. This will lay the foundation for an integration of the adaptive optimizer with the cloud-based stream scheduler and operation allocations. With the support of the above subscription and discovery operations, a stream processing pipeline written in CQELS-QL can be deployed across several sites distributed in different locations: e.g., weather stations provide environmental sensory streams in various locations on earth. Each autonomous CQELS node gives access to data streams fed from the streaming nodes connecting to it. Such stream nodes can ingest a range of sensors, such as air temperature, humidity and carbon monoxide. When the stream data arrives, this CQELS node can partially process the data at its processing site and then forward the results as mapping or RDF stream elements to its parent node. \section{Related Work} In Computer Vision, a DNN-based system heavily depends on expert knowledge about the data distribution of the targeted scenario for fitting it to the proper model. However, many factors can seriously interfere with its performance, such as occlusion, illumination, fuzziness, or noise interference (cf. Figure \ref{fig:example}). To jointly deal with those factors in the same pipeline, one has to encode the joint distributions via cascading DNN models and/or manually tuned lists of parameters based on the association hypotheses that emerged from the data and empirical analysis. In fact, like our method, traditional ones such as the Joint Probabilistic Data Association Filter (JPDAF) \cite{Rezatofighi:2015} and Hypothesis Tracking (MHT) \cite{Kim:2015} use multiple hypotheses. These methods perform data association on a frame-by-frame basis. The JPDAF generates a single state hypothesis by weighting individual measurements with their association likelihoods. In MHT, all possible hypotheses are tracked, but pruning schemes must be applied for tractability. Hence, considerable domain knowledge is needed for translating them to a specific optimization problem. Moreover, heuristic tricks and parameters tuning that are only useful for a certain application and dataset. To remedy the shortcomings of such a traditional programming approach, our reasoning programs offer not only modularity and portability, but also provide a logical basis for explaining the outputs they produce. In the knowledge representation community, the closest work to ours is \cite{Suchan:2019}, which expresses the probability optimisation problems of MOT in ASP using weak constraints. Apart from our highlighted advantages (i.e supporting weight learning and more efficient with multi-shot solving) against this approach at the beginning of the paper, our approach with semantic reasoning rules is more compact and more flexible with {\em window-based search}. For instance, it is easy for our approach to incorporate additional DNNs to the DeepSORT tracking logic with additional rules which are not trivial to do with~\cite{Suchan:2019}. Moreover, ~\cite{Suchan:2019} and other approaches surveyed in~\cite{Aditya:2019} have aforementioned shortcomings in using ASP or ILP solvers with the one-shot solving mechanism. On the nature of input data, while the work in ~\cite{Aditya:2019} only considered still images, we aim at visual streams to exploit the temporal relation and semantic information among a series of visual data, e.g video frames to apply the multi-shot solving mechanism. Similarly, DeepProbLog~\cite{Robin:2018} and NeurASP~\cite{Zhun:2020} also integrate DNNs with rules; however, their focus is on static data while ours is dealing with stream data processed by neural networks to achieve performance and scalability via deriving incremental and parallel algorithms based on succinct natures of the stream data. Investigating how the latter can be transferred to these approaches remains for future work. For instance, a tighter integration of our learning algorithm with the inner DNN learning loops is the next foreseeable step in our development of SSR. Along this line, extending our framework with online learning and feedback of rules to the DNNs is suggestive; the latter is conceptually straightforward under temporal stratification. \section{Conclusion} In this paper, we presented \system, the second version of \textbf{C}ontinuous \textbf{Q}uery \textbf{E}valuation over \textbf{L}inked \textbf{S}treams. \system is a platform-agnostic federated execution framework towards semantic stream fusion. In this version, we introduced a novel neural-symbolic stream reasoning component that enables specifying deep neural network (DNN) based data fusion pipelines via logic rules with learnable probabilistic degrees as weights. As a platform-agnostic framework, \system can be implemented for devices with different hardware architectures (from embedded devices to cloud infrastructures). Moreover, this version also includes an adaptive federator that allows CQELS instances on different nodes in a network to coordinate their resources to distribute processing pipelines by delegating partial workloads to their peers via subscribing continuous queries. \section{A Call for An Overhaul of CQELS Framework} \section{Introduction and Motivation} CQELS was proposed as one of the first RDF stream processing engines to solve the data integration problem for sensor data, Internet of Things, and the Web of data~\cite{Danh:2011}. The key feature of this data integration approach is the semantic interoperabiliy enabled by RDF data models. The framework has been used in various industry and research applications both as open source and commercial software The recent advances in \textit{machine learning} (ML) with \textit{deep neural network} (DNN) leads to the enormous amount of data in various formats, and in many cases from multimodal stream data with high accuracy. Therefore, the existing framework is no longer suitable for the new application scenarios and requires significant extensions. Towards this goal, in \system, we integrate a number of new stream data types such as video streams, LiDARs, and support more hardwares such as ARM and mobiles~\cite{Anh:2018,Manh:2019}. Moreover, we provide data fusion operations in our engines~\cite{Danh:2021,Manh:2021}. For example, the operation for object detection DNNs~\cite{Joseph:2015, Shaoqing:2015} returns a set of bounding boxes and object classes given an image or video frames. Thus, \system is designed as a DNN-based data stream fusion framework. Along with the new feature for different data sources, the CQELS-QL query language has evolved from supporting event query patterns~\cite{Minh:2015,Daniele:2016} to probabilistic reasoning in~\cite{Danh:2021,Manh:2021}. To implement such complex features and also to support for future demand in research, we bring the existing CQELS framework to the next level with new architecture and design. The new design is driven by requirements from use cases and research problems from various research projects (e.g. DFG COSMO\footnote{https://gepris.dfg.de/gepris/projekt/453130567?language=en} and BMBF BIFOLD\footnote{https://bifold.berlin/}) and industry partners. For example, application scenarios in edge intelligence~\cite{Zhi:2019,Shuiguang:2020} and industry 4.0 from DellEMC, Siemens and Bossh motivate us to build \emph{autonomous processing kernels} powered by CQELS~\cite{Manh:2019,Manh:2021}. Such systems deal with city-scale camera deployments which have become ubiquitous in smart cities and traffic monitoring with a continuously increasing in size and utilization of their deployments. For instance, the British Security Industry Association estimates that there are between 4 to 5.9 millions CCTV cameras in the UK~\cite{cctv}. To this end, the new design of CQELS framework has to deal with not only the new level of complexity of data sources, processing operations and deployment settings, but also with significantly larger processing scale in terms of throughput and volume. \section{Provisional Features} In this section, we present the details of a provisional feature of \system that can be used to solve the \emph{multiple object tracking} (MOT) problem~\cite{Bernardin:2008}. In computer vision, MOT algorithms are normally programmed in C/C++ or Python. With \system, we will show that the widely used tracking-by-detection approach~\cite{Ciaparrone:2019} for the MOT problem can be emulated in a declarative fashion with rules and queries. The key operations in tracking-by-detection approaches (e.g., SORT~\cite{Bewley:2016}, DEEPSORT~\cite{Wojke:2017}) are as following: 1) detection of objects (using DDN-based detector), 2) propagating object states (e.g., location and velocity) into future frames, 3) associating current detection with existin \begin{figure}[ht!] \centering \includegraphics[width=1.\textwidth]{figures/SSR-runex.jpg} \caption{A Semantic Visual Stream Snapshot. The red boxes are detected bounding boxes and the yellow boxes are tracked bounding boxes.} \label{fig:example} \end{figure} Figure~\ref{fig:example} illustrates the SORT algorithm~\cite{Bewley:2016} which is a simple object tracking algorithm based on DNN detectors such as SSD~\cite{Liu:2016} or YOLO~\cite{Redmon:2017}. To associate resultant detections with existing targets, SORT uses a Kalman filter~\cite{Bishop:2001} to predict the new locations of targets in the current frame. At time point 2, the red boxes $b_1$ and $b_3$ are newly detected, and the yellow boxes $b_2$ and $b_4$ are predicted by a Kalman filter based on the tracked boxes from the previous frame. Then, the SORT algorithm computes an associative cost matrix between detections and targets based on the intersection-over-union (IOU) distance between each detection and all predicted bounding boxes from the existing tracklets. In case some detection is associated with a target, the detected bounding box is used to update the target state via the Kalman filter. As in frame 2, the tracklets $trk_1$ and $trk_2$ are set to the two new bounding boxex $b_1$ and $b_2$ which are associated with predicted boxes $b_3$ and $b_4$ respectively. Otherwise, the target state is simply predicted without correction using the linear velocity model. For example, at time point 3, the detector misses detecting the white car due to an occlusion, however, the tracklet 2 is till assigned to box $b_7$ which contains part of the white car. With the Feature Extractor component (see. Figure~\ref{fig:concept}), \system extracts the detection boxes from input video frames and represent them as RDF facts. The data abstraction is modelled using the neural symbolic stream modelling practice (presented in~\cite{Danh:2021}), which extends the standardised Semantic Sensor Network Ontology (SSN)~\cite{Armin:2019} to model video streams and intermediate processing states. The extension includes various vocabularies to specify the semantics of camera sensors, video frames, and tensors as shown in Figure~\ref{fig:abstract}. \begin{figure}[ht!] \centering \includegraphics[width=1\textwidth]{figures/ssn1} \caption{Data abstraction of Neural-Symbolic stream with Semantic Sensor Network Ontology} \label{fig:abstract} \end{figure} With the above data abstraction, \system consumes the video data stream that is observed by a camera (as a ${Sensor}$) as \emph{a stream of observations}. Each observation is a video frame. These video frames are represented as instances of the class ${Image2D}$ that inherits from the generic ${Observation}$ class of SSN. The detection of a video frame or a tracklet are represented as SSN $Sampling$ which are processed by a DNN model or a CV algorithm represented as a \emph{Procedure}. \begin{lstlisting}[ caption={Semantic Stream Serialization with RDF$^*$}, label={rdf:frame2}, language=SPARQL, numbers=left, captionpos=b, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor},] //time point/frame 2 <<:image2 a :Image2D>> a sosa:Observation; sosa:madeBySensor :cam1; sosa:resultTime 2. <<:det1 :det :b1>> a :Detection; sosa:resultTime 2; sosa:hasSimpleResult 'car'; :score '0.8'; :isDetectionOf :image2; sosa:usedProcedure :Yolo. <<:det1 :det :b3>> a :Detection; sosa:resultTime 2; sosa:hasSimpleResult 'car'; :score '0.7'; :isDetectionOf :image2; sosa:usedProcedure :Yolo. <<:trk1 :trk :b2>> a :Tracklet; sosa:resultTime 2; sosa:usedProcedure :KalmanFilter. <<:trk2 :trk :b4>> a :Tracklet; sosa:resultTime 2; sosa:usedProcedure :KalmanFilter. \end{lstlisting} For example, Listing~\ref{rdf:frame2} illustrates the the symbolically representation in RDF* format\footnote{\url{https://w3c.github.io/rdf-star/cg-spec/editors$\_$draft.html}} of the frame 2 in the stream snapshot in Figure~\ref{fig:example} Line 5 denotes that the detection model generates an output consisting of a bounding box $b_1$, object type $car$ and confidence score $0.8$. Line 13 presents that the box $b_2$ is predicted by a Kalman filter and is tracked by tracklet 1. To emulate these MOT algorithms, \system represents these association hypotheses by hard rules and soft rules that are translated into an optimization problem solved by an ASP Solver. To formalise the reasoning process on semantic representations of stream data, we use a temporal semantic model that allows us to reason about the properties and features of objects. The model accounts for the laws of the physical world and commonsense, which allow the system to handle incomplete information (e.g., if we do not see objects appearing in observations, or camera reads are missing). Using the above RDF representations, we allow RDF\&SPARQL developers to write soft rules with SHACL rule language\footnote{SHACL Advanced Features} along with the extension of CQEL-QL. The extension we made here is replacing SPARQL CONSTRUCT with the corresponding CONSTRUCT of CQELS-QL which extends SPARQL with the window operators over RDF Stream. Moreover, extending SHACL for expressing ASP-like rules is aligned with the recent proposal for assigning SHACL to negation stable semantics~\cite{Medina:2020}. Note that we extend CQESL-QL syntax in~\cite{Danh:2011} with the keyword "NAF" to express the default negation of ASP. For example, the soft rule 1 in Listing~\ref{soft-rule1} is used to trigger the event a car enters the "Field of View" of a camera and the car starts being tracked. \begin{lstlisting}[ caption={Soft rule 1 - detect vehicles entering Field of View}, label={soft-rule1}, captionpos=b, language=SPARQL, numbers=left, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor}, escapeinside=||,] ssr:rule_w_1 a sh:NodeShape; sh:rule [ a sh:CQELSRule ; sh:prefixes ssr: ; sh:construct |"""| CONSTRUCT {<<?O :enters <ssr:FoV>> @ ?T.} WHERE { STREAM <:ssr> { <<?Dt :det ?B >> @ ?T; :score ?S. ?B sosa:isSampleOf ?O ; a :car. FILTER (?S > 0.8) } NAF STREAM <:ssr> window[5 sec] { ?O :inFOV ssr:FoV. } } |"""| ; ] ; \end{lstlisting} To associate a detected bounding box $B$ with an object $O$, we use soft rules that assert the triple <<B sosa:isSampleOf O>> based on {\em explained spatial, temporal, and visual appearance evidences}. Such rules can be used to represent {\em hypotheses}\/ on temporal relations among detected objects in video frames following a tracking trajectory. When the object's movement is consistent with the constant velocity model, e.g., the Kalman filter used in SORT~\cite{Bewley:2016}, and there is a detection associated with its trajectory, the fact <<B sosa:isSampleOf O>> is generated by rule~\ref{soft-rule2}. Here, $iou(B_1,B_2)$ states the IOU (intersection over union) condition of the bounding boxes $B_1$ and $B_2$ satisfy. \begin{lstlisting}[ caption={Soft rule 2 - emulation of SORT algorithm~\cite{Bewley:2016}.}, label={soft-rule2}, captionpos=b, language=SPARQL, numbers=left, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor}, escapeinside=||,] ssr:rule_w_2 a sh:NodeShape ; sh:rule [ a sh:CQELSRule ; sh:prefixes ssr: ; sh:construct |"""| CONSTRUCT { ?B1 sosa:isSampleOf ?O. } WHERE{ STREAM <:ssr>{ <<?Dt :det ?B2 >> @ ?T; :score ?S. <<?Trk :trk ?B1 >> @ ?T. ?Trk :trklet ?O. FILTER (?S>0.8 && iou (?B1,?B2) > 0.8) } } |"""| ; ] ; \end{lstlisting} \begin{lstlisting}[ caption={Soft rule 3 - emulation of DEEPSORT algorithm~\cite{Wojke:2017}.}, label={soft-rule3}, captionpos=b, language=SPARQL, numbers=left, basicstyle=\footnotesize\ttfamily, backgroundcolor=\color{lbcolor}, escapeinside=||,] ssr:rule_w_3 a sh:NodeShape ; sh:rule [ a sh:CQELSRule ; sh:prefixes ssr: ; sh:construct |"""| CONSTRUCT { ?B1 sosa:isSampleOf ?O. } WHERE{ STREAM <:ssr> @?Te window[5 sec] { ?Trk2 :trk ?B2 } STREAM <:ssr>{ <<?Trk1 :trk ?B1 >> @ ?T. <<?B1 :vMatch ?B2 >> :score ?S. ?B2 sosa:isSampleOf ?O. ?Trk2 :ends ?Te. FILTER {?T<?Te+3 && ?S>0.8 } } } |"""| ; ] ; \end{lstlisting} Furthermore, we can also emulate DeepSORT~\cite{Wojke:2017} via the soft rule~\ref{soft-rule3} that can search for supporting evidences to link a newly detected bounding box from an occluded tracklet using visual appearance associations, e.g. frames 2 and 4 of Figure~\ref{fig:example}. For this, we search for pairs of bounding boxes from recently occluded tracklets w.r.t. visual appearance. As the search space of possible matches is large, we limit it by filtering the candidates based on their temporal and spatial properties. To this end, we use rules with windows to reason about disconnected tracklets that have bounding boxes visually matched within a window of time points that are aligned with DeepSORT's gallery of associated appearance descriptors for each tracklet. Based on this gallery of previously tracked boxes, the appearance-based discriminative metrics are computed to recover the identities after long-term occlusion, where the motion is less discriminative. Hence, to connect a newly detected bounding box $B_1$ that has a visual appearance match with another bounding box $B_2$ (represented by the fact <<$B_1$ :vMatch $B_2.$>> in line 13) of a discontinued tracklet $T_2$ (represented by <<$Trk_2$ :ends $T_e$>> in line 15) that ended 3 time points before.
{'timestamp': '2022-03-01T02:57:15', 'yymm': '2202', 'arxiv_id': '2202.13958', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13958'}
arxiv
\section{Introduction} \label{sec:intro} Detecting the positions of a person's hands and an object-in-contact (hand-object detection) from an image provides an important clue for understanding how the person interacts with the physical world. This hand-object detection is applicable to recognizing a person's primitive actions, such as ``taking" or ``pushing", and logging the person's activity of interacting with the environment~\cite{yagi2021go}. Shan et al.~\cite{Shan20} built a hand-object detector for localizing hands and interacting objects on a large-scale dataset collected in naturalistic house-holding situations, such as in kitchen~\cite{damen2018scaling, li2018eye, sigurdsson2018actor}, DIY~\cite{Shan20}, and craft work~\cite{Shan20, sigurdsson2018actor}. However, a hand-object detector trained on such house-holding images may not be well generalized to other hand-manipulation images. For instance, the images in biological laboratories or factories have significantly different data distribution from the daily scenes used in training. To build an accurate hand-object detector for such unique application domains, a large amount of data and labels must be collected from scratch. However, data collection and annotation can be difficult due to various reasons, such as cost or privacy issues. In particular, expert knowledge is required to annotate the data in such specific application domains. Under these limitations, a hand-object detector may overfit the training data and lack the generalization ability due to the small amount of training data. To improve the generalization ability of the detector trained on a small dataset, data augmentation is a key component in training. Recently, Mixup~\cite{zhang2017mixup}, a method that overlays two different images, has been used as an empirically strong augmentation for object detection~\cite{zhou2021instant}. Nevertheless, naively applying Mixup induces unintended biases in hand-object detection. As shown in Figure~\ref{fig:mixup_issue}, (a) contact states become ambiguous when hand-object pairs from different images overlap, and (b) the concentration of hands and objects in a specific local region makes identifying object boundaries difficult. These unintended mixtures will degrade the performance of a hand-object detector. \begin{figure}[tb] \centering \begin{minipage}[t]{\linewidth} \centering \includegraphics[width=0.85\linewidth]{image/section1/bbox_type.png} \end{minipage} \\ \begin{minipage}[t]{0.48\linewidth} \centering \includegraphics[height=2.6cm, width=\linewidth]{image/section1/missing_grab.png} \subcaption{Ambiguous contact states} \end{minipage} \begin{minipage}[t]{0.48\linewidth} \centering \includegraphics[height=2.6cm, width=\linewidth]{image/section1/complex.png} \subcaption{Ambiguous object boundaries} \end{minipage} \caption{\textbf{Problems with Mixup.} Naively mixing two images causes ambiguity in (a) contact states and (b) object boundaries.} \label{fig:mixup_issue} \end{figure} \begin{figure}[tb] \centering \includegraphics[width=0.9\linewidth]{image/section1/teaser.png} \caption{\textbf{Overview of Background Mixup.} We aim to improve diversity in training data while preserving foreground's semantics.} \label{fig:teaser} \end{figure} To handle this, we propose a novel data-augmentation method, called Background Mixup, that utilizes data-mixing regularization while reducing the unintended effects in hand-object detection. As shown in Figure~\ref{fig:teaser}, we aim to augment a training image by mixing it with the background of external image sources that does not contain the foreground (i.e., hands and objects-in-contact) and using the mixed images for training a hand-object detector. The contributions of this paper are summarized as follows. \begin{itemize} \item We propose a novel data-augmentation method, Background Mixup, that mixes a training image and a background image to improve the generalization ability of a hand-object detector in a small dataset. \item Compared with Mixup, our experiments showed that Background Mixup improves the performance of a hand-object detector in supervised and semi-supervised learning settings. \item Our method has also shown to be effective in reducing the number of false-positive predictions although Mixup has the disadvantage in this metric. \end{itemize} \section{Related Work} \label{sec:related} \subsection{Hand and Object-in-Contact} Jointly analyzing hands and objects-in-contact serves to understand human behavior~\cite{li2015delving,bambach2015lending}. While these studies have been conducted in a limited scale of data, Shan et al.~\cite{Shan20} proposed a large-scale dataset for training a hand-object detector localizing hands and interacting objects, which is collected in daily situations such as EPIC-KITCHENS 2018~\cite{damen2018scaling}, EGTEA~\cite{li2018eye}, CharadesEgo~\cite{sigurdsson2018actor}. However, directly fine-tuning the hand-object detector on a small and specific dataset can lead to limited performance as discussed in Section~\ref{sec:intro}. To overcome this, we developed Background Mixup to improve the generalization ability of a hand-object detector on a small dataset in specific domains such as biomedical experiments and factory work. \subsection{Mixture-Based Data Augmentation} \label{sec:interpolation_aug} Mixture-based data augmentation mixes input data with other inputs to increase the diversity of data on a small dataset and improve the generalization performance of the model. Several mixture-based methods, such as Mixup~\cite{zhang2017mixup}, CutMix~\cite{yun2019cutmix}, Mosaic~\cite{ge2021yolox}, and Cutout~\cite{devries2017cutout}, have been used in many downstream tasks. These mixture-based methods are used for semi-supervised learning of object detection~\cite{liu2021unbiased,zhou2021instant}. Unbiased-Teacher~\cite{liu2021unbiased} uses Cutout while Instant-Teaching~\cite{zhou2021instant} uses Mixup and Mosaic showing that Mixup particularly contributes to improving the performance of object detection. However, applying Mixup leads to unintended biases in the hand-object detection, as discussed in Section~\ref{sec:intro}. These unintended mixtures will degrade the performance of a hand-object detector. \section{Proposed Method} \label{sec:method} In this section, we introduce our proposed training of a hand-object detector with Background Mixup data augmentation. Let $\mathcal{X}_{train}$ and $\mathcal{X}_{test}$ be sets of training and testing images, respectively. When the size of $\mathcal{X}_{train}$ is small, a hand-object detector trained on $\mathcal{X}_{train}$ may not generalize well to $\mathcal{X}_{test}$ due to over-fitting to the training data. To solve this problem, we propose Background Mixup that uses a background image without foreground entities, i.e., hands and objects-in-contact, for increasing the diversity of the training data. We use a trained hand-object detector~\cite{Shan20} to extract the background images from an external image source (e.g., kitchens), which are different from our target data of $\mathcal{X}_{train}$ and $\mathcal{X}_{test}$. We extract the background images in which neither object-in-contact nor hand was detected by the hand-object detector, and construct a set of the background images $\mathcal{X}_{bg}$. Figure \ref{fig:diff_mixup} shows a comparison between Mixup and Background Mixup. With Mixup, the foreground and background are combined, causing unintended effects that make the contact state ambiguous or make it difficult to identify the boundaries of objects, as shown in Figure \ref{fig:mixup_issue}. In contrast, Background Mixup reduces such unintended effects by mixing the training image with the background image, which can retain the foreground of the training image. \begin{figure}[tb] \centering \includegraphics[width=0.8\linewidth]{image/section3/difference_mixup.png} \caption{Comparison of Mixup~\cite{zhang2017mixup} and Background Mixup.} \label{fig:diff_mixup} \end{figure} We denote the training image as $I_{train}\in\mathcal{X}_{train}$ and the background image as $I_{bg}\in\mathcal{X}_{bg}$. We define Background Mixup as: \begin{equation} \hat{I} = \lambda I_{train} + (1-\lambda) I_{bg} \end{equation} \begin{equation} \lambda \sim Beta(\alpha, \beta). \end{equation} \noindent where $I_{train}$ and $I_{bg}$ are randomly sampled and $\lambda\in[0, 1]$ is a parameter controlling the degree of the mixture. Following Mixup, the parameter $\lambda$ is drawn from beta distribution $Beta(\alpha, \beta)$ where $\alpha$ and $\beta$ indicate hyperparameters to determine the distribution shape. We use $\hat{I}$ for training the hand-object detector instead of $I_{train}$. This method can be implemented with a small computational cost at the training stage. Thus no additional computational cost is required in inference. \section{Experiments} \label{sec:experiment} \subsection{Experimental Setup} \textbf{Datasets.} We validated our method on various hand manipulation datasets including biomedical experiments, mock factories, and kitchens. We used a first-person video dataset of biomedical experiments and a mock factory environment dataset~\cite{ragusa2021meccano} as specific application domains where the data size and variety are limited. We also used a kitchen environment dataset~\cite{damen2018scaling, Shan20} including diverse cooking scenes. For the dataset of biomedical experiments, we recorded 12 videos that contained basic actions such as preparing reagents in a biomedical lab. The bounding boxes of hands and objects-in-contact were annotated by an expert in the field. The total duration is 27 minutes, and the number of annotated frames is 3,093. We split the 12 videos into 6:3:3 for train:val:test. For the set of background images in the experiments on biomedical and factory datasets, we used EPIC-KITCHENS-100~\cite{Damen2021RESCALING} of cooking scenes in kitchens as an external image source. For the experiments on the cooking dataset, we used Something-Something V2~\cite{goyal2017something} of daily scenes as an external image source to augment the background appearance. \textbf{Training details.} We measure the performance of our method in supervised and semi-supervised learning settings. For supervised learning, we fine-tune the pre-trained hand-object detector proposed by Shan et al.~\cite{Shan20}. For semi-supervised learning, we trained the hand-object detector in the training pipeline of Unbiased-Teacher (UB-Teacher)~\cite{liu2021unbiased}. We evaluated the performance by the average precision (AP) of hands and objects-in-contact. Note that we do not provide hand AP in an experiment with mock factory environment dataset~\cite{ragusa2021meccano} because the hand bounding boxes are not annotated. \textbf{Baselines.} We denote our proposed Background Mixup with EPIC-KITCHENS-100~\cite{Damen2021RESCALING} and Something-Something V2~\cite{goyal2017something} as \textbf{BG-Mix$_{K}$} and \textbf{BG-Mix$_{D}$}, respectively. We prepared two variants of Mixup as comparison methods. \textbf{Mixup} is the original Mixup that combines two different images within a dataset, and \textbf{Mixup$_{K}$} is Mixup that mixes a training image with a randomly selected image from EPIC-KITCHENS 2018~\cite{Shan20,damen2018scaling}. \subsection{Quantitative Evaluation} \subsubsection{Supervised Learning} \label{sec:qual_sup} \begin{table*}[t] \begin{center} \caption{Quantitative comparisons on supervised learning.} \label{tab:sup_eval_ind_kitchen} \scalebox{0.8}[0.8]{ \begin{tabular}{@{}lcccccccc@{}} \toprule & \multicolumn{3}{c}{Biomedical} & \multicolumn{2}{c}{Factory} & \multicolumn{3}{c}{Cooking} \\ Model & hand AP & obj AP & mAP & hand AP & obj AP & hand AP & obj AP & mAP \\ \midrule Supervised & \textbf{90.9} $\pm{0.0}$ & 70.6 $\pm{0.3}$ & 80.7 $\pm{0.2}$ & - & 45.0 $\pm{0.1}$ & \textbf{90.6} $\pm{0.0}$ & \textbf{66.4} $\pm{0.1}$ & \textbf{78.5}$\pm{0.0}$\\ \; + Mixup & \textbf{90.9} $\pm{0.0}$ & 70.4 $\pm{0.1}$ & 80.6 $\pm{0.0}$ & - & 44.6 $\pm{0.0}$ & \textbf{90.6} $\pm{0.0}$ & 65.6 $\pm{0.2}$ & 78.1$\pm{0.1}$\\ \; + Mixup$_{K}$ & \textbf{90.9} $\pm{0.0}$ & 69.8 $\pm{0.4}$ & 80.4 $\pm{0.2}$ & - & 44.6 $\pm{0.1}$ & - & - & - \\ \; + BG-Mix$_{K}$ & \textbf{90.9} $\pm{0.1}$ & \textbf{72.2} $\pm{0.2}$ & \textbf{81.0} $\pm{0.1}$ & - & \textbf{45.2} $\pm{0.1}$ & - & - & - \\ \; + BG-Mix$_{D}$ & - & - & - & - & - & \textbf{90.6} $\pm{0.0}$ & 65.7 $\pm{0.2}$ & 78.2$\pm{0.1}$\\ \bottomrule \end{tabular} } \end{center} \end{table*} Table \ref{tab:sup_eval_ind_kitchen} lists the results on the supervised learning settings. In the biomedical and mock factory environment datasets, BG-Mix$_{K}$ exhibited the highest performance in mAP and object AP while Mixup and Mixup$_{K}$ decreased in these metrics. This is because our method avoids the unintended effects shown in Figure \ref{fig:mixup_issue}, which degrades the performance of detecting an object-in-contact. In the cooking dataset, however, Mixup, Mixup$_{K}$ and BG-Mix$_{D}$ all obtained lower obj AP and hand AP than the Supervised baseline because the dataset already has diverse foreground and background appearances even without data augmentation. The hand APs of Background Mixup did not increase because the hand APs were already saturated. \subsubsection{Semi-Supervised Learning} \begin{table*}[tb] \begin{center} \caption{Quantitative comparisons on semi-supervised learning at 1\% labels.} \label{tab:semi_eval_ind_kitchen} \scalebox{0.8}[0.8]{ \begin{tabular}{@{}lcccccccc@{}} \toprule & \multicolumn{3}{c}{Biomedical} & \multicolumn{2}{c}{Factory} & \multicolumn{3}{c}{Cooking} \\ Model & hand AP & obj AP & mAP & hand AP & obj AP & hand AP & obj AP & mAP \\ \midrule UB-Teacher & 90.6 $\pm{0.1}$ & 64.0 $\pm{1.1}$ & 77.3 $\pm{0.4}$ & - & 27.0 $\pm{0.5}$ & \textbf{90.5} $\pm{0.0}$ & 41.4 $\pm{0.5}$ & 65.9 $\pm{0.3}$\\ \; + Mixup & \textbf{90.9} $\pm{0.0}$ & 62.4 $\pm{3.4}$ & 76.6 $\pm{1.7}$ & - & 30.4 $\pm{1.4}$ & 90.4 $\pm{0.0}$ & 46.5 $\pm{0.1}$ & 68.5 $\pm{0.1}$\\ \; + Mixup$_{K}$ & 90.8 $\pm{0.1}$ & 65.4 $\pm{0.6}$ & 78.1 $\pm{0.3}$ & - & 31.0 $\pm{1.4}$ & - & - & - \\ \; + BG-Mix$_{K}$ & 90.8 $\pm{0.1}$ & \textbf{66.4} $\pm{0.1}$ & \textbf{78.6} $\pm{0.1}$ & - & \textbf{32.6} $\pm{0.7}$ & - & - & - \\ \; + BG-Mix$_{D}$ & - & - & - & - & - & \textbf{90.5} $\pm{0.0}$ & \textbf{47.2} $\pm{0.5}$ & \textbf{68.9} $\pm{0.2}$\\ \bottomrule \end{tabular} } \end{center} \end{table*} Table \ref{tab:semi_eval_ind_kitchen} shows the results for semi-supervised learning with 1\% labeled data. BG-Mix$_{K}$ and BG-Mix$_{D}$ exhibited the highest performance on all datasets, except for the hand AP on the biomedical data. In the cooking dataset having a variety of objects and backgrounds, although the performance of supervised learning decreased with both BG-Mix$_D$ and Mixup as shown in Section \ref{sec:qual_sup}, BG-Mix$_D$ improved the performance of semi-supervised learning. This indicates that Background Mixup is effective under limited labels where the fully-supervised model suffers from generalizing to unknown test data. \subsubsection{Analysis of False-positive Predictions} Although mAP is a standard evaluation criterion in object detection, there is a technique that can improve the mAP score by allowing many false positives with low confidence ~\cite{kaggle2021map}. However, detection results that contain many false positives are problematic in real scenarios. Therefore, we experimented with precision to measure the percentage of false positives in detection results of a hand-object detector. Precision indicates the percentage of true positives among the predictions detected as positive. In other words, the lower precision, the higher the percentage of false positives. Table \ref{tab:comparison_fp} shows a comparison of precision when the percentage of labeled data is 1\% in semi-supervised learning, and the confidence threshold is 0.1. While Mixup$_{K}$ improves mAP, the precision is decreased. This indicates training the detector on mixed images with many overlapping bounding boxes in a specific area, as illustrated in Fig.~\ref{fig:mixup_issue}(b), induces the bias of increasing the number of false positives. BG-Mix$_{K}$ can improve the mAP without increasing the number of false positives because it keeps the information of hand-object contact and avoids the concentration of target hands and objects-in-contact in a local region. \begin{table}[tb] \begin{center} \caption{Comparisons of false positive predictions on biomedical experiments dataset.} \label{tab:comparison_fp} \scalebox{0.85}[0.85]{ \begin{tabular}{@{}lccc@{}} \toprule Model & mAP & Precision$_{hand}$ & Precision$_{obj}$ \\ \midrule UB-Teacher & 77.3$\pm{0.6}$ & 87.1 $\pm{1.5}$ & \textbf{49.7} $\pm{0.1}$ \\ \; +Mixup & 76.6$\pm{1.7}$ & 76.8 $\pm{1.8}$ & 42.0 $\pm{3.2}$ \\ \; +Mixup$_{K}$ & 78.1$\pm{0.3}$ & 75.6 $\pm{5.3}$ & 38.7 $\pm{2.9}$ \\ \; +BG-Mix$_{K}$ & \textbf{78.6} $\pm{0.1}$ &\textbf{89.1} $\pm{2.5}$ & 48.8 $\pm{2.6}$ \\ \bottomrule \end{tabular} } \end{center} \end{table} \subsection{Qualitative Evaluation} \begin{figure}[tb] \vspace{0.3cm} \hspace{-0.35cm} \begin{tabular}{c} \includegraphics[width=0.35\linewidth]{image/section4/bbox_type.png} \\ \begin{tabular}{cccc} \begin{minipage}[t]{0.23\linewidth} \centering \includegraphics[clip, width=\linewidth]{image/section4/none/12well_medium_fpv_255.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/none/insert_tube_fpv4_1304.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/none/prep_reagent_fpv_930.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/none/prep_reagent_fpv_4256.png} \\ \subcaption{UB-Teacher} \end{minipage} \begin{minipage}[t]{0.23\linewidth} \centering \includegraphics[clip, width=\linewidth]{image/section4/mixup/12well_medium_fpv_255.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/mixup/insert_tube_fpv4_1304.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/mixup/prep_reagent_fpv_930.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/mixup/prep_reagent_fpv_4256.png} \\ \subcaption{+Mixup} \end{minipage} \begin{minipage}[t]{0.23\linewidth} \centering \includegraphics[clip, width=\linewidth]{image/section4/ek_mixup/12well_medium_fpv_255.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/ek_mixup/insert_tube_fpv4_1304.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/ek_mixup/prep_reagent_fpv_930.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/ek_mixup/prep_reagent_fpv_4256.png} \\ \subcaption{+Mixup$_{K}$} \end{minipage} \begin{minipage}[t]{0.23\linewidth} \centering \includegraphics[clip, width=\linewidth]{image/section4/ek_bgmix/12well_medium_fpv_255.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/ek_bgmix/insert_tube_fpv4_1304.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/ek_bgmix/prep_reagent_fpv_930.png} \\ \includegraphics[clip, width=\linewidth]{image/section4/ek_bgmix/prep_reagent_fpv_4256.png} \\ \subcaption{+BG-Mix$_{K}$} \end{minipage} \end{tabular} \end{tabular} \caption{Qualitative results in detecting object-in-contact. } \label{fig:qualitative_comparison} \end{figure} Figure \ref{fig:qualitative_comparison} shows the inference results for object-in-contact with a confidence threshold of 0.1. We observed that Figure~\ref{fig:qualitative_comparison} (b) Mixup and (c) Mixup$_{K}$ increased the number of false positives (e.g., red bounding boxes far from the ground truth bounding boxes). In contrast, the predictions of Figure~\ref{fig:qualitative_comparison} (d) Background Mixup is less noisy and accurately represent the location of the object-in-contact compared to ground truth. Our method of increasing the diversity of the background without changing the foreground semantics could improve the performance of a hand-object detector without increasing the number of false positives. \section{Conclusion} \label{sec:conclusion} We proposed Background Mixup, which mixes training images with background images that do not contain the hands and the objects-in-contact, whereas Mixup mixes both the foreground (i.e., the hand and the object-in-contact) and the background. Background Mixup can improve the performance of a hand-object detector in small datasets, such as biomedical experiments and mock factory environments, by increasing the diversity of the background appearances while inhibiting the unintended effects caused by Mixup. We have also shown that Background Mixup was effective in reducing the number of false positives.
{'timestamp': '2022-03-02T02:12:17', 'yymm': '2202', 'arxiv_id': '2202.13941', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13941'}
arxiv
\subsection{Effective Bandwidth Benchmark} In this benchmark, we use the rules of the Effective Bandwidth (b\_eff) benchmark given in \cite{b_eff_website}. It is a synthetic benchmark that uses the derived metric \emph{effective bandwidth} to combine both -- the network latency and bandwidth -- into a single metric. The original benchmark sends messages of sizes $2^0, 2^1, \dots, 2^{20}$ \si{\byte} to neighbor nodes in a ring topology. The effective bandwidth is calculated from the measured bandwidth for the different message sizes as shown in Equation~\ref{eq:effective_bandwidth}. \begin{equation} b_{\mathit{eff}} = \frac{\sum_L(\mathit{max}_{\mathit{rep}}(b(L, \mathit{rep})))}{21} \label{eq:effective_bandwidth} \end{equation} where $L$ are the message sizes, $\mathit{rep}$ the repetitions of the execution and $b(L, \mathit{rep})$ the measured bandwith for message size $L$ during repetition $\mathit{rep}$. The base implementation of this benchmark does not require a \ac{FPGA} kernel because data is transferred between the \acp{FPGA} solely by the host. The optimized version for Intel FPGAs is configurable with the parameters given in Table~\ref{tab:b_eff_configuration_parameters}. Next to the number of kernel replications, it contains the width of the external channels in Bytes. \begin{table} \centering \caption{Configuration parameters of the b\_eff benchmark} \begin{tabular}{p{2.5cm}p{4.5cm}} \toprule \textbf{Parameter} & \textbf{Description} \\ \midrule \texttt{CHANNEL\_WIDTH} & The width of a single external channel in bytes \\ \bottomrule \end{tabular} \label{tab:b_eff_configuration_parameters} \end{table} \subsubsection{Base Implementation} The base implementation exchanges the messages between the global memory of neighboring \acp{FPGA} in the ring. Therfore, it reads a memory buffer representing the message using the OpenCL directive \texttt{clEnqueueReadBuffer} from \ac{FPGA} to host. In a second step, it exchanges the buffer via \texttt{MPI\_Sendrecv} with the node that contains the neighboring \ac{FPGA}. In a last step, the buffers are written to the global memory of the \acp{FPGA} with the \texttt{clEnqueueWriteBuffer} OpenCL directive. These steps are executed for both directions in the ring and for all message sizes. The expected performance is limited by the required time to read ($\mathit{pcie\_read}_t$) and to write ($\mathit{pcie\_write}_t$) a message of the given size to the FPGA via PCIe, plus the time required to exchange the message between the nodes using MPI ($\mathit{mpi}_t$). All three steps need to be executed sequentially, so the expected bandwidth for a message size $L$ can be modelled with Equation~\ref{eq:b_eff_exe_time_pcie}. \begin{equation} b_{L} = \frac{2 \cdot L}{\mathit{pcie\_write}_t + \mathit{mpi}_t + \mathit{pcie\_read}_t} \label{eq:b_eff_exe_time_pcie} \end{equation} \subsubsection{Intel External Channels Implementation} \label{sec:intel_external_channels_implementation} The Intel-optimized implementation requires OpenCL kernel code and consists of two different kernel types: a \emph{send} kernel and a \emph{receive} kernel. During execution, they continuously send or receive data over two external channels of the width specified in \texttt{CHANNEL\_WIDTH}. A kernel replication always consists of both kernels since a \emph{send} kernel always requires a counterpart. Because the message size might exceed the width of the channels, the messages are further divided into data chunks that match the channel width. Thus, a message is streamed chunk-wise over two channels to the receiver in a pipelined loop. At kernel start, the \emph{send} kernel will generate a message chunk that is filled with bytes of the value $ld(m) \mod 256$. The message chunk will be used continuously for sending and will be stored in global memory after the last transmission. This allows verifying the correct transmission of the data chunk over the whole range of repetitions. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/network_topology_setup.pdf} \caption{Data exchange of two kernel pairs over the external channels. The kernel pairs are executed on two different FPGAs and communicate over the bi-directional external channels. The kernel pairs are connected over a internal channel to forward the received data to the send kernel for the next iteration.} \label{fig:b_eff_kernels} \end{figure} A schematic view of the channel connections for the kernel implementation is given in Figure~\ref{fig:b_eff_kernels}. The kernels are connected to another kernel pair on a different \ac{FPGA}. In the Figure, the kernels form a small ring over two FPGAs and the topology can be arbitrarily scaled by adding more FPGAs. The arrows describe the path of a single data chunk through the kernels. A message chunk will be repeatedly sent over the external channel until the sum of all sent chunks matches the desired message size. Messages are sent in parallel in both directions. After a complete message is sent, the message chunk is forwarded from the receive to the send kernel over the internal channel. Only then, the next message is sent now using the message chunk received over the internal channel. The message chunk is stored in a global memory buffer after the last message is exchanged and used for validation on the host side. A single send-receive kernel pair will use two external channels in both directions. \begin{table} \centering \caption{Characteristics of the serial channel IP of the BittWare 520N board taken from the specification \cite{bittware_bsp_doc}} \begin{tabular}{p{1.5cm}p{3.5cm}>{\raggedleft\arraybackslash}p{1cm}@{\hskip 1pt}p{1cm}} \toprule \textbf{Parameter} & \textbf{Description} & \multicolumn{2}{c}{\textbf{Value}} \\ \midrule $c_n$ & Number of external channels & 4 &\\ $c_l$ & Latency of a channel & 520 & \si{\nano\second} \\ $c_f$ & Frequency of a channel & 156.25 & \si{\mega\hertz} \\ $c_w$ & Width of a channel & 32 & \si{\byte} \\ \bottomrule \end{tabular} \label{tab:520n_external_channels} \end{table} The performance metric of the benchmark combines latency and the total bandwidth of the network. To model the performance, we need precise information about the latency and bandwidth of the external channels as they are given in Table~\ref{tab:520n_external_channels}. Every kernel replication can only make use of two external channels, which means that $c_n' = 2$ and the total number of external channels is utilized by using a replication count of 2. The execution time of a kernel pair for a given message size can then be modeled with Equation~\ref{eq:b_eff_exe_time} where $L$ is the used message size and $i$ the number of messages that are sent. \begin{equation} t_{L, i} = \frac{\lceil\frac{L}{c_n' \cdot c_w}\rceil \cdot i}{c_f} + i \cdot c_l \label{eq:b_eff_exe_time} \end{equation} For the bandwidth model, we insert the values for the IP core taken from Table~\ref{tab:520n_external_channels} which results in Equation~\ref{eq:b_eff_bandwidth}. \begin{equation} b_{L} = \frac{2 \cdot L}{\lceil\frac{L}{64B}\rceil \cdot 6.4ns + 520ns} \label{eq:b_eff_bandwidth} \end{equation} This equation models the bandwidth for a single send-receive kernel pair and is expected to scale linearly with the number of kernel pairs. \subsection{Parallel Matrix Transposition} The parallel matrix transposition (PTRANS) benchmark computes the solution of $C = B + A^T$ where $A,B,C \in \mathbb R^{n \times n}$. The matrix $A$ is transposed and added to another matrix $B$. The result is stored in matrix $C$. All matrices are divided into blocks, and the blocks are distributed over multiple \acp{FPGA} using a PQ distribution scheme shown in Figure~\ref{fig:ptrans_data_distribution}. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/pq_data_distribution.pdf} \caption{Diagonal distribution of the 16 blocks of a $4 \times 4$ block matrix on four FPGAs with $P=Q=2$. The original matrix is shown on the left. Colors equal the FPGA in which global memory the data block of the matrix will reside at the beginning of the calculation. On the right, the placement of the data on the different FPGAs is shown. The bold lines represent the borders of the memory of a single FPGA.} \label{fig:ptrans_data_distribution} \end{figure} \begin{table} \centering \caption{Configuration parameters of the PTRANS benchmark} \begin{tabular}{p{2.5cm}p{4.5cm}} \toprule \textbf{Parameter} & \textbf{Description} \\ \midrule \texttt{BLOCK\_SIZE} & Size of the matrix blocks that are buffered in local memory and also distributed between the FPGAs. \\ \rule{0pt}{3ex}% \texttt{CHANNEL\_WIDTH} & Width of the channels in data items. Together with the used data type, the width of the channel in bytes can be calculated. \\ \rule{0pt}{3ex}% \texttt{DATA\_TYPE} & Specifies the used data type for the calculation. \\ \bottomrule \end{tabular} \label{tab:ptrans_configuration_parameters} \end{table} \subsubsection{Base Implementation} The configuration parameters for the implementation are given in Table~\ref{tab:ptrans_configuration_parameters}. The number of kernel pairs can be defined with the \texttt{NUM\_REPLICATIONS} parameter and the block size that also defines the sizes of the local memory buffers can be set with \texttt{BLOCK\_SIZE}. Moreover, the width of the channel is defined by \texttt{CHANNEL\_WIDTH} and \texttt{DATA\_TYPE}. It should match the width of the used communication channel. In case of the base implementation, this is the width of the global memory interface. The implementation consists of a single OpenCL kernel that sequentially executes three pipelines for every matrix block. In the first pipeline, a block of matrix $A$ is read from global memory and written into a buffer. The second pipeline reads the block of $A$ transposed from the buffer, reads a block of $B$ from global memory, adds both blocks, and stores the result in an additional buffer. The content of this buffer is written back to global memory in the last pipeline. Every pipeline is reading or writing a single block of data from the global memory. This is a similar approach as it is used for the STREAM benchmark in the suite and leads to an efficient use of the global memory. Before the kernel can be executed, the matrix $A$ needs to be exchanged by the host ranks using \texttt{MPI\_Sendrecv}. With Equation~\ref{eq:ptrans_performance}, the expected execution time for a single matrix block is given. It consists of the time required to exchange the blocks via MPI and write them into the global memory of the \acp{FPGA} ($t_\mathit{MPI}$) and the execution time of the OpenCL kernel. The kernel execution time is based on the three pipelines that are executed sequentially, the block size $b$, the channel width in number of values $c_w$, and the clock frequency of the used channel $c_f$. Depending on the number of kernel replications, the \ac{FPGA} may be able to process multiple matrix blocks simultaneously without interference. \begin{equation} t_{\mathit{PTRANS}} = t_\mathit{MPI} + 3 \cdot \frac{b^2}{c_w} \cdot c_f \label{eq:ptrans_performance} \end{equation} For the verification of the data, the non-transposed blocks of matrix $A$ are exchanged by the hosts using MPI. Then, each host re-calculates the result using a CPU reference implementation. The reported error is the maximum residual error between the FPGA and CPU result. \subsubsection{Intel External Channels Implementation} The Intel-specific implementation comes with the restriction that $P\overset{!}{=}Q$. This allows to set up a static circuit-switched network between the pairs or \acp{FPGA} and exchange the matrix blocks without additional routing. The FPGA logic is implemented in two kernels per external channel, similar to the b\_eff benchmark. For this implementation, the width of the channel defined by \texttt{CHANNEL\_WIDTH} and \texttt{DATA\_TYPE} should match the width of the external channels. One of the kernels reads a block of $A$ into local memory. The size of this local memory buffer can be defined with \texttt{BLOCK\_SIZE}. The block of matrix $A$ is then read transposed from local memory and written into the external channel. Reading from global memory and writing to the external channel is implemented in a single pipeline, double buffering the local memory block. The second kernel will receive chunks of a transposed block of $A$, add a block of $B$ to it and store it in global memory. In consequence, no local memory is needed in this kernel. One major goal of this implementation is to continuously send and receive data over all available external channels to utilize the available network bandwidth, which is most likely the performance bottleneck. Nevertheless, the kernels may also suffer from low global memory bandwidth because they need to concurrently read and write to three different buffers for every kernel replication. This leads to a total required global memory bandwidth on a single \ac{FPGA} given in Equation~\ref{eq:ptrans_mem_bandwidth}. \begin{equation} b_{\mathit{global}} = 3 \cdot r \cdot c_w \cdot c_f \label{eq:ptrans_mem_bandwidth} \end{equation} where $r$ the number of external channels per FPGA (or number of kernel replications), and $c_f$ and $c_w$ the frequency and the width of an external channel as defined in Table~\ref{tab:520n_external_channels}. This means the required global memory bandwidth is three times higher than the network bandwidth to keep the benchmark network-bandwidth-bound. As a performance metric, the \ac{FLOP} per second are calculated. For the calculation it is assumed, that $n^2$ additions are required for the computation on matrices of width $n$. Considering the characteristics of the external channels of the used BittWare 520N boards, the maximum performance will be $p = i \cdot r \cdot 32B \cdot 156.25MHz$ for an sufficiently large matrix, where $i$ is the number of used \acp{FPGA}. Note, that the block size is not considered in this performance model. It is used to allow larger memory bursts from global memory, which are defined by the width of the block. This will lead to a higher efficiency of the global memory accesses, but since the performance model covers the case where the network bandwidth is the bottleneck, this parameter can be neglected. However, for very small block sizes, the efficiency of the global memory may be reduced to the point that it becomes the bottleneck. \subsection{High Performance Linpack} The High Performance Linpack benchmark solves a large equation system $A \cdot x = b$ for $x$, where $A \in \mathbb R^{n \times n}$ and $b,x \in \mathbb R^{n}$. This is done in two steps: First the matrix $A$ is decomposed into a lower matrix $L$ and an upper matix $U$. In a second step, these matrices are used to first solve $L \cdot y = b$ and finally $U \cdot x = y$ to get the result for the vector $x$. For the implementation of the benchmark on \ac{FPGA}, the rule set for the HPL-AI mixed-precision benchmark \cite{hpl_ai} was adapted, which defines $A$ to be a diagonally dominant matrix. Thus, the LU factorization does not require pivoting. In contrast to the original benchmark it is possible to choose between single-precision and double-precision floating-point values. Since the benchmark suite is designed to only measure the \ac{FPGA} performance, no additional iterative method is used to refine the result if a lower precision is used. Only the LU decomposition, which is the most compute-intensive step in this calculation, is executed on the \acp{FPGA}. The number of \acp{FLOP} for this step is defined to be $\frac{2 \cdot n^3}{3}$ for a matrix $A$ with width $n$ in contrast to $2 \cdot n^2$ for solving the equation systems for the LU-decomposed matrix. Only the performance of the LU factorization on the FPGA is reported. \begin{figure} \centering \includegraphics[width=0.7\linewidth]{figures/lu_iteration.pdf} \caption{In every iteration of the algorithm, a single block in the matrix is decomposed into a lower and upper matrix (green). The lower matrix is used to update all blocks on the right of this block (blue) and the upper matrix to update all blocks below this block (orange). The updated Top and Left blocks are then used to update all inner blocks (red) and the dark red blocks need to be updated before the next communication phase can start.} \label{fig:lu_iteration} \end{figure} \subsubsection{Base Implementation} The base implementation uses a blocked, right-looking variant for the LU factorization as it is described in \cite{blocked_lu_factorization}. Therefore, the matrix will be divided into sub-blocks with a width of $2^\mathit{BLOCK\_SIZE\_LOG}$ elements. The exact size of the blocks is defined over a configuration parameter. For the update of a single row and column of blocks, we need to perform four different operations. A single iteration of the blocked LU decomposition is shown in Figure~\ref{fig:lu_iteration}. In every iteration, the LU factorization for a diagonal block of the matrix is calculated which is marked green in the visualization. All grey-colored blocks on the left and top of this block are already updated in previous iterations and will require no further processing. This is why this approach is called right-looking, since we will always update the blocks on the right of the LU block. After the LU block is decomposed, the lower matrix block $L$ is used to update all blocks on the right of the LU block. Since they are the top-most blocks that still require an update, they are in the following called \emph{top blocks}. The upper matrix block $U$ is used to update all blocks below the current LU-block. These are the left-most blocks that require an update, so they are referred to as \emph{left blocks}. The left and top blocks again are used to update all inner blocks, which can efficiently be done using matrix multiplication. The design contains a separate kernel for each of the four operations. Additionally, a single iteration of the LU decomposition is split into two subsequent steps in the design. In the \emph{communication phase}, the LU, left, and top blocks are updated which also involves data exchange between kernels on the same \ac{FPGA} and between the \acp{FPGA}. In the \emph{update phase}, the exchanged data is used to update all inner blocks locally using matrix multiplication kernels. Both phases can overlap as shown by the timeline of kernel executions in Figure~\ref{fig:lu_execution_schedule_pcie} based on the matrix given in Figure~\ref{fig:lu_iteration}. The number of matrix multiplications required for a single iteration of the algorithm increases quadratically with the matrix size. No data dependency exists between the light red matrix multiplications and the operations of the next \emph{communication phase}, which allows overlapping of the two phases. For large matrices this means that the performance of the implementation is limited by the aggregated performance of the matrix multiplication kernels. During the \emph{communication phase}, matrix blocks are exchanged via the host using PCIe and MPI. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/lu_execution_schedule_pcie.pdf} \caption{Kernel executions over time for a single iteration of the LU decomposition in the base implementation. During the communication phase, data needs to be exchanged two times between FPGAs using MPI and PCIe. The matrix multiplication kernels are executed in the update phase. Communication and update phase of subsequent iterations can overlap, so communication latency can partially be hidden.} \label{fig:lu_execution_schedule_pcie} \end{figure} \subsubsection{Intel External Channels Implementation} Figure~\ref{fig:lu_communication_kernels} shows connections between the kernels used in the communication phase. For the execution over multiple FPGAs, the boards are arranged into a quadratic 2D torus of variable size using the point-to-point connections. Not all kernels need to be active on every \ac{FPGA} within a single iteration. Instead, data can also be received over the external channels if it is computed on another \ac{FPGA}. If the FPGA is in charge of calculating the LU block, the LU kernel is executed and the decomposed L and U blocks are forwarded row and column-wise to a network kernel. The network kernel forwards the data over the external channels to neighboring \acp{FPGA} in the torus. The four possible directions are used for different types of data as it is indicated by the red arrows. Moreover, the network kernel forwards the locally computed L and U block to the Left and Top kernel. The top and left kernel use the data to update a block with the L or U block and forward the updated block to the next network kernels. Here, the input data is selected either from the internal or external channels and data is forwarded over the external channels if required. Besides that, incoming data is stored in global memory buffers for later use in the update phase. By splitting the network communication into three kernels, it is possible to establish a cycle-free data path through the torus during the communication phase. This reduces the impact of pipeline and channel latencies during this phase. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/lu_communication_kernels.pdf} \caption{Data flow through the kernels of the communication phase on a single FPGA. The kernels are connected over internal channels. Between the calculation kernels, network kernels are used to select the correct input for the next kernel from the internal or external channels. The network kernels for the top and left direction will also store incoming matrix blocks as input for the matrix multiplication. The bold arrows represent the serial channels and their direction in the 2D torus.} \label{fig:lu_communication_kernels} \end{figure} During the transfer from the left kernel to the network kernel, the left blocks are transposed. This allows a simplified design of the matrix multiplication for the inner blocks since all input matrices can be processed row-wise. Figure~\ref{fig:lu_execution_schedule} shows a part of the execution of the kernels over time for the iteration given in Figure~\ref{fig:lu_iteration}. It can be seen that the LU kernel is only executed once per communication phase. The lower and upper matrices are buffered by the left and top kernel to allow the update of subsequent blocks. All network kernels are summarized under \emph{Network} in the graph. In the example, two matrix multiplication kernels are used, and the blocks a redistributed between the two replications. The next communication phase starts as soon as the first row and column of the inner blocks is updated, which is represented by the dark red blocks. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/lu_execution_schedule.pdf} \caption{Kernel executions over time for a single iteration of the LU decomposition. During the communication phase, the network kernels are active whereas during the update phase the matrix multiplication kernel is executed. Communication and update phase of subsequent iterations overlap.} \label{fig:lu_execution_schedule} \end{figure} A 2D torus is used to connect multiple \acp{FPGA} for the LU decomposition. Every \ac{FPGA} is programmed with the same bitstream and the host schedules the kernels in the required order and configuration. Matrix blocks are distributed between the \acp{FPGA} using a PQ-grid of the size of the torus. This allows balancing the load between the devices more evenly since the matrix will get smaller with every iteration of the algorithm. In Figure~\ref{fig:lu_torus_data_exchange} the active kernels and the data exchange between \acp{FPGA} in a $3 \times 3$ torus is shown for a global matrix size of more than 12 blocks so \ac{FPGA} has to update more than four blocks. In this case, only the \ac{FPGA} on the top left needs to execute all four compute kernels, but every FPGA will use its matrix multiplication kernel. \begin{figure} \centering \includegraphics[width=\linewidth]{figures/torus_data_forward.pdf} \caption{For the LU decomposition, the FPGAs use a 2D torus network topology to exchange data. This example shows the active kernels during a single iteration in a $3 \times 3$ torus. The black boxes are the FPGAs, and the colors within the boxes indicate the active kernels. The direction and type of data that is forwarded between the FPGAs is given by the arrows. \rev{In every iteration of the algorithm this communication scheme shifts one FPGA to the bottom-right in the torus.}} \label{fig:lu_torus_data_exchange} \end{figure} The base implementation of the HPL benchmark uses a similar two-leveled blocked approach than the GEMM benchmark described in \cite{hpcc_fpga}. Thus, it uses two parameters to specify the block sizes of the local memory buffers and of the compute units as described in Table~\ref{tab:hpl_configuration_parameters}. Additionally, it is possible to specify the data type and specify the number of matrix multiplication kernels using the \texttt{NUM\_REPLICATIONS} parameter. The two-leveled blocked approach is also used for the communication kernels and all kernels use the same first level block sizes. A main difference is the parallelism in the computation between communication kernels and matrix multiplication. The matrix multiplication kernels unroll the computation in three dimensions in the second level whereas the communication only use a two-dimensional unrolling. This means the parallel calculation increase cubically with the chosen register block size for the matrix multiplications and only quadratically for the communication kernels. It would also be possible to scale the second level blocks differently between the two kernel types. This has to be considered in further optimizations steps. \begin{table} \centering \caption{Configuration parameters of the LINPACK benchmark} \begin{tabular}{p{3cm}p{4.5cm}} \toprule \textbf{Parameter} & \textbf{Description} \\ \midrule \texttt{LOCAL\_MEM\_BLOCK\_LOG} & Logarithm of the size of the matrix blocks that are buffered in local memory and also distributed between the FPGAs. \\ \rule{0pt}{3ex}% \texttt{REGISTER\_BLOCK\_LOG} & Logarithm of the size of the second level matrix blocks. The kernels contain completely unrolled logic to start the computation of such a sub-block every clock cycle. \\ \rule{0pt}{3ex}% \texttt{DATA\_TYPE} & Specifies the used data type for the calculation. \\ \bottomrule \end{tabular} \label{tab:hpl_configuration_parameters} \end{table} Only the LU factorization of matrix $A$ is calculated on the FPGAs. After this step, the equation system is solved using a distributed CPU reference implementation among all MPI ranks. The input matrix was generated such that the resulting vector is a vector of all ones. The reported error is the normalized maximum residual error calculated with $\frac{||x||}{n \cdot ||b|| \cdot \epsilon}$ where $n$ is the width of matrix $A$ and $\epsilon$ the machine epsilon. \subsection{Extend Existing Benchmarks for Multi-FPGA Execution} In addition to the new benchmarks proposed in this paper, we also extend the existing benchmarks of our previous work \cite{hpcc_fpga} for the execution in a multi-\ac{FPGA} environment. An essential configuration parameter for all benchmarks is the specification of kernel replications \texttt{NUM\_REPLICATIONS}. These kernel replications are kernels with the same or very similar functionality to allow a higher utilization of the \ac{FPGA} resources. The input data is then distributed between the replicated kernels such that every kernel works on its own data set. Especially for devices with \ac{HBM2} this step is crucial to make use of the high number of memory banks and the high aggregated bandwidth. So the existing implementations in HPCC FPGA already handle the memory banks on a single \ac{FPGA} like a distributed memory system. As a result, changes on the \ac{OpenCL} kernels are not required for most of the legacy benchmarks, and the extensions focus on the host codes to trigger the distributed execution and support the validation and result collection over multiple compute nodes using \ac{MPI}. The RandomAccess benchmark was not well scalable because it could at best update a single data item per clock cycle even when scaled over multiple \acp{FPGA}. This is limited by the way the pseudo-random numbers for the address calculation are generated. We now allow the generation of multiple pseudo-random numbers per clock cycle to overcome this limitation by replicating the \ac{RNG}. This also changed the configuration parameters of the benchmark as given in Table~\ref{tab:ra_configuration_parameters}. A single replication of the improved RandomAccess kernel is given in Figure~\ref{fig:ra_shift_register}. The \acp{RNG} are initialized with different seeds to generate a sub-part of the random-number sequence. In consequence, the same random number as with the old version are generated, only the order of updates may vary. Every clock cylce, the \ac{RNG} outputs a new random number. This number is placed into a shift register, if two conditions hold: \begin{enumerate} \item The buffer address derived from the random number is in range of the kernel replication. \item The shift register does not already contain a valid random number at the position where it should be inserted. \end{enumerate} In the latter case, the \ac{RNG} will stall until the random number can be placed into the shift register. So in other terms, the produced random numbers are sequentialzed by the shift register for the input into the actual update logic. This approach increases the probability, that the update logic processes a valid address for high numbers of kernel replications. Since scaling over multiple \acp{FPGA} corresponds to increasing the number of kernel replications, this does also improve the performance in multi-\ac{FPGA} execution. \begin{table} \centering \caption{Configuration parameters of the RandomAccess benchmark} \begin{tabular}{p{4cm}p{3.5cm}} \toprule \textbf{Parameter} & \textbf{Description} \\ \midrule \texttt{HPCC\_FPGA\_RA\_DEVICE\_ BUFFER\_SIZE\_LOG} & Logarithm of the size of the data buffer that is randomly updated in number of values.\\ \rule{0pt}{3ex}% \texttt{HPCC\_FPGA\_RA\_RNG\_COUNT\_LOG} & Logarithm of the number of \acp{RNG} that are created per kernel replication.\\ \rule{0pt}{3ex}% \texttt{HPCC\_FPGA\_RA\_RNG\_DISTANCE} & Distance between \acp{RNG} in the shift register.\\ \bottomrule \end{tabular} \label{tab:ra_configuration_parameters} \end{table} \begin{figure} \centering \includegraphics[width=\linewidth]{figures/RA_shift-register.pdf} \caption{RandomAccess shift register used to connect the different \acp{RNG}.} \label{fig:ra_shift_register} \end{figure} \subsection{Evaluation Setup and Synthesis Results} For the evaluation of the benchmarks we used version 0.5.1 of the benchmark suite \cite{hpcc_fpga_release} and we made all artifacts and code modifications for additional experiments publicly available \cite{hpcc_fpga_evaluation}. We synthesized and executed the benchmarks on two multi-\ac{FPGA} systems: The Noctua system of \ac{PC$^2$} at Paderborn University and the Xilinx FPGA evaluation system of the Systems Group at ETH Zurich. The Noctua system uses \emph{Nallatech/BittWare 520N} boards equipped with Intel Stratix 10 GX2800 \acp{FPGA}, where every node is a two-socket system equipped with Intel Xeon Gold 6148 CPUs, \SI{192}{\giga\byte} of DDR4-2666 main memory, and two \acp{FPGA} connected via x8 PCIe 3.0. Moreover, the nodes in the cluster communicate over a hybrid network: The CPUs use an Intel Omni Path network with \SI{100}{\giga\bit\per\second} per port, whereas the \acp{FPGA} can exchange data over the four serial interfaces with up to \SI{40}{\giga\bit\per\second} per port. The serial interfaces are connected to a CALIENT S320 Optical Circuit Switch that allows the configuration of arbitrary full-duplex point-to-point connections between the serial interfaces of the \acp{FPGA}. This functionality allows creating the desired network topology and is used in the following to establish connections between up to 26 \acp{FPGA} to execute the optimized versions of the benchmarks. The network topology is set up before running the benchmarks and stays unchanged during execution. \ac{BSP} version 20.4.0 and Intel OpenCL \ac{SDK} for FPGA version 21.2.0 are used to synthesize all benchmark kernels. This \ac{BSP} version comes in two different sub-versions with and without support for the external channels. All benchmarks were synthesized with the \emph{HPC} sub-version which offers no support for communication over the external channels. This \ac{BSP} requires slightly fewer resources than the \emph{MAX} sub-version with external channel support. Only the optimized versions of b\_eff, PTRANS, and LINPACK are synthesized with the \emph{MAX} sub-version. The host codes are compiled with GCC 8.3.0 and Intel MPI 2019 Update 6 Build 20191024. Configuration and generation of the build scripts are done using CMake 3.15.3. Additionally, the benchmarks are synthesized and executed on \emph{Xilinx Alveo U280} boards. The Xilinx FPGA evaluation system contains four of these boards. As \ac{SDK}, Vitis 2020.2 is used with the shell \emph{xilinx\_u280\_xdma\_201920\_3} and XRT 2.9. The host codes are compiled with GCC 7.5.0 and OpenMPI 2.1.1. Each FPGA is controlled by an Intel(R) Xeon(R) Gold 6234 CPU with \SI{108}{\giga\byte} of main memory. All benchmark kernels are designed to be independent of the number of used \acp{FPGA}, so only a single synthesis for every benchmark and FPGA board is required for the evaluation. With configuration parameters, it is possible to improve resource utilization and performance of the benchmark kernels for a specific \ac{FPGA} board before synthesis. For the benchmarks STREAM, FFT, and GEMM, these configuration parameters were discussed in more detail in \cite{hpcc_fpga}. Table~\ref{tab:used_parameters} contains the used configurations for each benchmark. The configuration parameters are chosen to better utilize performance-relevant resources on the \ac{FPGA}. In Table~\ref{tab:resource_usage} the resource usage of the synthesized benchmark kernels is given. Our updated scalable implementation of the RandomAccess benchmark now requires additional logic and BRAMs to implement the \acp{RNG}. We have chosen the number of \acp{RNG} in the configuration to be the next larger power of two of the used \acp{FPGA}. This increaes the probability, that a valid number can be processed in every clock cycle by every FPGA. Further increasing the number of \acp{RNG} may lead to lower clock frequencies, wich will also have an impact on performance. With the recent SDK version we were able to synthesize the GEMM benchmark with a much higher clock frequency for the BittWare 520N, which promises a large performance improvement. For the b\_eff benchmark, only a single bitstream is synthesized. For the base implementations, no bitstream is required since the data transfer is solely handled by the host. Also resource consumption is not an issue with this synthetic benchmark because the performance is mainly limited by the network bandwidth and latency. PTRANS requires BRAM buffers that are used to block-wise transpose the matrix and store intermediate results. A large block size will benefit large memory bursts but it is also important to achieve a clock frequency close to 300~MHz to make best use of the memory bandwith. For LINPACK it is -- similar to GEMM -- important to maximize the number of used DSPs for matrix multiplications. In addition, mainly some extra BRAM is required to store the matrix blocks for the kernels of the communication phase. As a result, the resource utilization is very similar to GEMM. A significant difference is visible for the Alveo U280, where only 69\% of the DSPs can be utilized. We were not able to fit the communication kernels and three matrix multiplication kernels on the FPGA, so we had to reduce the number of matrix multiplication kernels. Since we are not able to scale the matrix multiplication kernels individually, this lead to a onsiderable amount of unused resources. The difference in DSPs between the base and optimized implementation for the BittWare 520N is caused by the way, the multiplication of the $8 \times 8$ matrices in registers is implemented. In case of the \ac{IEC} version, only multiply-adds are used consuming 512 DSPs in total per replication. In the base implementation, the compiler created the same matrix multiplication from 64 dot-products of size 8 followed by 64 additions. This slightly increases the DSP usage to 576 DSPs per replication but considerably reduces the logic and BRAM usage as it can be seen in the resource utilization. Besides the two bitstreams for the baseline and one for the vendor-specific implementation, we also synthesized LINPACK with a block size of 256 elements for the 520N. This is the same block size that is used on the U280 and allows a better comparison of the performance results of both \ac{FPGA} boards. The configuration requires considerably lesser logic and BRAM compared to the version wih 512 element block width and achieves a higher clock frequency. \begin{table*} \centering \caption{Synthesis configurations of all benchmarks} \begin{tabular}{p{2cm}p{5.5cm}>{\raggedleft\arraybackslash}p{1cm}>{\raggedleft\arraybackslash}p{1cm}>{\raggedleft\arraybackslash}p{1cm}>{\raggedleft\arraybackslash}p{1cm}} \toprule \textbf{Benchmark} & \textbf{Parameter} & \textbf{520N IEC} & \textbf{520N PCIe} & \textbf{U280 PCIe}\\ \midrule \multirow{5}{*}{STREAM} &\texttt{NUM\_REPLICATIONS} & 4 & 4 & 2 \\ &\texttt{DATA\_TYPE} & float & float & float\\ &\texttt{GLOBAL\_MEM\_UNROLL} & 1 & 1& 1\\ &\texttt{VECTOR\_COUNT} & 16 & 16 & 16\\ &\texttt{DEVICE\_BUFFER\_SIZE} & 32,768 & 32,768 & 16,384\\ \midrule \multirow{4}{*}{RandomAccess} & \texttt{NUM\_REPLICATIONS} & 4 & 4 & 2\\ &\texttt{HPCC\_FPGA\_RA\_DEVICE\_BUFFER\_SIZE\_LOG} & 0 & 0 & 10\\ &\texttt{HPCC\_FPGA\_RA\_RNG\_COUNT\_LOG} & 5 & 5 & 3\\ &\texttt{HPCC\_FPGA\_RA\_RNG\_DISTANCE} & 5 & 5 & 1\\ \midrule \multirow{2}{*}{FFT} &\texttt{NUM\_REPLICATIONS} & 2 & 2 & 1\\ & \texttt{LOG\_FFT\_SIZE} & 17 & 17 & 9 \\ \midrule \multirow{5}{*}{GEMM} &\texttt{NUM\_REPLICATIONS} & 5 & 5 & 3 \\ &\texttt{DATA\_TYPE} & float & float & float\\ &\texttt{GLOBAL\_MEM\_UNROLL} & 8 & 8& 8 \\ &\texttt{BLOCK\_SIZE} & 512 & 512 & 256 \\ &\texttt{GEMM\_SIZE} & 8 & 8 & 8\\ \midrule \multirow{2}{*}{b\_eff} &\texttt{NUM\_REPLICATIONS} & 2 & \multicolumn{2}{c}{only host code required} \\ &\texttt{CHANNEL\_WIDTH} & 8 & \multicolumn{2}{c}{only host code required} \\ \midrule \multirow{4}{*}{PTRANS} &\texttt{NUM\_REPLICATIONS} & 4 & 4 & 2\\ &\texttt{DATA\_TYPE} & float & float & float\\ &\texttt{CHANNEL\_WIDTH} & 8 & 16 & 16\\ &\texttt{BLOCK\_SIZE} & 512 & 512 & 256 \\ \midrule \multirow{4}{*}{LINPACK} &\texttt{NUM\_REPLICATIONS} & 5 & 5 & 2\\ &\texttt{DATA\_TYPE} & float & float & float\\ &\texttt{LOCAL\_MEM\_BLOCK\_LOG} & 9 & 9 & 8\\ &\texttt{REGISTER\_BLOCK\_LOG} & 3 & 3 & 3\\ \bottomrule \end{tabular} \label{tab:used_parameters} \end{table*} \begin{table*} \centering \caption{Resource usage of the synthesized benchmarks} \begin{tabular}{p{2cm}p{1cm}>{\raggedleft\arraybackslash}p{1cm}@{\hskip 3pt}p{1cm}>{\raggedleft\arraybackslash}p{1cm}@{\hskip 3pt}p{1cm}>{\raggedleft\arraybackslash}p{1cm}@{\hskip 3pt}p{1cm}p{1cm}>{\raggedleft\arraybackslash}p{1cm}} \toprule \textbf{Benchmark} & \textbf{Device} & \multicolumn{2}{c}{\textbf{Logic}} & \multicolumn{2}{c}{\textbf{BRAM}} & \multicolumn{2}{c}{\textbf{DSPs}} & \textbf{Freq. [MHz]} & \textbf{Comp. Time [h]} \\ \midrule \multirow{2}{*}{STREAM} & 520N & 178,268 & (19\%) & 3,926 & (33\%) & 128 & (2\%) & 341.67 & 2.64\\ & U280 & 188,124 & (14\%) & 854 & (42\%) & 170 & (2\%) & 300.00 & 2.44\\ \midrule \multirow{2}{*}{RandomAccess} & 520N & 222,405 & (24\%) & 602 & (5\%) & 14 & (<1\%) & 325.00 & 3.50\\ & U280 & 184,888 & (14\%) & 350 & (17\%) & 24 & (<1\%) & 300.00 & 2.20\\ \midrule \multirow{2}{*}{FFT} & 520N & 280,105 & (30\%) & 1,811 & (15\%) & 1,560 & (27\%) & 400.00 & 4.10\\ &U280 & 375,069 & (29\%) & 342 & (17\%) & 682 & (8\%) & 286.00 & 6.94\\ \midrule \multirow{2}{*}{GEMM} & 520N & 310,564 & (33\%) & 8,321 & (71\%) & 3,318 & (58\%) & 272.50 & 9.87\\ & U280 & 659,200 & (51\%) & 1,139 & (57\%) & 7,714 & (85\%) & 186.00 & 12.25\\ \midrule \multirow{3}{*}{b\_eff} & 520N$^2$ & 173,010& (19\%) & 512 & (4\%) & 0& (0\%) & 290.63 & 2.45\\ & 520N$^1$ & \multicolumn{8}{c}{only host code required}\\ & U280$^1$ & \multicolumn{8}{c}{only host code required}\\ \midrule \multirow{3}{*}{PTRANS} & 520N$^2$ & 242,232 & (26\%) & 4,756 & (41\%) & 68 & (1\%) & 281.25 & 3.64\\ & 520N$^1$ & 233,317 & (25\%) & 4,662 & (40\%) & 162 & (3\%) & 380.00 & 3.62\\ & U280$^1$ & 283,028 & (22\%) & 598 & (30\%) & 96 & (1\%) & 283.00 & 4.07\\ \midrule \multirow{3}{*}{LINPACK} & 520N$^2$& 361,377 & (39\%) & 8,326 & (71\%) & 2,809 & (49\%) & 225.00 & 10.40\\ & 520N$^1$& 303,471 & (33\%) & 8,245 & (70\%) & 3,185 & (55\%) & 233.34 & 9.42\\ & 520N$^{1,3}$& 276,546 & (30\%) & 2,587 & (22\%) & 3,185 & (55\%) & 280.00 & 6.08\\ & U280$^1$& 663,418 & (51\%) & 994 & (49\%) & 6,201 & (69\%) & 156.00 & 12.10\\ \bottomrule \multicolumn{10}{r}{$^1$communication via MPI and PCIe using the host network}\\ \multicolumn{10}{r}{$^2$communication via Intel external channels (IEC) OpenCL extension}\\ \multicolumn{10}{r}{$^3$version with a reduced block size of 256 elements}\\ \end{tabular} \label{tab:resource_usage} \end{table*} \subsection{Evaluation of the Effective Bandwidth and PTRANS} The \emph{b\_eff} benchmark does not only report the derived metric \emph{effective bandwidth} but also the achieved bandwidth for all tested message sizes, which range from a single byte to 1~MB. A new message is only sent after the current message is received by the neighbor node. The base implementation of the b\_eff benchmark reads the data from the \ac{FPGA} board to the host using an OpenCL call, exchange the data between the host CPUs using the \texttt{MPI\_Sendrecv} method, and write the data back to the \ac{FPGA} using OpenCL. This means, in contrast to the optimized \ac{IEC} implementation, no OpenCL device code is required for this benchmark to work. The measured total bandwidth over the message sizes is given in Figure~\ref{fig:beff_message_sizes_mpi} for two \acp{FPGA} or CPU nodes respectively. We do not show the MPI-only performance for the Xilinx system in this plot since it heavily overlaps with the measurements for the base implementations. The maximum theoretical bandwidths for PCIe, MPI via the Intel Omni Path 100Gbps interconnect, and \ac{IEC} are given by the black dashed lines in the plot. For the base implementations, the bandwidth remains below \SI{5}{\giga\byte\per\second} on both devices although the theoretical bandwidth of PCIe and MPI are both much higher. The bandwidth gets limited by the additional copy operations that are required to get the data from FPGA to CPU and back. This leads to a theoretic peak performance of \SI{5.9}{\giga\byte\per\second} for this approach. However, the measurements with the MPI-only implementation of the benchmark show, that the maximum message size of \SI{1}{\mega\byte} is not sufficiently large to utilize the MPI peak performance on Noctua. The optimized \ac{IEC} approach shows maximum bandwidths close to the theoretical peak for \SI{1}{\mega\byte} message sizes. Also the measurements closely correlate to the model described in Section~\ref{sec:intel_external_channels_implementation}. The linear scaling behavior for the derived \emph{effective bandwidth} metric is visualized for all for implementations in Figure~\ref{fig:beff_effective_bw}. All implementations show nearly perfect scaling with the available network bandwidth as it is indicated by the extrapolation lines for each device. Especially for the MPI-only and the MPI + PCIe version, the performance on a single node is considerably higher than the available network bandwidth because in these cases the data will be transferred between the ranks using shared memory. We also observe a huge difference in the effective bandwidth between the two MPI versions of Noctua and the Xilinx system. These measurements have to be kept in mind when comparing the results of the base implementation on the two systems, since the huge difference in MPI performance will also have an impact on the PCIe + MPI performance. The ability to add additional optimized implementations of the benchmark kernels allows to generate comparable results not only limited to \acp{FPGA} but also for CPU or other accelerators. This only requires minor changes in the existing code base and large amounts of the code can be reused including handling of input parameters, input data generation and validation, calculation of derived metrics, and printing of performance summaries. \begin{figure} \includegraphics[width=\linewidth]{figures/beff_bw_message_sizes_mpi.pdf} \caption{The aggregated bandwidth over different message sizes measured by the b\_eff benchmark over two CPUs or FPGAs. Next to the measurements, the maximum performance for the communication between FPGAs, CPUs, and between FPGAs and CPUs via PCIe.} \label{fig:beff_message_sizes_mpi} \end{figure} \begin{figure} \includegraphics[width=\linewidth]{figures/beff_effective_bw.pdf} \caption{The measured effective bandwidth over the number of used FPGAs and CPUs. A logarithmic scale is used for the ring size and the measured bandwidth. The colored lines represent the perfect scaling based on measured effective bandwidth over two FPGAs or CPU nodes.} \label{fig:beff_effective_bw} \end{figure} For the matrix transposition, the blocks of a matrix are distributed among the \acp{FPGA} in a PQ distribution where $P = Q$. A matrix of 32,768 elements is transposed using strong and weak scaling. The resulting speedups for the different \acp{FPGA} is given in Figure~\ref{fig:ptrans_performance}. In the strong scaling experiment, the base implementation on the BittWare 520N shows a better scaling behavior as the optimized version using \ac{IEC}. This is because the base implementation is mainly bottlenecked by the PCIe bandwidth for the exchange of the matrices. In contrast to that, the optimized version shows a significant reduction of the speedup for larger number of \acp{FPGA}. This is caused by the compute pipeline on the \acp{FPGA} which can not be fully utilized with the smaller matrix sizes. In the weak scaling experiment, the matrix size per \ac{FPGA} stays the same and the implementation achieves optimal speedup for up to 25 \acp{FPGA}. The base implementation shows no significant differences for both \acp{FPGA} in strong and weak scaling. On the Xilinx Alveo U280, the base implementation does not scale well. This is related to the low \ac{FPGA}-to-\ac{FPGA} bandwidth that we also measured in the b\_eff benchmark. This means that this difference is caused by the comparably low MPI performance on the Xilinx system and not by the \acp{FPGA}. \begin{figure*} \includegraphics[width=0.65\linewidth]{figures/ptrans_scaling_norm.pdf} \caption{Speedup of the PTRANS benchmark executed with a quadratic matrix of 16,384 elements over up to 25 FPGAs in a weak and strong scaling scenario.} \label{fig:ptrans_performance} \end{figure*} \subsection{Evaluation of HPL} In a first experiment, we measure the performance on a single \ac{FPGA} for different matrix sizes of up to 20,480 elements. The performance for four bitstreams on the two different systems are given in Figure~\ref{fig:hpl_scaling_single_fpga}. To allow an easier comparison of the efficiency of the design on the different platforms, the performance was normalized to a kernel frequency of \SI{100}{\mega\hertz} and a single kernel replication. So the nomalized performance for a given matrix size should be very similar on the different platforms. For small matrix sizes, the communication phase can not be overlapped with the computation phase. Only for larger sizes of the matrix, both phases overlap for most of the computation time and the performance converges to the matrix multiplication performance. Still, significant differences between the different bitstreams can be observed. They are mainly caused by the chosen benchmark configuration parameters and compiler flags. When comparing the base version and the vendor-specific version with Intel external channels (IEC) used on the BittWare 520N board, the base version using PCIe for communication shows lower performance, although the same configuration parameters are used. The base version of the benchmark failed to synthesize with memory interleaving because additional \acp{LSU} are used for the communication and increase the complexity of the memory system. Since only a single buffer is used to store matrix $A$, this effectively reduces the global memory bandwidth and stalls of the matrix multiplication kernels increase. On the Xilinx Alveo U280 board the largest block size that fits on the device is 256 elements in contrast to 512 element blocks for the 520N board. The reduced block size results in an overlap of communication and computation for smaller matrix sizes but also reduces the peak performance because the utilization of the matrix multiplication pipeline decreases. For comparison, we synthesized a bitstream for the 520N with a block size of 256. It shows a similar scaling behavior with regards to the matrix size but shows a slightly lower normalized peak performance. The bitstream for the 520N achieves a nearly 80~\% higher frequency which also increases the memory bandwidth utilization and leads to more frequent pipeline stalls, which eventually leads to a lower nomalized performance. \begin{figure} \includegraphics[width=\linewidth]{figures/hpl_scaling_norm.pdf} \caption{Normalized performance of the HPL bitstreams on the target FPGAs for different matrix sizes. The base versions of the benchmark are marked with PCIe, referring to the path of communication. For small matrices, the design is limited by the communication latency until it can be efficiently hidden by matrix multiplications. Moreover, an additional execution for the BittWare 520N with a block size of 256 is given for comparison with the Xilinx Alveo U280.} \label{fig:hpl_scaling_single_fpga} \end{figure} Based on the measurements done with a single \ac{FPGA}, we set the matrix size for the multi-\ac{FPGA} experiments to 24,576 elements, since all bitstreams will be close the their peak performance for this size. We use this matrix size as a base for a weak scaling experiment, where the matrix size increases with the width of the \ac{FPGA} torus so the matrix size on a single \ac{FPGA} remains constant. Additionally, we execute a strong scaling experiment, where the global matrix size remains constant while increasing the torus size. The measurement results for the weak scaling experiment are given in Figue~\ref{fig:hpl_torus_speedup_weak}. It can be observed, that all three implementations of the benchmark show a close to optimal scaling for up to 25 \acp{FPGA}. Considering the differences in the network bandwidth that had an effect on the PTRANS results, this also means, that the benchmark implementation is compute bound on all \acp{FPGA}. The results of the strong scaling experiment are given in Figue~\ref{fig:hpl_torus_speedup_strong}. Both benchmarks show a much lower increase in performance for larger torus sizes. Based on the data of our single FPGA scaling experiment shown in Figure~\ref{fig:hpl_scaling_single_fpga}, we created an extrapolation model for the strong scaling experiment. It shows that performance per FPGA is tighlty coupled to the size of the local matrices on the \acp{FPGA}. The extrapolation for the Xilinx Alveo U280 shows a better speedup in this strong scaling scenario because of the smaller block sizes. With this very simple approach it is already possible to model the performance depending on the total matrix size and the number of \acp{FPGA} with high accuracy. The strong scaling experiment shows that the overall performance in the torus is tightly coupled to the input size on a single device for all implementations. \begin{figure} \includegraphics[width=\linewidth]{figures/hpl_torus_speedup_weak.pdf} \caption{Speedup of HPL with a matrix width of 24,576 elements over multiple FPGAs in a weak scaling scenario.} \label{fig:hpl_torus_speedup_weak} \end{figure} \begin{figure} \includegraphics[width=\linewidth]{figures/hpl_torus_speedup_strong.pdf} \caption{Speedup of HPL with a matrix width of 24,576 elements over multiple FPGAs in a strong scaling scenario. Extrapolation models for the three different bitstreams are given as colored lines. They are based on the measured single-FPGA performance per matrix size in Figure~\ref{fig:hpl_scaling_single_fpga}.} \label{fig:hpl_torus_speedup_strong} \end{figure} The HPL implementation achieves a lower performance per FPGA than the existing GEMM benchmark, although both get their performance from matrix multiplication. Also, the configuration parameters are chosen similarly for both benchmarks, which results in a similar expected performance. The main difference in performance is caused by the different clock frequencies of the designs given in Table~\ref{tab:resource_usage}. The tools achieve higher clock frequencies for the base implementation of the GEMM benchmark because the kernels of the HPL communication phase consume additional resources. Also, the matrix multiplications work on smaller matrix sizes of just a single block, which reduces the reuse of data in local memory. Our HPL implementation achieves 14.3~TFLOP/s for the base version and 20.8~TFLOP/s for the optimized version using \ac{IEC} on 25 BittWare 520N \acp{FPGA}. The scaling experiments show, that the two major reasons for the performance differences rely on the achieved frequencies and a more efficient use of the global memory. Although the benchmark is computation-bound, our optimized version using \ac{IEC} still achieves higher performance by reducing the number of \acp{LSU}. This allows further global memory optimizations and higher kernel frequencies that improve the performance. \subsection{Evaluation of the Existing Benchmarks} \label{sec:existing_bms_eval} For STREAM, FFT, and GEMM, the design did not change compared to the previous work. All except RandomAccess are executed embarrassingly parallel, so MPI is only used to exchange measurement and validation results. In the case of RandomAccess, the data array is distributed among the \acp{FPGA}. This way, only scaling to a power of two is allowed since the total size of the data array must be a power of two. \begin{figure*} \begin{subfigure}{0.49\linewidth} \centering % \includegraphics[width=\linewidth]{figures/stream_scaling_performance.pdf} \caption{STREAM Triad with 4 GB arrays per FPGA} \label{fig:stream_scaling} \end{subfigure} \begin{subfigure}{0.49\linewidth} \centering % \includegraphics[width=\linewidth]{figures/ra_scaling_performance.pdf} \caption{RandomAccess with 8 GB of data per FPGA} \label{fig:ra_scaling} \end{subfigure} \begin{subfigure}{0.49\linewidth} \centering % \includegraphics[width=\linewidth]{figures/fft_scaling_performance.pdf} \caption{Batches of 4096 1d FFTs of size $2^{17}$ per FPGA} \label{fig:fft_scaling} \end{subfigure} \begin{subfigure}{0.49\linewidth} \centering % \includegraphics[width=\linewidth]{figures/gemm_scaling_performance.pdf} \caption{GEMM with a matrix width of 45 blocks per FPGA} \label{fig:gemm_scaling} \end{subfigure} \caption{Normalized performance of the four benchmarks without inter-FPGA communication. Data is normalized to a single memory bank and a frequency of 100~MHz clock for STREAM, GEMM, and RandomAccess, to allow a better comparison for the two FPGA boards.} \label{fig:basic_results} \end{figure*} We executed the four benchmarks on up to 26 \acp{FPGA} to show their scaling performance. 4~GB arrays are used in STREAM, FFT calculates on $4,096$ 1d FFTs of $2^{17}$ or $2^9$ complex numbers, and GEMM uses matrices with the width of $23,040$ elements per \ac{FPGA}. RandomAccess is executed in a strong scaling scenario with 8~GB data array. The normalized measurement results are given in Figure~\ref{fig:basic_results}. For STREAM, the measurements are normalized to a single memory bank with a theoretical bandwidth of 19.2~GB/s. The benchmark shows a similar scaling behavior on both devices. For GEMM, the results are normalized to a single kernel replication running at 100~MHz with with an $8 \times 8 \times 8$ matrix multiplication in registers. This leads to a maximum theoretical performance of 102.4~GFLOP/s times the number of used \acp{FPGA}. Also here, the base implementation shows a performance close to the theoretical peak on both devices. Because of the comarably high clock frequency of our synthesized design, we achieved more than 1.2~TFLOP/s per FPGA on the BittWare 520N. Although we did not change the benchmark code, we were not able to execute the FFT benchmark on the Alveo U280. The benchmark required internal channels or pipes between the kernels to forward data but support for pipes in OpenCL kernel code was removed with XRT 2.9. This still allows synthesis of the benchmark, but no execution. On the BittWare 520N, the benchmark scaled lineraly. For FFT, we show the absolute measured performance. The RandomAccess results were also normalized to the number of memory banks and a kernel frequency of 100~MHz. Because an update of a value requires one read and one write to the memory bank, two clock cycles are required per update, which results in a theoretical peak performance of 50~MUOP/s per FPGA. On the BittWare 520N, the base implementation gets close to this theoretical peak whereas on the Alveo U280, we only get roughly half of this performance. One reason for that is the difference in the configuration: For the Alveo U280 we need a small buffer to read and write multiple values subsequentially which partially hides the lantency of memory accesses and increases performance. As a trade-off, we see an increased error rate, because we may overwrite values, that are already in the buffer. Still, this approach requires iteration between two different pipelines that fill and empty the buffer. Since these pipelines have a considerable latency because of memory accesses, this will also reduce the performance because the pipelines have to be emptied frequently. If it would be possible to ignore the dependency between reads and writes, the single-pipeline approach could be used as it is done for the BittWare 520N. \section{Introduction} \label{sec:introduction} \input{introduction} \section{Parallel Implementation of HPC Challenge Benchmarks for FPGA} \label{sec:hpcc-benchmark} \input{benchmark_description} \section{Benchmark Execution and Evaluation} \label{sec:evaluation} \input{evaluation} \section{Related Work} \label{sec:related_work} \input{related_work} \section{Conclusion} \label{sec:conclusion} \input{conclusion} \ifopen \begin{acks} The authors gratefully acknowledge the support of this project by computing time provided by the Paderborn Center for Parallel Computing (PC2) and the Systems Group at ETH Zurich as well as the Xilinx Adaptive Compute Clusters (XACC) program for access to their Xilinx FPGA evaluation system. This work is partially funded by the German Research Foundation (DFG) within the Collaborative Research Center "On-The-Fly Computing" (SFB901), the project "Performance and Efficiency in HPC with Custom Computing" (PerficienCC), grant agreement No PL 595/2-1, and by the Federal Ministry of Education and Research (BMBF) and the state of North Rhine-Westphalia as part of the NHR Program. \end{acks} \fi \newpage \bibliographystyle{bibliography/ACM-Reference-Format}
{'timestamp': '2022-03-01T02:58:29', 'yymm': '2202', 'arxiv_id': '2202.13995', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13995'}
arxiv
\section{Introduction} Translating natural language program descriptions to actual code is meant to help programmers to ease writing reliable code efficiently by means of a set of advanced code completion mechanisms. There are mainly two classes of methods for obtaining code corresponding to a query expressed in natural language. The first one is code retrieval, which consists of searching and retrieving an appropriate code snippet from a code database. The second one is code generation, where the goal is to generate code fragments from a natural language description, generating potentially previously unseen code. In this work, we are interested in Python code generation. Code generation features a mismatch between an ambiguous and noisy natural language input and the structured nature of the generated code. Although Python's vocabulary has a finite number of keywords, the set of values that can be assigned to a variable is infinite and constitutes one of the issues in predicting code corresponding to natural language. Like many other NLP tasks, current architectures for natural language to code generally take advantage of pre-trained language models such as BERT \cite{BERT} or GPT \cite{GPT} based on the transformer architecture \cite{Transformer}. In particular, these architectures are used for code generation where parallel data is limited due to the human expertise required for alignment. The best results on code generation are reached by pretraining seq2seq models on external sources, then by fine-tuning those models on smaller data sets. For instance, \citet{orlanski-21} fine-tune BART \cite{BART} on data pairs of natural language and code and by taking advantage of external informations. Similarly, \citet{monolingualdata} used BERT and a transformer decoder in a semi-supervised way by taking advantage of a large amount of additional monolingual data. Another popular method is to train large language models on code \cite{LLM1, APPS}. Notably, GPT-3 has been finetuned on a large quantity of data from Github to obtain a powerful language model named Codex \cite{Codex} that powers Github Copilot, a tool to help developers. Overall the above mentioned solutions aim to take advantage of large amounts of training data available nowadays, but few of them care about generating code that is guaranteed to be syntactically correct nor well typed. Let us mention some exceptions from semantic parsing like \citet{LSTMtree, ASN,tranx-1} that rely on grammatical constraints to ensure that the generated code can be executable. In this work, we study variations around the {\fontfamily{cmss}\selectfont TranX} seq2seq architecture \citep{tranx-2018} for translating natural language to code. Rather than generating directly code tokens from natural language, the architecture generates an Abstract Syntax Tree (AST) constrained by the programming language grammar. The paper reports state of the art results on the task and specifically introduces: \begin{itemize} \item A formalization of the grammar constrained code generator relying on the \citet{earley:1970} parser transition system. \item A study of the impact of key components of the architecture on the performance of the system: we study the impact of the grammatical component itself, the impact of the language model chosen, the impact of variable naming and typing and the impact of the input/output copy mechanisms. \end{itemize} It is structured as follows. Section {\ref{TransitionSystem}} formalizes the symbolic transition system used for generating the grammatically correct code, Section \ref{Code Generation} describes a family of variants around the {\fontfamily{cmss}\selectfont TranX} architecture that will be used to study the impact of these variations in the experimental part of the paper (Section \ref{Experiments}). \section{A transition system for code generation} \label{TransitionSystem} \begin{figure*}[htbp] \begin{center} \hspace{-0.5cm}\scalebox{0.77}{\tt \begin{tabular}{lcl} \asts{expr} &=& \astc{BinOp} \asts{expr} \astf{left}, \asts{operator} \astf{op}, \asts{expr} \astf{right}\\ \asts{operator} &=& \astc{Add}\\ \asts{expr} &=& \astc{Constant} \asts{constant} \astf{value}\\ \asts{expr} &=&\astc{List} \asts{expr*} \astf{elts} \end{tabular}} \end{center} \caption{\label{fig:asdl}Example of ASDL rules for the Python language. Each rule is built from a set of grammatical symbols (in blue), is uniquely identified by a constructor name (in red) and provides names to its right hand side symbols, its fields (in green). Grammatical symbols are split in nonterminals (like {\tt expr}) and terminals or primitives (like {\tt constant}). Grammatical symbols can also be annotated with qualifiers ({\tt *}) that allow for zero or more iterations of the symbol.} \end{figure*} Among the models tested in the paper, some are generating syntactically constrained code. In the context of our study, we propose a transition model that meets two objectives: the code generated is grammatically valid in terms of syntax and the whole translation process still reduces to a seq2seq transduction mechanism that allows us to leverage standard machine learning methods. To this end we introduce a transition system for code generation that generates an AST as a sequence of actions. The derivations can then be translated into ASTs and in actual Python code by means of deterministic functions. The set of valid ASTs is a set of trees that are generated by an ASDL grammar \cite{Wang:97}. An ASDL grammar is essentially a context free grammar abstracting away from low level syntactic details of the programming language and aims to ease the semantic interpretation of the parse trees. To this end ASDL grammar rules come with additional decorators called constructors and field names (Figure \ref{fig:asdl}). Our transition system generates derivations, or sequences of actions, that can be translated to a syntactically correct Python code. We adapt to code generation the transition system of the Earley parser \cite{earley:1970} as formalized in Figure \ref{fig:earley}. The generator state is a stack of dotted rules. A dotted rule is a rule of the form $A\rightarrow \alpha \bullet X \beta$ where $\alpha$ is a sequence of grammar symbols whose subtrees are already generated and $X\beta$ is a sequence of grammar symbols for which the subtrees are yet to be generated. The $\bullet X$ symbol is the dotted symbol or the next symbol for which the system has to generate the subtree. The Python ASDL grammar includes rules with star ($*$) qualifiers allowing zero or more occurrences of the starred symbol. The transition system uses an additional set of starred actions and a {\sc close} action to stop these iterations (Figure \ref{fig:earley}). Each {\sc predict}(C) action starts the generation of a new subtree from its parent. The {\sc generate} action adds a new leaf to a tree. The {\sc complete} action finishes the generation of a subtree and continues the generation process with its parent. The set of {\sc predict} actions is parametrized by the ASDL rule constructor ($C$), thus there are as many predict actions as there are constructors in the ASDL grammar. Constructors are required in order to generate the actual ASTs from the derivations. {\sc generate}(V) actions are actions responsible for generating the terminal or primitive symbols. The Python ASDL grammar generates ASTs with primitive leaf types ({\tt identifier, int, string, constant}) that have to be filled with actual values for the AST to be useful. To generate actual primitive values the set of generate actions is also parametrized by the actual values $V$ for the primitive types. The set of such values is infinite and consequently the set of generate actions is also infinite. Non-Determinism comes from the use of {\sc predict}(C), {\sc generate}(V) and {\sc close} rules. By contrast the application of the {\sc complete} action is entirely deterministic: once the generator has a completed dotted rule on the top of its stack, it has no other choice than applying the complete rule. The sequential generation process is illustrated in Figure \ref{fig:example}. Given a start state, at each time step, the generator has to decide which action to perform according to the current state of the stack and updates the stack accordingly. Once the generator reaches the goal state, we collect the list of actions performed (the derivation) in order to build the AST that we finally translate into actual Python code\footnote{We use the \texttt{astor} library to this end.}. \begin{figure*} \begin{center} \scalebox{0.95}{ \begin{tabular}{llcll}\toprule {\bf Action}&{\bf Transition}&&&{\bf Condition}\\\midrule {\sc start}(C)&$\langle A \rightarrow \bullet \alpha \rangle$\\ {\sc goal }&$\langle A\rightarrow \alpha\bullet \rangle$\\\midrule {\sc predict}(C)&$\langle\mathbf{S}| A\rightarrow \alpha\bullet B\beta \rangle$& $\Rightarrow$& $\langle \mathbf{S}| A\rightarrow \alpha\bullet B\beta | B \rightarrow \bullet \gamma \rangle$&$(B\rightarrow \gamma \in \text{rules})$\\ {\sc generate}(V)&$\langle\mathbf{S}| A\rightarrow \alpha\bullet t \beta \rangle$&$ \Rightarrow$&$ \langle \mathbf{S}|A\rightarrow \alpha t\bullet\beta \rangle$&$(t\in \text{primitives})$\\ {\sc complete}&$\langle\mathbf{S}| A\rightarrow \alpha\bullet B\beta |B\rightarrow \gamma \bullet\rangle$& $\Rightarrow $&$\langle\mathbf{S}| A\rightarrow \alpha B \bullet \beta\rangle$\\\midrule {\sc predict}$^*$(C)&$\langle\mathbf{S}| A\rightarrow \alpha\bullet B^*\beta \rangle$& $\Rightarrow$& $\langle \mathbf{S}| A\rightarrow \alpha \bullet B^*\beta | B \rightarrow \bullet \gamma\rangle$&$(B\rightarrow \gamma \in \text{rules})$\\ {\sc generate}$^*$(V)&$\langle\mathbf{S}| A\rightarrow \alpha\bullet t^* \beta \rangle$ &$\Rightarrow$&$\langle \mathbf{S}|A\rightarrow \alpha t^\bullet t^*\beta \rangle$&$(t\in \text{primitives})$\\ {\sc complete}$^*$&$\langle\mathbf{S}| A\rightarrow \alpha\bullet B^*\beta |B\rightarrow \gamma \bullet\rangle $&$\Rightarrow$&$ \langle\mathbf{S}| A\rightarrow \alpha B\bullet B^* \beta\rangle$\\ {\sc close}$^*$ &$\langle\mathbf{S}|A\rightarrow \alpha \bullet X^*\beta \rangle$&$\Rightarrow$& $\langle\mathbf{S}|A\rightarrow \alpha \bullet\beta \rangle$\\\bottomrule \end{tabular}} \end{center} \caption{\label{fig:earley} An Earley inspired transition system for generating Abstract Syntactic Trees. The state of the generator is a stack of dotted rules whose bottom is $\mathbf{S}$. As in the the Earley parser, the {\sc predict} rule starts the generation of a new subtree by pushing a new dotted rule on the stack, the {\sc generate} rule adds a leaf to the tree by swapping the top of the stack and the {\sc complete} rule attaches a generated subtree into its parent by popping the top two elements of the stack and pushing an updated dotted rule. To handle {\tt *} qualifiers we add the starred inference rules where {\sc complete}$^*$ and {\sc generate}$^*$ implement an iteration that stops with the {\sc close}$^*$ rule. } \end{figure*} \begin{figure*} \begin{center} \begin{minipage}{.57\textwidth} \scalebox{0.6} {\begin{tabular}{ll}\toprule {\bf Generator State (stack)}&{\bf Action}\\\midrule $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* \rangle$&{\sc start}(List)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{operator}\,\mathtt{expr} \rangle$&{\sc predict}$^*$(BinOp)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{operator}\,\mathtt{expr}| \mathtt{expr} \rightarrow\bullet \mathtt{constant}\rangle$&{\sc predict}(Constant)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{operator}\,\mathtt{expr}| \mathtt{expr} \rightarrow \mathtt{constant}\bullet\rangle$&{\sc Generate}(7)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \bullet\mathtt{operator}\,\mathtt{expr}\rangle $&{\sc complete}\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \bullet\mathtt{operator}\,\mathtt{expr} | \mathtt{expr}\rightarrow\bullet\rangle $&{\sc predict}(Add)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\bullet\mathtt{expr} \rangle $&{\sc complete}\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\bullet\mathtt{expr}|\mathtt{expr}\rightarrow \bullet\mathtt{constant}\rangle $&{\sc predict}(Constant)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\bullet\mathtt{expr}|\mathtt{expr}\rightarrow \mathtt{constant}\bullet\rangle $&{\sc generate}(5)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\mathtt{expr}\bullet\rangle $&{\sc complete}\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\bullet\mathtt{expr}^* \rangle $&{\sc complete}$^*$\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\bullet\mathtt{expr}^* | \mathtt{expr}\rightarrow\bullet\mathtt{constant}\rangle $&{\sc predict}$^*$(Constant)\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\bullet\mathtt{expr}^* | \mathtt{expr}\rightarrow\mathtt{constant}\bullet\rangle $&{\sc generate}(4)\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\,\mathtt{expr}\bullet\mathtt{expr}^* \rangle $&{\sc complete}$^*$\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\,\mathtt{expr}\bullet\rangle $&{\sc close}$^*$\\\bottomrule \end{tabular} } \end{minipage} \begin{minipage}{.4\textwidth} \tikzset{every tree node/.style={align=center,anchor=north}} \tikzset{level distance=40pt} \scalebox{0.65}{ \begin{tikzpicture} \Tree [.{\asts{expr}\\\astc{(List)}} [.\node(left){\asts{expr}\astf{:elts}\\\astc{(BinOp)}}; [.{\asts{expr}\astf{:left}\\\astc{(Constant)}} {\asts{constant}\astf{:value}\\{\bf 7}} ] {\asts{operator}\astf{:op}\\\astc{(Add)}} [.{\asts{expr}\astf{:right}\\\astc{(Constant)}} {\asts{constant}\astf{:value}\\{\bf 5}} ] ] [.\node(right){\asts{expr}\astf{:elts}\\\astc{(Constant)}}; {\asts{constant}\astf{:value}\\{\bf 4}} ] ] \fill [rounded corners=0.3cm,fill=yellow, fill opacity=0.2] (left.south west) rectangle (right.north east); \end{tikzpicture} } \end{minipage} \end{center} \caption{\label{fig:example}Example derivation for the generation of the Python list expression {\tt [7+5,4]}. The derivation starts with $\mathtt{expr}$ as axiom symbol and applies transitions until the goal is reached. The list of actions performed is called the generator {\bf derivation}. Given a generated derivation we can design a straightforward deterministic procedure to translate it into an {\sc ast}. The actual Python code is generated from the {\sc ast} by the {\tt astor} library.} \end{figure*} \comment{ \begin{figure*} \begin{center} \begin{minipage}{.57\textwidth} \scalebox{0.6} {\begin{tabular}{ll}\toprule {\bf Generator State (stack)}&{\bf Action}\\\midrule $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr} \rangle$&{\sc start}(Expr)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr} |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{expr}^*\,\mathtt{keyword}^* \rangle$&{\sc predict}(Call)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr} |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{expr}^*\,\mathtt{keyword}^*| \mathtt{expr} \rightarrow\bullet \mathtt{identifier}\ \mathtt{expr\_context}\rangle$&{\sc predict}(Name)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr} |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{expr}^*\,\mathtt{keyword}^*| \mathtt{expr} \rightarrow\bullet \mathtt{identifier}\ \mathtt{expr\_context}\rangle$&{\sc generate}(foo)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \bullet \mathtt{expr}\, \mathtt{operator}\,\mathtt{expr}| \mathtt{expr} \rightarrow \mathtt{constant}\bullet\rangle$&{\sc Generate}(7)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \bullet\mathtt{operator}\,\mathtt{expr}\rangle $&{\sc complete}\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \bullet\mathtt{operator}\,\mathtt{expr} | \mathtt{expr}\rightarrow\bullet\rangle $&{\sc predict}(Add)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\bullet\mathtt{expr} \rangle $&{\sc complete}\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\bullet\mathtt{expr}|\mathtt{expr}\rightarrow \bullet\mathtt{constant}\rangle $&{\sc predict}(Constant)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\bullet\mathtt{expr}|\mathtt{expr}\rightarrow \mathtt{constant}\bullet\rangle $&{\sc generate}(5)\\ $\langle \mathtt{expr} \rightarrow \bullet\mathtt{expr}^* |\mathtt{expr}\rightarrow \mathtt{expr}\, \mathtt{operator}\,\mathtt{expr}\bullet\rangle $&{\sc complete}\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\bullet\mathtt{expr}^* \rangle $&{\sc complete}$^*$\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\bullet\mathtt{expr}^* | \mathtt{expr}\rightarrow\bullet\mathtt{constant}\rangle $&{\sc predict}$^*$(Constant)\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\bullet\mathtt{expr}^* | \mathtt{expr}\rightarrow\mathtt{constant}\bullet\rangle $&{\sc generate}(4)\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\,\mathtt{expr}\bullet\mathtt{expr}^* \rangle $&{\sc complete}$^*$\\ $\langle \mathtt{expr} \rightarrow \mathtt{expr}\,\mathtt{expr}\bullet\rangle $&{\sc close}$^*$\\\bottomrule \end{tabular} } \end{minipage} \begin{minipage}{.4\textwidth} \tikzset{every tree node/.style={align=center,anchor=north}} \tikzset{level distance=40pt} \scalebox{0.45}{ \begin{tikzpicture} \Tree [.{\asts{expr}\\\astc{(Expr)}} [.\node(left){\asts{expr}\astf{:value}\\\astc{(Call)}}; [.{\asts{expr}\astf{:func}\\\astc{(Attribute)}} [.{\asts{expr}\astf{:value}\\\astc{(Name)}} {\asts{identifier}\astf{:id}\\{\bf foo}} {\asts{expr\_context}\astf{}\\\astc{(Load)}} ] {\asts{identifier}\astf{:attribute}\\{\bf append}} {\asts{expr\_context}\astf{}\\\astc{(Load)}} ] [.{\asts{expr}\astf{:args}\\\astc{(List)}} [.{\asts{expr}\astf{:value}\\\astc{(Num)}} {\asts{object}\astf{:n}\\{\bf 8}} ] [.{\asts{expr}\astf{:value}\\\astc{(Num)}} {\asts{object}\astf{:n}\\{\bf 7}} ] {\asts{expr\_context}\astf{}\\\astc{(Load)}} ] {\asts{expr\_context}\astf{}\\\astc{(Load)}} ] ] \fill [rounded corners=0.3cm,fill=yellow, fill opacity=0.2] (left.south west) rectangle (right.north east); \end{tikzpicture} } \end{minipage} \end{center} \caption{\label{fig:exampleNath}Example derivation NATH for the generation of the Python list expression {\tt foo.append([8,7])}. The derivation starts with $\mathtt{expr}$ as axiom symbol and applies transitions until the goal is reached. The list of actions performed is called the generator {\bf derivation}. Given a generated derivation we can design a straightforward deterministic procedure to translate it into an {\sc ast}. The actual Python code is generated from the {\sc ast} by the {\tt astor} library} \end{figure*} } \section{Factors influencing code prediction} \label{Code Generation} All architectures analyzed in this study are variations around a seq2seq architecture. We describe the several variants of this architecture used in this paper both on the encoder and decoder side. We identify key factors that have an impact on the natural-language-to-code translation architecture and we formalize a family of models that allow to test variations of these factors. \begin{figure*} \begin{center} \scalebox{0.9}{ \includegraphics[width=\textwidth]{images/model.png}} \end{center} \caption{\label{fig:model}Illustration of the seq2seq model with the variables {\sc substitution}, {\sc grammar}, {\sc bert}, {\sc pointernet} set to {\sc True}. We describe here the complete process where we predict a derivation sequence composed of grammar rules and {\sc close} ({\sc predrule}) or Python variables/built-in ({\sc generate}). The astor library is used to transform the AST constructed with the derivation sequence into Pyton code. In the case where {\sc grammar = False}, we only have the {\sc generate} action which exclusively predicts unconstrained code tokens (as for a classical seq2seq).} \end{figure*} We consider a family of models generating Python code $y$ from a natural language description $x$, that have the generic form: \begin{equation} p({y|x}) = \prod_{t}p({y}_t|y_{<t},x) \end{equation} $y$ is either a sequence of code tokens in case we do not use a grammar, or a sequence of actions from a derivation in case we use a grammar. The decoding objective aims to find the most-probable hypothesis among all candidate hypotheses by solving the following optimization problem: \begin{equation} \label{eqn:MAP} \hat{y} = \mathop{\text{argmax}}_{y} p(y|x) \end{equation} The family of models varies according to four key qualitative factors that we identify in the {\fontfamily{cmss}\selectfont TranX} architecture. First we describe a substitution procedure managing variables and lists names in section \ref{Preprocessing}). Second, in section \ref{subsec:encoder}, we test the architectural variations for encoding the natural language sequence. Third, in section \ref{subsec:decoder}, we describe variations related to constraining the generated code with grammatical constraints and architectural variations that allow to copy symbols from the natural language input to the generated code. \subsection{Substitution} \label{Preprocessing} Programming languages come with a wide range of variable names and constant identifiers that make the set of lexical symbols infinite. Rather than learning statistics on a set of ad-hoc symbols, we rather normalize variable and constant names with a pre-processing method, reusing the method of \citet{tranx-2018}. Preprocessing amounts to substitute the actual names of the variables with a normalized set of predefined names known to the statistical model. The substitution step renames all variables both in the natural language and in the code with conventional names such as \verb+var_0, var_1+, etc. for variables and \verb+lst_0,lst_1+, etc. for lists. A post processing step substitutes back the predicted names with the original variable names in the system output. For example, given the natural language intent: \begin{quote} \textit{create list \texttt{\textasciigrave done\textasciigrave} containing permutations of each element in list \texttt{\textasciigrave [a, b, c, d]\textasciigrave} with variable \texttt{\textasciigrave x\textasciigrave} as tuples} \end{quote} is transformed into: \begin{quote} \textit{create list \texttt{var\_0} containing permutations of each element in list \texttt{lst\_0} with variable \texttt{var\_1} as tuples} \end{quote} The predicted code such as \codeword{var_0 = [(el, var_1) for el in [lst_0]]} is transformed back into \codeword{done = [(el, x) for el in [a, b, c, d]]}. Models using variable replacement as illustrated above, are identified with the notation {\sc substitution = True} in section \ref{Experiments}. Implementing this heuristic is made easy by the design of the {\fontfamily{cmss}\selectfont CoNaLa} data set where all such names are explicitly quoted in the data while for {\fontfamily{cmss}\selectfont Django} we had to detect variable names by comparing natural language with its corresponding code. \subsection{Encoder} \label{subsec:encoder} We switched between a classic bi-LSTM and a pretrained $\mathrm{BERT_{BASE}}$ to encode the input natural language $\{x_{i}, i \in \llbracket 1, n \rrbracket \}$ of $n$ words into a vectorial representations $\{h_{i}^\mathrm{(enc)}, i \in \llbracket 1, n \rrbracket \}$ which are later used to compute the attention mechanism. \\ We set the {\sc BERT} factor to {\sc True} when using it and {\sc False} when using the bi-{\sc lstm}. \subsection{Decoder} \label{subsec:decoder} At each time step $t$, the $\mathrm{LSTM}$ decoder computes its internal hidden state $h_{t}^\mathrm{(dec)}$: \begin{equation} { h_{t}^\mathrm{(dec)}} = \text{LSTM}([e_{t-1}:\widetilde{a}_{t-1}], h_{t-1}^\mathrm{(dec)}) \end{equation} where $e_{t-1}$ is the embedding from the previous prediction, $\widetilde{a}_{t-1}$ is the attentional vector. We compute the attentional vector $\widetilde{a}_{t}$ as in \citet{Attention} combining the weighted average over all the source hidden state $c_t$ and the decoder hidden state $h_{t}^\mathrm{(dec)}$: \begin{equation} \widetilde{a}_t = W_a[c_t:h_{t}^\mathrm{(dec)}] \end{equation} It is the attention vector $\widetilde{a}_{t}$ which is the key to determine the next prediction $y_t$. We use several variants of the code generator, that we describe by order of increasing complexity. The basic generator is a feed forward that uses the attention vector to generate a code token $v$ from a vocabulary $V$: \begin{equation} \label{eqn:generate} \begin{aligned} p(y_t = \mathrm{GENERATE}[v]|x, e_{<t}) = \\ \text{softmax}(e_v^\top \cdot W_g \cdot {\widetilde{a}_t}) \end{aligned} \end{equation} These models are not constrained by the Python grammar and we identify these models with {\sc grammar = False}. We also use a pointer network that may either copy symbols from input to output or generate symbols from $V$. Then the probability of generating the symbol $v$ is given by the marginal probability: \begin{equation} \label{eqn:generate+pn} \begin{aligned} p(y_t = \mathrm{GENERATE}[v]|x, e_{<t})= \\ p(\mathrm{gen}|x,e_{<t}) p(v|\mathrm{gen}, x, e_{<t}) \\ + p(\mathrm{copy}|x,e_{<t}) p(v|\mathrm{copy}, x, e_{<t}) \end{aligned} \end{equation} The probabilities $p(\mathrm{gen}|.)$ and $p(\mathrm{copy}|.)$ sum to 1 and are computed with $\text{softmax}(W \cdot \widetilde{a}_t)$. The probability of generating $v$ from the vocabulary $V$ $p(v|\mathrm{gen}, .)$ is defined in the same way as (\ref{eqn:generate}). We use the pointer net architecture \cite{Pointernet} to compute the probability $p(v|\mathrm{copy},.)$ of copying an element from the natural language $x$. Models that use a pointer network are identified with {\sc pn = True}, otherwise with {\sc pn = False} . Finally we use a set of models that are constrained by the Python grammar and that rely on the transition system from section \ref{TransitionSystem}. Rather than directly generating Python code, these models generate a derivation whose actions are predicted using two prediction tasks. \\ When the generator is in a state where the dot of the item on the top of the stack points on a nonterminal symbol, the {\sc predrule} is used. This task either outputs a {\sc predict}(C) action or the {\sc close} action: \begin{equation} \label{eqn:applyrule} \begin{aligned} p(y_t = \mathrm{PREDRULE}[c]|x, e_{<t})= \\ \text{softmax}(e_r^\top \cdot W_p \cdot {\widetilde{a}_t}) \end{aligned} \end{equation} When the generator is in a state where the dot of the item on the top of the stack points on a terminal symbol, the generate task is used. This amounts to reuse either equation (\ref{eqn:generate}) or equation (\ref{eqn:generate+pn}) according to the model at hand. Models constrained by the grammar are labelled with {\sc grammar = True}. Recall that the {\sc complete} action of the transition system is called deterministically (Section \ref{TransitionSystem}). \comment{ \subsubsection{Action Probabilities} {\sl comment on grammatical constraints; pointer network } The attentional vector $\widetilde{s}_t$ is the key to compute the next derivation's action. \\ \textbf{\texttt{PREDICT} case} The probability of using rule r as the current action $d_t$ is given by softmax: \begin{equation} \label{eqn:applyrule} \begin{aligned} p(d_t = PREDICT[r]|x, d_{<t})= \\ \text{softmax}(a_t^T \cdot W \cdot {(\widetilde{s}_t})) . e(r) \end{aligned} \end{equation} where each row of $a_t$ is embedding matrix for \texttt{PREDICT} and e(r) is the one-hot vector for rule r. \\ \textbf{\texttt{GENERATE} case} As explained in \nameref{Code Generation}, a new token $v$ can be generated from an external vocabulary or copied from the input. Then the probability of generating $v$ is given by the marginal probability: \begin{equation} \begin{aligned} p(d_t = GENERATE[v]|x, d_{<t})= \\ p(gen|x,d_{<t}) p(v|gen, x, d_{<t}) \\ + p(copy|x,d_{<t}) p(v|copy, x, d_{<t}) \end{aligned} \end{equation} {\sl distinguer le cas où on utilise le PN et la cas où on l'utilise pas} Here, the probabilities p(gen|.) and p(copy|.) are computed with $\text{softmax}(W . \widetilde{s}_t)$. The probability of generating v from an external vocabulary $p(v|gen, .)$ is defined in the same way as \ref{eqn:applyrule} (with $W_g$ as embedding matrix for \texttt{GENERATE}). We use the pointer net architecture \cite{Pointernet} to compute the probability $p(v|copy,.)$ of copying an element from the natural language $x$.} \section{Experiments} \label{Experiments} In this section we describe the characteristics of the data sets on which we have tested our different setups and the underlying experimental parameters\footnote{The code of our experiments is public and available at {\tt https://gitlab.com/codegenfact/BertranX}}. \comment{ \subsection{Setup} {\bf Data sets} In this study we use two available data sets, {\fontfamily{cmss}\selectfont Django} and {\fontfamily{cmss}\selectfont CoNaLa}, to perform our code generation task. The {\fontfamily{cmss}\selectfont Django} data set provides line-by-line comments with code from the {\fontfamily{cmss}\selectfont Django} web framework. About 70\% of the 18805 examples are simple Python operation ranging from function declarations to package imports, and including exception handling. Those examples strongly share the natural language structure (e.g. {\it call the function cache.close} $\rightarrow$ \texttt{cache.close()}) with more than 26\% of the words in the natural language are also present in the code. The BLEU score between the NL-code is equal to 19.4. {\fontfamily{cmss}\selectfont CoNaLa} is made up of 600k natural language-code pairs from {\tt StackOverflow}, part of which have been manually cleaned up by developers (2879 examples). The natural language descriptions correspond to actual developer queries (e.g. {\it Delete an element 0 from a dictionary `a`}) and the associated code is diverse and idiomatic ({e.g. \tt \{i: a[i] for i in a if (i != 0)\}}). Compared to {\fontfamily{cmss}\selectfont Django}, the code is therefore much more difficult to generate. In particular because the number of words shared between the NL and the code is much lower (BLEU = 0.32). Also, the code is longer and more complex with an AST depth of 7.1 on average against 5.1 for {\fontfamily{cmss}\selectfont Django}. {\bf Configuration} Hyperparameters of our model depend on whether BERT is used or not. \\ When {\sc BERT = False}, the size of all embeddings is 128. The hidden layers size of the bi-LSTM at encoding and the LSTM at decoding is 256. The resulting attention vector size is 300. Since our data sets are relatively small for a data-hungry neural model, we impose regularization with a word dropout layer for embeddings and dropout at the output of the attention.\\ When {\sc BERT = True}, the size of the natural language embedding is already set to 756 with BERT. We therefore apply a linear transformation to its output so that the embedding size is equal to 512.The embedding of the code tokens is fixed at 256, as well as the embeddings of the grammar actions when {\sc grammar = True}. LSTM decoder hidden state and attention vector are set at 512. We regularize only the attentional vector in that case.\\ In both case, we use a beam search size of 15 for decoding. \\} \subsection{Data sets} In this study we use two available data sets, {\fontfamily{cmss}\selectfont Django} and {\fontfamily{cmss}\selectfont CoNaLa}, to perform our code generation task. The {\fontfamily{cmss}\selectfont Django} data set provides line-by-line comments with code from the {\fontfamily{cmss}\selectfont Django} web framework. About 70\% of the 18805 examples are simple Python operation ranging from function declarations to package imports, and including exception handling. Those examples strongly share the natural language structure (e.g. {\it call the function cache.close} $\rightarrow$ \texttt{cache.close()}). More than 26\% of the words in the natural language are also present in the code, BLEU score between the natural language and code is equal to 19.4. {\fontfamily{cmss}\selectfont CoNaLa} is made up of 600k NL-code pairs from {\tt StackOverflow}, among which 2879 examples have been been manually cleaned up by developers. All results are reported on the manually curated examples, unless stated otherwise. The natural language descriptions are actual developer queries (e.g. {\it Delete an element 0 from a dictionary `a`}) and the associated code is diverse and idiomatic ({e.g. \tt \{i: a[i] for i in a if (i != 0)\}}). Compared to {\fontfamily{cmss}\selectfont Django}, the code is much more challenging to generate. Especially because the number of words shared between the NL and the code is much lower (BLEU = 0.32). Also, the code is longer and more complex with an AST depth of 7.1 on average against 5.1 for {\fontfamily{cmss}\selectfont Django}. \subsection{Vocabulary generation} The vocabulary of natural language and code is essential. Usually, this vocabulary is created by adding all the words present in the training data set. There are however exceptions that are detailed in this section. The natural language vocabulary relies on a byte pair encoding tokenizer when {\sc BERT = True}. As explained in section \ref{Preprocessing}, the variable names are replaced with special tokens \texttt{var\_i} and \texttt{lst\_i}. These new tokens are crucial to our problem, and added to the BERT vocabulary . We can then fine-tune BERT with this augmented vocabulary on our data sets. For the decoder part, when {\sc grammar = True}, the vocabulary of grammatical actions is fixed, while the vocabulary of AST leaves has to be built. This associated vocabulary can be composed of built-in Python functions, libraries with their associated functions or variable names. Its creation is consequently a major milestone in the generation process. To create this external vocabulary, we proceed as in {\fontfamily{cmss}\selectfont TranX}. From the code, we create the derivation sequence composed of the action of the grammar as well as the primitives. All primitives of the action sequences are incorporated into our external vocabulary. \subsection{Setup} When {\sc BERT = False}, the size of the representations is kept small to prevent overfitting. Encoder and decoder embedding size is set to 128. The hidden layer size of the encoder and decoder bi-LSTM is set to 256 and the resulting attention vector size is 300. We have two dropout layers: for embeddings and at the output of the attention. We use Adam optimizer with learning rate $\alpha = 5.10^{-3}$. When {\sc BERT = True}, encoder embeddings have a natural size of 756 with BERT. We therefore apply a linear transformation to its output to get an embedding size equal to 512. The size of LSTM decoder hidden state and attention vector are set to 512. We regularize only the attentional vector in that case. We use Adam optimizer with learning rate $\alpha = 5.10^{-5}$. In both cases, we use a beam search size of 15 for decoding. \paragraph{Evaluation} To compare with previous work, we report the standard evaluation metrics for each data set: exact match accuracy and corpus-level BLEU. \paragraph{Python version} As the grammar slightly changes between Python versions, let us mention that all our experiments have been carried out with Python 3.7. \subsection{Ablation study} \label{Ablation} \begin{table*}[htbp] \begin{center} \scalebox{0.85}{ \begin{tabular}{ |c|c|c|c|c|c|c|c| } \hline Substitution & {\sc Bert} & Grammar & PN & {\fontfamily{cmss}\selectfont CoNaLa} BLEU & {\fontfamily{cmss}\selectfont CoNaLa} accuracy & {\fontfamily{cmss}\selectfont Django} BLEU & {\fontfamily{cmss}\selectfont Django} accuracy \\ \hline \multirow{8}{2em}{False} & \multirow{4}{2em}{False} & \multirow{2}{2em}{False} & \multirow{1}{2em}{False} & $21.05 \pm 0.81$ & $0.9\pm 0.42$ & $42.58 \pm 1.54$ & $26.86 \pm 1.15$ \\ \cline{4-8} & & & \multirow{1}{2em}{True} & $22.33 \pm 0.78$ & $1.7\pm 0.90$ & $64.79 \pm 1.00$ & $62.85 \pm 1.21$ \\ \cline{3-8} & & \multirow{2}{2em}{True} & \multirow{1}{2em}{False} & $20.59 \pm 0.74$ & $2.87 \pm 0.48$ & $43.23 \pm 1.62$ & $30.12\pm 0.63$ \\ \cline{4-8} & & & \multirow{1}{2em}{True} &$22.16 \pm 1.93$ & $3.87 \pm 1.65$ & $62.55 \pm 1.60$ & $65.20 \pm 0.03$ \\ \cline{2-8} & \multirow{4}{2em}{True} & \multirow{2}{2em}{False} & \multirow{1}{2em}{False} & $30.83\pm 4.08$ & $2 \pm 0.94$ & $53.18 \pm 0.87$ & $30.28 \pm 0.26$ \\ \cline{4-8} & & & \multirow{1}{2em}{True} & $30.98 \pm 1.33$ & $3.3 \pm 1.48$ & $58.69 \pm 1.28$ & $37.96 \pm 0.27$ \\ \cline{3-8} & & \multirow{2}{2em}{True} & \multirow{1}{2em}{False} & $25.88 \pm 0.94$ & $3.8 \pm 1.96$ & $47.32 \pm 0.50$ & $29.62 \pm 0.33$ \\ \cline{4-8} & \multirow{6}{2em}{False} & & \multirow{1}{2em}{True} & $28.43 \pm 0.64 $& $4.4 \pm 1.67$ & $52.55 \pm 0.51$ & $37.38 \pm 0.38$ \\ \cline{1-8} & & \multirow{2}{2em}{False} & \multirow{1}{2em}{False} & $31.17 \pm 0.88$ & $3.1\pm 1.52$ & $70.4 \pm 0.25$ & $70.40 \pm 0.29$ \\ \cline{4-8} \multirow{10}{2em}{True} & & & \multirow{1}{2em}{True} & $32.10 \pm 1.06$ & $3.1 \pm 1.24$& $70.28 \pm 0.38$& $70.46 \pm 0.37$ \\ \cline{3-8} & & \multirow{2}{2em}{True} & \multirow{1}{2em}{False} & $33.36 \pm 1.63$ & $6.37 \pm 0.63$ & $70.82 \pm 0.22$ & $71.3 \pm 0.19$ \\ \cline{4-8} & & & \multirow{1}{2em}{True} & $32.86 \pm 1.75$ & $5 \pm 1.67$& $70.62 \pm 0.49$& $71.47 \pm 0.19$ \\ \cline{2-8} & \multirow{6}{2em}{True} & \multirow{3}{2em}{False} & \multirow{1}{2em}{False} & $36.43\pm 0.41$ & $4.5 \pm 1.84$ & $\boldsymbol{76.97 \pm 0.15}$ & $74.58 \pm 0.27$ \\ \cline{4-8} & & & \multirow{2}{2em}{True} & $36.29 \pm 2.27$ & $5 \pm 1.32$ &$76.62 \pm 0.50$& $\boldsymbol{76 \pm 0.71}$ \\ & & & & $35.42 \pm 1.75^*$ & $5.2 \pm 1.33^*$ & - & - \\ \cline{3-8} & & \multirow{3}{2em}{True} & \multirow{1}{2em}{False} & $35.04 \pm 1.03$ & $7.3 \pm 1.25$ & $76.20 \pm 0.46$ & $74.88 \pm 0.56$ \\ \cline{4-8} & & & \multirow{2}{2em}{True} & $37.99 \pm 1.85$ & $7.5 \pm 1.12$ &$76.32 \pm 0.59$& $75.32 \pm 1.54$ \\ & & & & $\boldsymbol{39.01 \pm 1.08}^*$ & $\boldsymbol{ 7.7 \pm 1.92}^*$ & - & - \\ \hline \end{tabular}} \caption{Performances with different natural language encoders on the development sets with and without a grammatical component. The scores reported are the mean and standard deviation resulting from training with 5 different seeds. The * refers to the use of 100k {\fontfamily{cmss}\selectfont CoNaLa} mined data in addition to clean examples.} \label{table:ablationstudy} \end{center} \end{table*} \begin{figure}[htbp] \scalebox{0.48}{ \includegraphics[width=\textwidth]{images/marginalmean.png}} \caption{Difference between the marginal mean of each variable for the {\sc True} and {\sc False} conditions. } \label{fig:margmean} \end{figure} To highlight the contribution of the different factors, {\sc substitution, bert, grammar, pn} on the {\fontfamily{cmss}\selectfont Django} and {\fontfamily{cmss}\selectfont CoNaLa} data sets we report a detailed study of their impact in Table \ref{table:ablationstudy}. The results are analyzed by distinguishing lexical and grammatical aspects and by identifying relations between the different factors. We start by a comparison of the marginal mean of the BLEU score for each of our variables in both conditions. Figure \ref{fig:margmean} highlights the mean difference between the conditions by contrasting the case where the value is {\sc True} with the case where the value is {\sc False}. \comment{ \begin{figure}[htbp] \begin{tikzpicture} \begin{axis}[ symbolic x coords={substitution, BERT, grammar, pointernet}, xtick=data,ylabel=BLEU, ybar,height=7cm,width=8cm] \addplot[ybar,fill=blue] coordinates { (substitution,9.13) (BERT,5.78) (grammar,-0.91) (pointernet,1.1) }; \addplot[ybar,fill=red] coordinates { (substitution,20.41) (BERT,2.83) (grammar,-1.73) (pointernet,6.47) }; \legend{CoNaLa, Django} \end{axis} \end{tikzpicture} \caption{Difference between the marginal mean of each variables set to True and False. {\it la légende est dégueu je sais pas comment tourner ça}} \label{fig:margmean} \end{figure} \\} \begin{table*}[htbp] \scalebox{0.8}{ \begin{tabular}{l|cccc} \hline System & {\fontfamily{cmss}\selectfont CoNaLa} BLEU & {\fontfamily{cmss}\selectfont CoNaLa} accuracy & {\fontfamily{cmss}\selectfont Django} BLEU & {\fontfamily{cmss}\selectfont Django} accuracy \\ \midrule \citep{tranx-2018} & 27.2 & - & - & 73.7\\ \citep{tranx-2018} + mined & 28.1 & - & - & - \\ \citep{orlanski-21} + mined 100k &30.55&-&-&-\\ \citep{monolingualdata} + 600k mined & 32.57&-&-& {\bf 81.03}\\ \midrule Ours {\sc Bert + grammar} & 31.6 & 4.5 & 79.86 & 79.77 \\ Ours {\sc bert + grammar} + 100k mined & {\bf 34.20} & {\bf 5.8} & - & - \\ \hline Ours {\sc Bert} (tokens) & 30.73 & 1.40 & 79.81 & 79.61 \\ Ours {\sc bert} + 100k mined (tokens) & 32.39 & 3.4 & - & - \\ \hline \end{tabular}} \caption{Comparisons of the systems trained without external data sources on {\fontfamily{cmss}\selectfont CoNaLa} and {\fontfamily{cmss}\selectfont Django} test sets.} \label{table:sota} \end{table*} \paragraph{Pointer network} The pointer network can improve the results, especially when {\sc substitution = False}. This is because the only way to obtain the name of the variables is to copy them. Combined with substitution, the pointer network offers an additional possibility to predict the \codeword{var_i, lst_i} which allows to achieve the best results with a BLEU score of 39.01 on {\fontfamily{cmss}\selectfont CoNaLa} and an exact match accuracy of 76 on {\fontfamily{cmss}\selectfont Django}. \paragraph{Substitution and Typing} The scores are stabilised and much higher with substitution. We gain more than 9 points of BLEU on {\fontfamily{cmss}\selectfont CoNaLa} (respectively 20 points on {\fontfamily{cmss}\selectfont Django}) thanks to substitution. The "weakest" configuration where all variables are {\sc False} except the substitution gives better results than all configurations where {\sc substitution = False}. \\ The increase in BLEU with substitution can be explained in two ways. On the one hand, we remark that the model has difficulties to memorize the values to fill the lists with {\sc generate}. For example, four tokens of code must be generated to predict the list \codeword{[a, b, c, d]}. Using substitution, the model can just predict \texttt{lst\_0} which will be replaced by \codeword{[a, b, c, d]} during postprocessing. This avoids a potential error in the creation of the list and directly gives a valid 4-gram. This contributes to greatly increase the BLEU, which shows the importance of replacing lists. On {\fontfamily{cmss}\selectfont CoNaLa}, BLEU score on the development set drops from an average of 37.99 to an average of 30.66 without list replacement. Besides list replacement, the architecture has also a weakness with respect to variable typing. When using the grammar without substitution, the results are lower than without grammar. This effect is the result of a type checking failure. The model predicts ill-typed AST structures. For instance it predicts an AST whose corresponding code should be \codeword{1.append([6,7])}. However the AST library we used prevents from generating such ill-typed code. The absence of code generation in such cases explain the decrease in BLEU score. The use of substitution partially corrects for these typing errors because the substituted symbols \codeword{var_i, lst_i} are generally more likely to be predicted and are likely to have the right type thanks to the mapping. {\bf Grammatical aspect} The transition system doesn't improve the results on average because of the empty predictions when {\sc substitution = False}. The use of the transition system leads to better results when {\sc substitution = True} but not as drastically as one would have expected. However the real contribution of the grammar associated with substitution is the syntactic validity of the code in 100\% of the cases, as tested with our architecture obtaining the best results. In scenarios where we do not use the grammar, it is never the case to have an empty output. But then the proportion of code sequences that are actually syntactically valid in this setup is 92\% on average. \paragraph{BERT} As expected when using BERT to encode the natural language input we get an improvement of about 6 marginal BLEU on {\fontfamily{cmss}\selectfont CoNaLa} (respectively +3 BLEU on {\fontfamily{cmss}\selectfont Django}). More interestingly, this effect is lower than the one of the substitution operation. \paragraph{}We conclude that the use of a pre-trained model increases the results but less than substitution, despite what one might think and it suggests that improving the management of variable names and lists is one of the key elements for improving the system. The contribution of grammatical constraints in BLEU may seem detrimental but we could see that this is a side effect of typing constraints in adversarial scenarios. Overall the non-constrained generated code is syntactically incorrect in 8\% of the cases. \comment{ \begin{table*} \scalebox{0.85}{ \begin{tabular}{cccc|cc |cc} \toprule {\sc Bert} & grammar & preprocessing &PN&CoNaLa BLEU & CoNaLa accuracy & Django BLEU & Django accuracy \\ \midrule no&no&no&no& $21.05 \pm 0.81$ & $0.9\pm 0.42$ & $42.58 \pm 1.54$ & $26.86 \pm 1.15$ \\ yes &no&no&no & $30.83\pm 4.08$ & $2 \pm 0.94$ & $53.18 \pm 0.87$ & $30.28 \pm 0.26$ \\ \midrule no &no&no&yes& $22.33 \pm 0.78$ & $1.7\pm 0.90$ & $64.79 \pm 1.00$ & $62.85 \pm 1.21$ \\ yes &no&no&yes & $30.98 \pm 1.33$ & $3.3 \pm 1.48$ & $58.69 \pm 1.28$ & $37.96 \pm 0.27$ \\ \midrule no &no&yes&no& $31.17 \pm 0.88$ & $3.1\pm 1.52$ & $70.4 \pm 0.25$ & $70.40 \pm 0.29$ \\ yes &no&yes&no & $36.43\pm 0.41$ & $4.5 \pm 1.84$ & $76.97 \pm 0.15$ & $74.58 \pm 0.27$ \\ \midrule no &no &yes&yes&$32.10 \pm 1.06$ & $3.1 \pm 1.24$& $70.28 \pm 0.38$& $70.46 \pm 0.37$ \\ yes & no &yes &yes& $36.29 \pm 2.27$ & $5 \pm 1.32$ &$76.62 \pm 0.50$& $76 \pm 0.71$ \\ yes* & no &yes&yes & $35.42 \pm 1.75$ & $5.2 \pm 1.33$ & - & - \\ \midrule no &yes&no&no&$20.59 \pm 0.74$ & $2.87 \pm 0.48$ & $43.23 \pm 1.62$ & $30.12\pm 0.63$ \\ yes &yes&no&no & $25.88 \pm 0.94$ & $3.8 \pm 1.96$ & $47.32 \pm 0.50$ & $29.62 \pm 0.33$ \\ \midrule no &yes&no&yes& $22.16 \pm 1.93$ & $3.87 \pm 1.65$ & $62.55 \pm 1.60$ & $65.20 \pm 0.03$ \\ yes&yes &no&yes & $28.43 \pm 0.64 $& $4.4 \pm 1.67$ & $52.55 \pm 0.51$ & $37.38 \pm 0.38$ \\ \midrule no &yes&yes&no& $33.36 \pm 1.63$ & $6.37 \pm 0.63$ & $70.82 \pm 0.22$ & $71.3 \pm 0.19$ \\ yes &yes&yes&no & $35.04 \pm 1.03$ & $7.3 \pm 1.25$ & $76.20 \pm 0.46$ & $74.88 \pm 0.56$ \\ \midrule no &yes &yes&yes&$32.86 \pm 1.75$ & $5 \pm 1.67$& $70.62 \pm 0.49$& $71.47 \pm 0.19$ \\ yes & yes &yes &yes& $37.99 \pm 1.85$ & $7.5 \pm 1.12$ &$76.32 \pm 0.59$& $75.32 \pm 1.54$ \\ yes* & yes &yes&yes & $39.01 \pm 1.08$ & $7.7 \pm 1.92$ & - & - \\ \bottomrule \end{tabular}} \caption{Performances with different natural language encoders on the development sets with and without a grammatical component. The scores reported are the mean and standard deviation resulting from training with 5 different seeds. The * refers to the use of CoNaLa mined data in addition to clean examples.} \label{table:ablationstudy} \end{table*} } \subsection{Test} \label{testset} We compare in table \ref{table:sota} our results with other systems on {\fontfamily{cmss}\selectfont CoNaLa} and {\fontfamily{cmss}\selectfont Django} test sets. We report our best performing models on the development set with and without grammatical constraints. We also use models trained on the full {\fontfamily{cmss}\selectfont CoNaLa} including mined examples to get relevant comparisons. Among the other systems \citet{tranx-2018} is the only one that uses grammatical constraints. Our architecture differs with the use of a BERT encoder whereas \citet{tranx-2018} use an LSTM. The other systems do not use grammatical constraints but rather try to take advantage of additional data. \citet{orlanski-21} and \citet{monolingualdata} aim to take advantage of the {\fontfamily{cmss}\selectfont CoNaLa} mined examples. As these mined examples are noisy, \citet{orlanski-21} takes advantage of BART \cite{BART}, a denoising encoder. They also enrich the natural language input with the results of queries from StackOverflow by adding the title of the post, its associated tags, etc. \citet{monolingualdata} use BERT as encoder and a transformer decoder. They apply the Target Autoencoding method introduced by \citet{TAE}. During training, the encoder parameters are frozen and the decoder is trained to reconstruct code examples. They use this method on the mined examples to take maximal advantage of the additional noisy data. We observe that our grammar based model with BERT encoder is state of the art on {\fontfamily{cmss}\selectfont CoNaLa} while the transformer encoder/decoder architecture of \citet{monolingualdata} performs best on {\fontfamily{cmss}\selectfont Django}. Quite interestingly the exact match accurracy of these models remain weak on {\fontfamily{cmss}\selectfont CoNaLa}. \section{Conclusion} We formalized a transition system that allows us to guarantee the generation of syntactically correct code. A detailed study of the components of the seq2seq architecture reveals that the models have difficulties at managing accurately variable names and list encodings. The comparison with models trained on larger noisy data sets reveals that our grammatically constrained architecture without explicit denoising remains competitive. This further highlights the importance of grammatical constraints and of specific processes dedicated to manage variables, list naming and typing. Finally, we observe that BLEU and exact match, used in this paper, although commonly used in the literature, are not ideal metrics especially because high BLEU scores do not guarantee that the code will be executable. Even exact match is not satifactory since a single natural language query can be solved by several python programs. In future work, we plan to build extensions to the datasets used here with additional test cases assessing the correction of the generated code. These tests are likely to support more relevant metrics for code generation evaluation.
{'timestamp': '2022-03-17T01:34:20', 'yymm': '2202', 'arxiv_id': '2202.13972', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13972'}
arxiv
\section{Introduction} Reconfigurable Intelligent Surfaces (RISs) \cite{huang2019reconfigurable} are lately gaining increased interest as a cost- and power-efficient means to enable programmable wireless signal propagation environments \cite{rise6g}. Due to their minimal hardware footprint, they are envisioned to coat available surfaces or objects in the wireless medium, offering extra degrees of freedom for diverse communication, localization, and sensing improvements. RISs are artificially planar structures usually consisting of multiple unit elements (of half- or even sub-wavelength inter-element spacing), whose reflection behavior can be adjusted to finite discrete states \cite{huang2019holographic}. The dynamic configuration of RISs is handled by dedicated controllers connected to them, while lately RIS hardware architectures including small numbers of Radio Frequency (RF) chains are being proposed \cite{George_RIS_2020,shlezinger2020dynamic,HRIS}, facilitating several RIS-enabled network management tasks. Among the possible functionalities, where RISs can have a significant contribution, belong the high-accuracy localization. This feature constitutes one of the key requirements for fifth Generation (5G), and beyond, wireless networks \cite{Positioning_5G_NR}. An overview of the main challenges and opportunities for localization and mapping with RIS-empowered wireless systems is provided in \cite{wymeersch2019radio}. Considering passive RISs with no active RF chains and quantized phase profiles in \cite{he2020large}, the Cram\'{e}r-Rao lower bound for RIS-based positioning in millimeter Wave (mmWave) Multiple-Input Multiple-Output (MIMO) systems was presented. For the same systems, an adaptive hierarchical codebook for positioning and data transmission was designed in \cite{he2020adaptive}. A supervised learning approach for wave fingerprinting was proposed in \cite{alexandg_2021} for localizing non-cooperative objects in rich scattering RIS-empowered wireless systems. Simultaneous localization and mapping enabled by passive RISs was proposed in \cite{yang2021wireless}. In \cite{keykhosravi2020siso}, a joint three-dimensional localization and synchronization approach for a single-input single-output system empowered by an RIS was designed. In addition to the above works on RISs without RF chains, \cite{shaban2020nearfield} exploited wavefront curvature for positioning, by utilizing RIS-based lenses with a single RF chain for reception. In this paper, motivated by the recent interest in RISs with basic sensing capability \cite{George_RIS_2020,HRIS}, we design a novel user localization method realized with multiple RISs, each equipped with a single Receive (RX) RF chain. Assuming that each meta-atom element of an RIS is coupled with a waveguide and that all waveguide outputs are fed to the RF chain \cite{George_RIS_2020,shlezinger2020dynamic}, we present the following contributions: \emph{i)} We design an Angle-of-Arrival (AoA) estimation technique for single-RX-RF RISs, which is based on collected measurements using multiple RIS phase profiles. \emph{ii)} We capitalize on the AoA estimations from multiple RISs for a source of interest and present a Maximum Likelihood (ML) localization algorithm that is based on a line intersection technique. \emph{iii)} We also derive the Position Error Bounds (PEBs) for the unknown parameters and provide numerical results that demonstrate the accuracy of the proposed localization for various system parameters, including different RIS codebooks, different quantization of RIS phase profiles, and different RIS placements, as well as under near- and far-field conditions. \subsubsection*{Notations} Vectors and matrices are denoted by boldface lowercase and boldface capital letters, respectively. The transpose, Hermitian transpose, and inverse of $\mathbf{A}$ are denoted by $\mathbf{A}^{\rm T}$, $\mathbf{A}^{\rm H}$, and $\mathbf{A}^{-1}$, respectively, while $\mathbf{I}_{n}$ ($n\geq2$) is the $n\times n$ identity matrix and $\mathbf{0}_{n\times m}$ ($n,m\geq1$) is an $n\times m$ matrix with zeros. ${\rm Tr}\{\mathbf{A}\}$ represents $\mathbf{A}$'s trace and $[\mathbf{A}]_{i,j}$ denotes its $(i,j)$-th element, while $[\mathbf{A}]_{:,i:j}$ is a submatrix of $\mathbf{A}$ including all rows of $\mathbf{A}$ and columns from the $i$-th up to the $j$-th. The Euclidean norm of $\mathbf{a}$ is denoted by $\left\|\mathbf{a}\right\|$ and $\odot$ is the matrix Hadamard product. $\mathbb{R}$ and $\mathbb{C}$ represent the real and complex number sets, respectively, and $\Re\left\{\cdot\right\}$ gives the real part of a complex matrix. $\mathbb{E}\{\cdot\}$ is the expectation operator, and $\mathbf{x}\sim\mathcal{CN}(\mathbf{a},\mathbf{A})$ indicates a complex Gaussian random vector with mean $\mathbf{a}$ and covariance matrix $\mathbf{A}$. Finally, $x\sim\mathcal{U}(a,b)$ denotes a uniformly distributed random variable in the interval $[a,b]$, and $\jmath\triangleq\sqrt{-1}$ is the imaginary unit. \vspace{-2mm} \section{System Model}\label{sec:System_Model} \begin{figure}[!t] \centering \includegraphics[trim=7cm 1.5cm 1.8cm 5cm, width=1\columnwidth]{Figures/SystemV4.pdf} \caption{The considered indoor setup with $M$ single-RX-RF RISs, each with $L$ elements, for the localization of a transmitting user at the unknown position $[x_p\,y_p\,z_p]^{\rm T}$. The position $[x_m\,y_m\,z_m]^{\rm T}$, with $m=1,2,\ldots,M$, of the reference unit element at each $m$-th RIS is assumed to be known.}\vspace{-0.4cm} \label{fig:system_setup} \end{figure} We consider the indoor environment of Fig.~\ref{fig:system_setup} comprising $M\ge2$ RISs, which are attached to the room's walls and are themselves planar and perpendicular to the floor. Each RIS consists of $L$ phase-tunable meta-atom elements and is implemented with the single-RX-RF architecture of \cite{George_RIS_2020}. There is a global coordinate system, where the reference point of each $m$-th RIS, with $m=1,2,\ldots,M$, is given by $\mathbf{p}_m\triangleq\left[x_m\;y_m\;z_m\right]^{\rm T}$ and its orientation (in terms of the azimuth angle) is represented by the parameter $\beta_m$. All RISs are assumed to be connected to the same central controller. Finally, a transmitting single-antenna user (the source) is located at the unknown position $\mathbf{p}\triangleq\left[x_p\;y_p\;z_p\right]^{\rm T}$. {It is noted that a similar system model can be considered for outdoor environments, where RISs can be deployed for coating, for example, building facades. This paper's localization method can be equally applied for such a system model.} {We assume that the user broadcasts a pilot symbol $s$ with constant transmit power $P$. This symbol is received $T$ times by each RIS, where during each repetition a different RIS phase profile is used. Under far-field signal propagation and in the presence of $C_{m}$ distinct channel paths, the observation during the $t$-th reception slot} ($t=1,2,\ldots,T$) at each $m$-th RIS's RX RF chain output can be mathematically expressed as follows: {\begin{align} y_{m,t}\triangleq \mathbf{u}_{m,t}^{\rm H}\sum_{c=1}^{C_{m}} h_{m,c}\boldsymbol{\alpha}\left(\phi_{m,c},\theta_{m,c}\right)s+\mathbf{u}_{m,t}^{\rm H}\mathbf{w}_{m,t}, \label{eq:ObservedSignalmthRIS} \end{align} where $h_{m,c}\triangleq\sqrt{P_{L_{m,c}}}\exp\left(\jmath\varphi_{m}\right)$ $\forall$$c=1,2,\ldots,C_m$ includes the gain of the $c$-th signal propagation path with parameter $P_{L_{m,c}}\triangleq\lambda^2/\left(4\pi r_{m,c}\right)^2$ denoting the free-space pathloss, where $\lambda$ is the signal wavelength. Without loss of generality, we assume that the $c=1$ channel path represents the Line-Of-Sight (LOS), hence, its pathloss $P_{L_{m,1}}$ depends on the Euclidean distance $r_{m,1}\triangleq\|\mathbf{p}_m-\mathbf{p}\|$; each distance $r_{m,c}$ for $c\geq2$ is defined similarly considering the position of the corresponding scatterer. In the expression for $h_{m,c}$, $\varphi_m\sim\mathcal{U}(0,2\pi)$ denotes a global phase offset accounting for the lack of phase synchronization between the user and the RF chain of the $m$-th RIS.} The vector $\mathbf{u}_{m,t}\in\mathbb{C}^{L\times 1}$ is the $t$-th phase configuration (among the total $T$ used) of the $m$-th RIS. The vector $\mathbf{w}_{m,t}\in\mathbb{C}^{L\times 1}$ in \eqref{eq:ObservedSignalmthRIS} represents the Additive White Gaussian Noise (AWGN) that is distributed as $\mathcal{CN}(\mathbf{0},\rho\mathbf{I}_L)$. {Finally, the spatial response vector $\boldsymbol{\alpha}\left(\phi_{m,c}, \theta_{m,c}\right)\in\mathbb{C}^{L\times1}$ for the azimuth and elevation AoAs $\phi_{m,c}\in\left[0,2\pi\right]$ and $\theta_{m,c}\in\left[0,\pi\right]$, respectively, of the user transmitted signal via multipath propagation, with respect to the coordinate system having as origin the point $\mathbf{p}_m$ (i.e., the reference point of the $m$-th RIS), is given for $\ell=1,2,\ldots,L$ as follows: \begin{equation}\label{eq:Spatial_response} \left[\boldsymbol{\alpha}\left(\phi_{m,c},\theta_{m,c}\right)\right]_\ell \triangleq \exp\left(-\jmath\mathbf{q}^{\rm T}_{m,\ell}\mathbf{k}(\phi_{m,c},\theta_{m,c})\right), \end{equation} where $\mathbf{q}_{m,\ell}\in\mathbb{R}^{3\times1}$ denotes the position of the $\ell$-th element of the $m$-th RIS and $\mathbf{k}(\phi_{m,c}\theta_{m,c})\in\mathbb{R}^{3\times1}$ is the wavevector at these respective AoAs, which is mathematically defined as: \begin{align} \mathbf{k}(\phi_{m,c},\theta_{m,c}) \triangleq -\frac{2 \pi}{\lambda}\left[\begin{array}{c} \sin\theta_{m,c}\cos\phi_{m,c}\\ \sin\theta_{m,c}\sin\phi_{m,c}\\ \cos\theta_{m,c} \end{array}\right]. \end{align}} The phase profiles of each $m$-th RIS are selected from a set $\mathcal{U}$ with cardinality $K$ such that $\mathbf{u}_{m,k}\in \mathcal{U}$ $\forall$$k=1,2,\ldots,K$. Note that, in general, $K$ may be larger or smaller than $T$. Assuming that $b$ is the phase resolution in bits per RIS phase-tunable unit element, we consider the $2^{b}$-element discrete set $\mathcal{F}\triangleq\{\exp\left(\jmath2^{1-b}\pi f\right)\}^{2^{b}-1}_{f=0}$ for the elements $[\mathbf{u}_{m,k}]_\ell$ $\forall m,k,\ell$, which results in a total of $K=2^{bL}$ phase profiles. \vspace{-2mm} \section{Proposed RIS-Enabled Localization Method} The proposed localization method comprises two stages: \textit{i}) AoA estimation {of the LOS channel component} in azimuth and elevation from each RIS; and \textit{ii}) user position estimation, by fusing the AoA measurements {of the LOS channel} from the individual RISs. {For the former stage, we apply a beamspace version of the Orthogonal Matching Pursuit (OMP) algorithm \cite{wu2013Support,wang2015Support}, which will be shown to perform accurate AoA estimations with relatively small values for $T$. The second stage for user localization is based on an ML approach, which is initialized with a line intersection technique that is based on the Least Squares (LS) criterion.} In terms of system architecture, we assume that the baseband measurements at the outputs of each RIS's RX RF chain are collected by a central controller or location server. This device can then estimate the AoA of the transmitted signal's {LOS component} at each RIS, and then, fuse all those $M$ AoA estimates to obtain the user position estimation, as will be detailed in the next section. It is noted that the AoA estimation can be performed at any RIS side at the cost of basic storage and computing capability. \vspace{-2mm} \subsection{AoA Estimation from Each Single-RX-RF RIS} {By stacking the $T$ phase profiles for a symbol observation in the $L\times T$ matrix $\mathbf{U}_m\triangleq[\mathbf{u}_{m,1}\,\mathbf{u}_{m,2}\,\cdots\,\mathbf{u}_{m,T}]$, we obtain the following $T$-element column vector using expression \eqref{eq:ObservedSignalmthRIS}: \begin{align}\label{eq:Rx_signal2} \mathbf{y}_{m} \triangleq \mathbf{U}_m^{\rm H}\sum_{c=1}^{C_m}h_{m,c}\boldsymbol{\alpha}\left(\phi_{m,c},\theta_{m,c}\right)s+\tilde{\mathbf{w}}_{m}, \end{align} where $\tilde{\mathbf{w}}_{m}\triangleq[\mathbf{u}_{m,1}^{\rm H}\mathbf{w}_{m,1}\,\mathbf{u}_{m,2}^{\rm H}\mathbf{w}_{m,2}\,\ldots\,\mathbf{u}_{m,T}^{\rm H}\mathbf{w}_{m,T}]^{\rm{T}}$.} {We next use the matrix $\boldsymbol{\Psi}\triangleq\mathbf{U}_m^{\rm H}\mathbf{A}\in\mathbb{C}^{T\times J}$ with $J\gg T$, where $\mathbf{A}\triangleq[\mathbf{a}(\bar{\phi}_1,\bar{\theta}_1)\,\mathbf{a}(\bar{\phi}_2,\bar{\theta}_2)\,\cdots\,\mathbf{a}(\bar{\phi}_{J},\bar{\theta}_{J})]\in\mathbb{C}^{L\times J}$ is a dictionary matrix with the spatial response vectors at the azimuth and elevation AoA pairs $(\bar{\phi}_j,\bar{\theta}_j)$ $\forall$$j=1,2,\ldots,J$, to approximate the received symbol vector at each $m$-th RIS as: \begin{equation}\label{eq:CS} \mathbf{y}_{m}\approx\boldsymbol{\Psi}\mathbf{x}_{m}+\tilde{\mathbf{w}}_{m}, \end{equation} where $\mathbf{x}_{m}\in\mathbb{C}^{J\times 1}$ is an approximately $C_{m}$-sparse vector including the gains of all channel paths via which the user's signal reaches the RIS. The latter formulation enables the deployment of compressed sensing tools for estimating $\mathbf{x}_{m}$, i.e., the AoAs and gains of all channel paths. In this paper, we deploy the OMP algorithm \cite{wu2013Support} to estimate $\phi_{m,1}$ and $\theta_{m,1}$ of the LOS channel, which will be then used for position estimation. This estimation can be obtained by running OMP with sparsity level $1$, when LOS is the strongest channel component. Otherwise, the support of $\mathbf{x}_{m}$ needs to be estimated, and then combined with a data association approach for estimating the LOS component.} \begin{rem} To recover the LOS component with the presented OMP, the measurement matrix $\boldsymbol{\Psi}$ needs to satisfy the first-order restricted isometry property \cite{wang2015Support}. One option for meeting this property is when $\boldsymbol{\Psi}$ is the Discrete Fourier Transform (DFT) matrix. In this paper, given the spatial response dictionary $\mathbf{A}$, we choose $\mathbf{U}_m$ as the DFT matrix, i.e., it must hold $T=L$, as well as a partial DFT matrix consisting of $T<L$ columns from the DFT matrix {\cite{candescompressed2011}}. For both cases, the elements of $\mathbf{U}_m$ for $\ell=1,2,\dots,L$ and $t=1,2,\dots,T$ are given by the following expression: \begin{equation}\label{eq:dft} [\mathbf{U}_m]_{\ell,t}=\frac{1}{\sqrt{L}}\exp\Big(-\frac{\jmath2\pi}{L}(\ell-1)(t-1)\Big). \end{equation} \end{rem} { \begin{rem} The AoA estimation performance of OMP can be improved by increasing the number of transmissions $T$, which proportionally increases the integrated SNR \end{rem}} \vspace{-2mm} \subsection{Centralized ML-Based Position Estimation} Given the known coordinates $\mathbf{p}_m=\left[x_m\;y_m\;z_m\right]^{\rm T}$ of the reference point at the $m$-th RIS as well as {the estimates $\hat{\phi}_{m,1}$ and $\hat{\theta}_{m,1}$ of the LOS AoAs $\phi_{m,1}$ and $\theta_{m,1}$}, the line where the single source lies can be estimated for each $m$-th RIS. Each point $\boldsymbol{\xi}\triangleq\left[x\;y\;z\right]^{\rm T}$ in this line can be obtained for $k\in\mathbb{R}$ as: \begin{equation} \boldsymbol{\xi}=\mathbf{p}_m+k\mathbf{v}_m, \end{equation} where $\mathbf{v}_m\in\mathbb{R}^{3\times1}$ is the direction vector, which is defined as {\begin{equation} \mathbf{v}_m\triangleq\left[\begin{array}{c} \sin{(\hat\theta_{m,1})}\cos{(\hat\phi_{m,1}+\beta_{m,1})}\\ \sin{(\hat\theta_{m,1})}\sin{(\hat\phi_{m,1}+\beta_{m,1})}\\ \cos{(\hat\theta_{m,1})} \end{array}\right]. \end{equation}} By assuming that the controller in the considered system model possesses all $M$ $\mathbf{p}_m$'s and calculates all $M$ angle pairs {$(\hat{\phi}_{m,1},\hat{\theta}_{m,1})$}, it is proposed to compute the estimation for the unknown position $\mathbf{p}$, as follows. The sum of the squared distances between the source and each of the $M$ estimated lines is given as a function of $\mathbf{p}$ by the expression \cite{dupre1992distance}: \begin{equation}\label{eq:LS_Distances} D(\mathbf{p})\triangleq\sum_{m=1}^{M}\left(\mathbf{p}_m-\mathbf{p}\right)^{\rm T}\mathbf{B}_m\left(\mathbf{p}_m-\mathbf{p}\right), \end{equation} where $\mathbf{B}_m\triangleq\mathbf{I}_3-\mathbf{v}_m\mathbf{v}_m^{\rm T}$. The estimation of the unknown $\mathbf{p}$ that minimizes this LS problem can be easily obtained as \begin{equation}\label{eq:intersection} \hat{\mathbf{p}}_{\text{LS}} = \Big(\sum_{m=1}^{M}\mathbf{B}_m\Big)^{-1}\Big(\sum_{m=1}^{M}\mathbf{B}_m\mathbf{p}_m\Big). \end{equation} The Root Mean Squared Error (RMSE) using the LS-based intersection of skew lines can be, in general, larger than the PEB, since all AoA estimates are treated equally. This fact may result in poor position estimation performance, if any or some of the $M$ AoA estimates is of poor quality. We next consider uncertainty in the AoA estimates to refine the position estimate. In particular, the estimation of AoAs for each $m$-th RIS can be expressed in the following form: {\begin{equation} \hat{\mathbf{{y}}}_m\left(\mathbf{p}\right)\triangleq\begin{bmatrix} \hat{\theta}_{m,1}\\ \hat{\phi}_{m,1} \end{bmatrix} = \begin{bmatrix} \theta_{m,1}\\ \phi_{m,1} \end{bmatrix}+\mathbf{z}_m=f_m\left(\mathbf{p}\right) + \mathbf{z}_m, \end{equation} where $f_m\left(\mathbf{p}\right)$ is a $2\times 1$ vector containing the azimuth and elevation angles with respect to the $m$-th RIS; this is a non-linear function of $\mathbf{p}$.} In addition, $\mathbf{z}_m\sim\mathcal{N}(0,\mathbf{G}_m)$ is a $2\times 1$ vector modeling the estimation errors for the AoAs. Given this uncertainty model, the ML estimation of the single transmitting user position, $\hat{\mathbf{p}}_{\rm ML}$, is obtained as follows: \begin{equation}\label{eq:ML} \begin{split} \hat{\mathbf{{p}}}_{\rm ML}\!\!\triangleq\!\operatorname*{argmin}_{\mathbf{p}}\! \sum^M_{m=1}[\hat{\mathbf{{y}}}_m\left(\mathbf{p}\right)-f_m\left(\mathbf{p}\right)]^{\rm{T}}\mathbf{G}^{-1}_m[\hat{\mathbf{y}}_m\left(\mathbf{p}\right)-f_m\left(\mathbf{p}\right)]. \end{split} \end{equation} This optimization problem does not possess a closed-form solution. We hence propose to solve it via any gradient-descent method using the LS-based position estimation in \eqref{eq:intersection}, as the initialization step. To determine each of the $2\times2$ covariance matrices $\mathbf{G}_m$ in \eqref{eq:ML} and establish a fundamental performance bound, we will next rely on a Fisher information analysis. \vspace{-4mm} \subsection{Fisher Information Analysis} \subsubsection{LOS Channel Parameters} {Let the vector $\bm{\eta}_m\triangleq\left[\sqrt{P_{L_{m,1}}}\;\varphi_m\;\phi_{m,1}\;\theta_{m,1}\right]^{\rm T}\in\mathbb{R}^{4\times1}$ include the unknown system parameters in \eqref{eq:ObservedSignalmthRIS}, referring to the received signal model via the LOS component at each $m$-th RIS. The $4\times4$ Fisher Information Matrix (FIM) for this unknown vector, based on the observation model in expression \eqref{eq:ObservedSignalmthRIS} when excluding the non-LOS channel paths, is defined as follows \cite{Kay97}:} \begin{equation}\label{eq:FIM_Initial} \mathbf{J}\left(\bm{\eta}_m\right)=\frac{2}{\rho}\sum_{t=1}^T\Re\left\{\left(\frac{\partial\mu_{m,t}}{\partial\bm{\eta}_m}\right)^{\rm H}\frac{\partial\mu_{m,t}}{\partial\bm{\eta}_m}\right\}, \end{equation} where {the function $\mu_{m,t}$ of the unknown vector $\bm{\eta}_m$ is defined as $\mu_{m,t} \triangleq \sqrt{P_{L_{m,1}}}\exp\left(j\varphi_{m}\right)\mathbf{u}_{m,t}^{\rm H}\boldsymbol{\alpha}\left(\phi_{m,1},\theta_{m,1}\right)s$, representing} the noiseless received signal at the $t$-th slot at the $m$-th RIS. Using Schur's complement, the Fisher information for the unknown AoAs {$\phi_{m,1}$ and $\theta_{m,1}$} can be computed as: {\begin{align} & \mathbf{G}^{-1}_m = \mathbf{J}\left(\phi_{m,1},\theta_{m,1}\right)=\left[\mathbf{J}(\bm{\eta}_{m})\right]_{3:4,3:4} \notag \\ & -\left[\mathbf{J}(\bm{\eta}_{m})\right]_{3:4,1:2}\left[\mathbf{J}(\bm{\eta}_{m})\right]_{1:2,1:2}^{-1}\left[\mathbf{J}(\bm{\eta}_{m})\right]_{1:2,3:4}. \label{eq:fim_schur} \end{align}} \subsubsection{Positioning} The Fisher information for each $m$-th RISs can be used for expressing the $3\times3$ FIM for the unknown position $\mathbf{p}$ as follows \cite{Kay97}: {\begin{equation}\label{eq:fim_position} \mathbf{J}\left(\mathbf{p}\right)=\sum_{m=1}^M\mathbf{T}_m\mathbf{J}\left(\phi_{m,1},\theta_{m,1}\right)\mathbf{T}_m^{\rm T}, \end{equation} where $\mathbf{T}_m\in\mathbb{R}^{3\times2}$ denotes the Jacobian $\mathbf{T}_m\triangleq[\frac{\partial\theta_{m,1}}{\partial\mathbf{p}} \frac{\partial\phi_{m,1}}{\partial\mathbf{p}}]$}. The derivatives needed for this Fisher information of the unknown AoAs and source position are given in the Appendix. The FIM for the unknown source position $\mathbf{p}$ can be finally used for computing the PEB, as follows: \begin{equation}\label{eq:peb} {\rm PEB}\triangleq\sqrt{{\rm Tr}\left\{\mathbf{J}^{-1}\left(\mathbf{p}\right)\right\}}\leq\sqrt{\mathbb{E}\left\{\left\|\hat{\mathbf{ p}}-\mathbf{p}\right\|^2\right\}}, \end{equation} which can serve as a lower bound for the RMSE of the position estimation $\mathbf{\hat p}$ for $\mathbf{p}$, when considering the model of Section~\ref{sec:System_Model}. \begin{rem} The bound in \eqref{eq:peb} is valid even in the presence of multipath, since in this scenario, multipath cannot improve positioning RMSE without data association among the RISs. \end{rem} \vspace{-2mm} \section{Numerical Results} \vspace{-1mm} \subsection{Simulated Scenario} We have considered a cubic room with dimensions $10\,{\rm m}\times 10\,{\rm m}\times 10\,{\rm m}$ and single-RX-RF RISs of half-wavelength, i.e., $\lambda/2$, inter-element spacing operating at $30$ GHz with the noise floor $\rho$ in \eqref{eq:ObservedSignalmthRIS} set to $-79$ dBm. Unless otherwise stated, we have assumed transmit power of $P=10$ dBm, $M=3$ RISs of size $L=8\times 8$, and $T=L$ RIS phase profiles resulting from the DFT beams. The RISs were considered placed on the room's vertical walls as depicted in Fig.~\ref{fig:system_setup}. We have generated a multipath channel with the same number of paths for all RISs (specifically, $C_{m}=3$ $\forall$$m$), comprising a LOS and two non-LOS components with $20$ dB power ratio, using both the far-field model in \eqref{eq:Spatial_response} for the steering vectors as well as a near-field model. For the latter model, we have used {the following formula for the LOS component (the non-LOS channel components were modeled similarly): \begin{equation}\label{eq:Spatial_response2} \left[\boldsymbol{\alpha}\left(\phi_{m,1},\theta_{m,1}\right)\right]_\ell \triangleq \exp\left(-\jmath2 \pi r_{m,1,\ell}/\lambda\right), \end{equation} where $r_{m,1,\ell}\triangleq\Vert \mathbf{p}- \mathbf{p}_{m,\ell}\Vert $} with $\mathbf{p}_{m,\ell}\in\mathbb{R}^{3\times1}$ being the absolute coordinate of the $\ell$-th element of the $m$-th RIS, which can be easily obtained from $\mathbf{q}_{m,\ell}$. It is noted that the proposed positioning techniques in Section~III were derived using \eqref{eq:Spatial_response}, and here, their performance over the multipath channel model resulting from \eqref{eq:Spatial_response2} is also investigated. \begin{figure} \centering \input{fig1_revised.tex} \caption{The empirical CDF of the PEB for various source positions with $z_p=5$ ${\rm m}$ and $P=10$ dBm, as well as $M=3$ RISs each with $L=8\times8$ unit elements. Different RIS placements on the room's walls were considered.} \vspace{-4mm} \label{fig:cdf_plot} \end{figure} \begin{figure} \centering \input{figure_2_camera_ready.tex} \caption{The RMSE of the positioning error in meters versus the number of RIS unit elements $L$, considering pilot symbol transmission with power $P=10$ dBm and the LS-based line intersection technique with $M=3$ RISs placed at $\mathbf{p}_1=[0\,5\,7]^{\rm{T}}$, $\mathbf{p}_2=[5\,0\,1]^{\rm{T}}$, and $\mathbf{p}_3=[10\,6\,8]^{\rm{T}}$. The user was located at the unknown position $\mathbf{p}=[4\,8\,2]^{\rm{T}}$. Different forms of the phase profiles for the RISs have been used.}\vspace{-4mm} \label{fig:rmse} \end{figure} \vspace{-2mm} \subsection{Discussion} \subsubsection{Impact of RISs' Placement on PEB and Coverage} In Fig.~\ref{fig:cdf_plot}, the empirical CDF of the PEB for various source positions with $z_p=5$ ${\rm m}$ and different placements of $3$ RISs with $8\times8$ elements is illustrated. As shown, the placement of the RISs on the room's walls impacts the localization performance of the proposed AoA-based positioning approach. For best overall coverage, placing the RIS on different walls is better, while for best localization performance near a single wall, it is preferred to place the RIS on that same wall. The heights of the placements of the RISs on the wall(s) play only a minor role, though the case of same heights appears better for localization performance, while the case of different heights leads to better overall coverage. \subsubsection{Impact of RISs' Size and Phase Profiles on LS Estimation} The RMSE positioning performance, as defined in \eqref{eq:peb}, is plotted versus $L$ in Fig.~\ref{fig:rmse}, {using the proposed ML positioning technique} in \eqref{eq:ML} for the case of $3$ RISs and various forms for their phase profiles. Specifically, we have considered position estimation with: \textit{i}) $T=L$ phase profiles using the DFT beams {in \eqref{eq:dft} and \textit{ii}) quantized DFT beams with $b=2,3$ according to $\mathcal{F}$} ; \textit{iii}) $T=\lfloor L/3 \rfloor$ of the DFT phase profiles in \textit{i}) pointing around the actual direction of the source with $30^{\degree}$ uncertainty range; \textit{iv}) the $b$-bit quantized versions of the phase profiles in \textit{iii}). % It is evident from the figure that, for all considered RIS phase profiles, the RMSE does not improve drastically with increasing $L$, and that the $T=L$ DFT profiles yield the best performance, with the directional $T\ll L$ DFT profiles requiring less overhead at a cost of a small performance loss. In addition, it is shown that quantization of both DFT and directive beams imposes performance loss, something that is less severe with higher $b$. Hybrid schemes with progressive refinement of the user location could form an interesting compromise between performance (RMSE) and observation latency ($T$). \begin{figure} \centering \input{fig3_revised.tex} \caption{The RMSE of the positioning error in meters versus the source transmit power $P$ in dBm considering $M=3$ and $4$ RISs, each with $L=8\times8$ unit elements, placed at $\mathbf{p}_1=[0\,5\,7]^{\rm{T}}$, $\mathbf{p}_2=[5\,0\,1]^{\rm{T}}$, $\mathbf{p}_3=[10\,6\,8]^{\rm{T}}$, and $\mathbf{p}_4=[4\,10\,6]^{\rm{T}}$. The user was positioned at {$\mathbf{p}=[4\,8\,2]^{\rm{T}}$ and $64$ quantized DFT phase profiles were used for each RIS. The proposed ML-based position technique was evaluated along with the PEB, considering both the Far-Field (FF) and Near-Field (NF) channel models.}} \vspace{-4mm} \label{fig:tr_power} \end{figure} \subsubsection{Impact of Number of RISs and Channel Model on Estimation Performance} The RMSE of the positioning error as a function of $P$ in dBm, considering $M\in \{3,4\}$ RISs, each with $L=8\times8$ elements and {$T=64$ quantized DFT phase profiles, is illustrated in Fig.~\ref{fig:tr_power}. We have considered the ML positioning technique with the far-field and near-field channel models. In addition, PEB curves are also included under the far-field model. It can be observed that, as expected, the PEB improves with increasing $P$ and $M$. Moreover, the ML-based technique performs sufficiently close to the PEB from low $P$ values. It is also shown for the latter technique that, for $P$ larger than $0$ dBm and the near-field channel model, the RMSE saturates around $0.1$ ${\rm m}$ for both $3$ and $4$ RISs and, for the $4$-RIS case with the far-field channel model, the RMSE saturates around $0.07$ ${\rm m}$. This shows that the ML technique exhibits an error floor due to the model mismatch in the case of the near-field, and due to multipath for the far-field case, but is still able to provide good positioning quality.} \section{Conclusion In this paper, we presented an ML-based localization method with multiple single-RX-RF RISs, which relies on a beamspace OMP technique for AoA estimation and LS-based line intersection. The presented numerical results showcased the accuracy of the proposed method under reasonable operating conditions for strong LOS multipath channels and single-source positioning, verifying our theoretical estimation analysis. We intend to extend the presented localization framework to hybrid RISs \cite{HRIS} and multiple mobile active users. \appendi {Using the notations $\nu\triangleq\phi_{m,1}$ and $\sigma\triangleq\theta_{m,1}$, it follows from the definition of the function ${\mu}_{m,t}$ in \eqref{eq:FIM_Initial} that:} \begin{equation} \frac{\partial {\mu}_{m,t}}{\partial\boldsymbol{\eta}_m}=\begin{bmatrix} \mathbf{u}_{m,t}^{\rm H}\boldsymbol{\alpha}\left(\nu,\sigma\right)\\ \jmath\sqrt{P_{L_{m,1}}}\mathbf{u}_{m,t}^{\rm H}\boldsymbol{\alpha}\left(\nu,\sigma\right)\\ \sqrt{P_{L_{m,1}}}\mathbf{u}_{m,t}^{\rm H}\frac{\partial\boldsymbol{\alpha}\left(\nu,\sigma\right)}{\partial\nu}\\ \sqrt{P_{L_{m,1}}}\mathbf{u}_{m,t}^{\rm H}\frac{\partial\boldsymbol{\alpha}\left(\nu,\sigma\right)}{\partial\sigma} \end{bmatrix}\exp\left(\jmath\varphi_{m}\right)s, \end{equation} where the included partial derivatives are derived as: \begin{equation}\frac{\partial\boldsymbol{\alpha}\left(\nu,\sigma\right)}{\partial\tau}=\exp\left(-\jmath\mathbf{q}^{\rm T}_{m}\mathbf{k}(\nu,\sigma)\right)\odot\jmath\mathbf{q}^{\rm T}_{m}\frac{\partial\mathbf{k}(\nu,\sigma)}{\partial\tau} \end{equation} with $\tau$ being either $\nu$ or $\sigma$ and $\mathbf{q}_{m}\triangleq[\mathbf{q}_{m,1}\,\mathbf{q}_{m,2}\,\cdots\,\mathbf{q}_{m,L}]$. The derivatives with respect to $\nu$ and $\sigma$ are computed as: \begin{equation} \frac{\partial\mathbf{k}(\nu,\sigma)}{\partial\nu}=-\frac{2\pi}{\lambda}\begin{bmatrix} -\sin{\sigma}\cos{\nu}\\ \sin{\sigma}\sin{\nu}\\ 0 \end{bmatrix}, \end{equation} \begin{equation} \frac{\partial\mathbf{k}(\nu,\sigma)}{\partial\sigma}=-\frac{2\pi}{\lambda}\begin{bmatrix} \cos{\sigma}\cos{\nu}\\ \cos{\sigma}\sin{\nu}\\ -\sin{\sigma} \end{bmatrix}. \end{equation} The Jacobian $\mathbf{t}_m$ required in \eqref{eq:fim_position} is calculated, as follows. We express the elevation angle as a function of the coordinates: \begin{equation} \sigma=\arccos\left(\dfrac{z_p-z_m}{\left\|\mathbf{p}-\mathbf{p}_m\right\|}\right), \end{equation} and then calculate the required partial derivative as: \begin{equation} \frac{\partial\sigma}{\partial\mathbf{p}} \triangleq \begin{bmatrix} \frac{\partial\sigma}{\partial x_p}\\ \frac{\partial\sigma}{\partial y_p}\\ \frac{\partial\sigma}{\partial z_p} \end{bmatrix}= \begin{bmatrix} \left(z_p-z_m\right)\left(x_p-x_m\right)(\kappa\chi)^{-1}\\ \left(z_p-z_m\right)\left(y_p-y_m\right)(\kappa\chi)^{-1}\\ \left(\frac{\left(z_p-z_m\right)^2}{\chi}-\frac{1}{\left\|\mathbf{p}-\mathbf{p}_m\right\|_2}\right)\kappa^{-1} \end{bmatrix}, \end{equation} where $\kappa\triangleq\sqrt{1-\frac{\left(z_p-z_m\right)^2}{\left\|\mathbf{p}-\mathbf{p}_m\right\|^2}}$ and $\chi\triangleq\left\|\mathbf{p}-\mathbf{p}_m\right\|^3$. The partial derivative of $\nu$ is obtained in a similar manner. \bibliographystyle{IEEEtran} \section{Introduction} Reconfigurable Intelligent Surfaces (RISs) \cite{huang2019reconfigurable} are lately gaining increased interest as a cost- and power-efficient means to enable programmable wireless signal propagation environments \cite{rise6g}. Due to their minimal hardware footprint, they are envisioned to coat available surfaces or objects in the wireless medium, offering extra degrees of freedom for diverse communication, localization, and sensing improvements. RISs are artificially planar structures usually consisting of multiple unit elements (of half- or even sub-wavelength inter-element spacing), whose reflection behavior can be adjusted to finite discrete states \cite{huang2019holographic}. The dynamic configuration of RISs is handled by dedicated controllers connected to them, while lately RIS hardware architectures including small numbers of Radio Frequency (RF) chains are being proposed \cite{George_RIS_2020,shlezinger2020dynamic,HRIS}, facilitating several RIS-enabled network management tasks. Among the possible functionalities, where RISs can have a significant contribution, belong the high-accuracy localization. This feature constitutes one of the key requirements for fifth Generation (5G), and beyond, wireless networks \cite{Positioning_5G_NR}. An overview of the main challenges and opportunities for localization and mapping with RIS-empowered wireless systems is provided in \cite{wymeersch2019radio}. Considering passive RISs with no active RF chains and quantized phase profiles in \cite{he2020large}, the Cram\'{e}r-Rao lower bound for RIS-based positioning in millimeter Wave (mmWave) Multiple-Input Multiple-Output (MIMO) systems was presented. For the same systems, an adaptive hierarchical codebook for positioning and data transmission was designed in \cite{he2020adaptive}. A supervised learning approach for wave fingerprinting was proposed in \cite{alexandg_2021} for localizing non-cooperative objects in rich scattering RIS-empowered wireless systems. Simultaneous localization and mapping enabled by passive RISs was proposed in \cite{yang2021wireless}. In \cite{keykhosravi2020siso}, a joint three-dimensional localization and synchronization approach for a single-input single-output system empowered by an RIS was designed. In addition to the above works on RISs without RF chains, \cite{shaban2020nearfield} exploited wavefront curvature for positioning, by utilizing RIS-based lenses with a single RF chain for reception. In this paper, motivated by the recent interest in RISs with basic sensing capability \cite{George_RIS_2020,HRIS}, we design a novel user localization method realized with multiple RISs, each equipped with a single Receive (RX) RF chain. Assuming that each meta-atom element of an RIS is coupled with a waveguide and that all waveguide outputs are fed to the RF chain \cite{George_RIS_2020,shlezinger2020dynamic}, we present the following contributions: \emph{i)} We design an Angle-of-Arrival (AoA) estimation technique for single-RX-RF RISs, which is based on collected measurements using multiple RIS phase profiles. \emph{ii)} We capitalize on the AoA estimations from multiple RISs for a source of interest and present a Maximum Likelihood (ML) localization algorithm that is based on a line intersection technique. \emph{iii)} We also derive the Position Error Bounds (PEBs) for the unknown parameters and provide numerical results that demonstrate the accuracy of the proposed localization for various system parameters, including different RIS codebooks, different quantization of RIS phase profiles, and different RIS placements, as well as under near- and far-field conditions. \subsubsection*{Notations} Vectors and matrices are denoted by boldface lowercase and boldface capital letters, respectively. The transpose, Hermitian transpose, and inverse of $\mathbf{A}$ are denoted by $\mathbf{A}^{\rm T}$, $\mathbf{A}^{\rm H}$, and $\mathbf{A}^{-1}$, respectively, while $\mathbf{I}_{n}$ ($n\geq2$) is the $n\times n$ identity matrix and $\mathbf{0}_{n\times m}$ ($n,m\geq1$) is an $n\times m$ matrix with zeros. ${\rm Tr}\{\mathbf{A}\}$ represents $\mathbf{A}$'s trace and $[\mathbf{A}]_{i,j}$ denotes its $(i,j)$-th element, while $[\mathbf{A}]_{:,i:j}$ is a submatrix of $\mathbf{A}$ including all rows of $\mathbf{A}$ and columns from the $i$-th up to the $j$-th. The Euclidean norm of $\mathbf{a}$ is denoted by $\left\|\mathbf{a}\right\|$ and $\odot$ is the matrix Hadamard product. $\mathbb{R}$ and $\mathbb{C}$ represent the real and complex number sets, respectively, and $\Re\left\{\cdot\right\}$ gives the real part of a complex matrix. $\mathbb{E}\{\cdot\}$ is the expectation operator, and $\mathbf{x}\sim\mathcal{CN}(\mathbf{a},\mathbf{A})$ indicates a complex Gaussian random vector with mean $\mathbf{a}$ and covariance matrix $\mathbf{A}$. Finally, $x\sim\mathcal{U}(a,b)$ denotes a uniformly distributed random variable in the interval $[a,b]$, and $\jmath\triangleq\sqrt{-1}$ is the imaginary unit. \vspace{-2mm} \section{System Model}\label{sec:System_Model} \begin{figure}[!t] \centering \includegraphics[trim=7cm 1.5cm 1.8cm 5cm, width=1\columnwidth]{Figures/SystemV4.pdf} \caption{The considered indoor setup with $M$ single-RX-RF RISs, each with $L$ elements, for the localization of a transmitting user at the unknown position $[x_p\,y_p\,z_p]^{\rm T}$. The position $[x_m\,y_m\,z_m]^{\rm T}$, with $m=1,2,\ldots,M$, of the reference unit element at each $m$-th RIS is assumed to be known.}\vspace{-0.4cm} \label{fig:system_setup} \end{figure} We consider the indoor environment of Fig.~\ref{fig:system_setup} comprising $M\ge2$ RISs, which are attached to the room's walls and are themselves planar and perpendicular to the floor. Each RIS consists of $L$ phase-tunable meta-atom elements and is implemented with the single-RX-RF architecture of \cite{George_RIS_2020}. There is a global coordinate system, where the reference point of each $m$-th RIS, with $m=1,2,\ldots,M$, is given by $\mathbf{p}_m\triangleq\left[x_m\;y_m\;z_m\right]^{\rm T}$ and its orientation (in terms of the azimuth angle) is represented by the parameter $\beta_m$. All RISs are assumed to be connected to the same central controller. Finally, a transmitting single-antenna user (the source) is located at the unknown position $\mathbf{p}\triangleq\left[x_p\;y_p\;z_p\right]^{\rm T}$. {It is noted that a similar system model can be considered for outdoor environments, where RISs can be deployed for coating, for example, building facades. This paper's localization method can be equally applied for such a system model.} {We assume that the user broadcasts a pilot symbol $s$ with constant transmit power $P$. This symbol is received $T$ times by each RIS, where during each repetition a different RIS phase profile is used. Under far-field signal propagation and in the presence of $C_{m}$ distinct channel paths, the observation during the $t$-th reception slot} ($t=1,2,\ldots,T$) at each $m$-th RIS's RX RF chain output can be mathematically expressed as follows: {\begin{align} y_{m,t}\triangleq \mathbf{u}_{m,t}^{\rm H}\sum_{c=1}^{C_{m}} h_{m,c}\boldsymbol{\alpha}\left(\phi_{m,c},\theta_{m,c}\right)s+\mathbf{u}_{m,t}^{\rm H}\mathbf{w}_{m,t}, \label{eq:ObservedSignalmthRIS} \end{align} where $h_{m,c}\triangleq\sqrt{P_{L_{m,c}}}\exp\left(\jmath\varphi_{m}\right)$ $\forall$$c=1,2,\ldots,C_m$ includes the gain of the $c$-th signal propagation path with parameter $P_{L_{m,c}}\triangleq\lambda^2/\left(4\pi r_{m,c}\right)^2$ denoting the free-space pathloss, where $\lambda$ is the signal wavelength. Without loss of generality, we assume that the $c=1$ channel path represents the Line-Of-Sight (LOS), hence, its pathloss $P_{L_{m,1}}$ depends on the Euclidean distance $r_{m,1}\triangleq\|\mathbf{p}_m-\mathbf{p}\|$; each distance $r_{m,c}$ for $c\geq2$ is defined similarly considering the position of the corresponding scatterer. In the expression for $h_{m,c}$, $\varphi_m\sim\mathcal{U}(0,2\pi)$ denotes a global phase offset accounting for the lack of phase synchronization between the user and the RF chain of the $m$-th RIS.} The vector $\mathbf{u}_{m,t}\in\mathbb{C}^{L\times 1}$ is the $t$-th phase configuration (among the total $T$ used) of the $m$-th RIS. The vector $\mathbf{w}_{m,t}\in\mathbb{C}^{L\times 1}$ in \eqref{eq:ObservedSignalmthRIS} represents the Additive White Gaussian Noise (AWGN) that is distributed as $\mathcal{CN}(\mathbf{0},\rho\mathbf{I}_L)$. {Finally, the spatial response vector $\boldsymbol{\alpha}\left(\phi_{m,c}, \theta_{m,c}\right)\in\mathbb{C}^{L\times1}$ for the azimuth and elevation AoAs $\phi_{m,c}\in\left[0,2\pi\right]$ and $\theta_{m,c}\in\left[0,\pi\right]$, respectively, of the user transmitted signal via multipath propagation, with respect to the coordinate system having as origin the point $\mathbf{p}_m$ (i.e., the reference point of the $m$-th RIS), is given for $\ell=1,2,\ldots,L$ as follows: \begin{equation}\label{eq:Spatial_response} \left[\boldsymbol{\alpha}\left(\phi_{m,c},\theta_{m,c}\right)\right]_\ell \triangleq \exp\left(-\jmath\mathbf{q}^{\rm T}_{m,\ell}\mathbf{k}(\phi_{m,c},\theta_{m,c})\right), \end{equation} where $\mathbf{q}_{m,\ell}\in\mathbb{R}^{3\times1}$ denotes the position of the $\ell$-th element of the $m$-th RIS and $\mathbf{k}(\phi_{m,c}\theta_{m,c})\in\mathbb{R}^{3\times1}$ is the wavevector at these respective AoAs, which is mathematically defined as: \begin{align} \mathbf{k}(\phi_{m,c},\theta_{m,c}) \triangleq -\frac{2 \pi}{\lambda}\left[\begin{array}{c} \sin\theta_{m,c}\cos\phi_{m,c}\\ \sin\theta_{m,c}\sin\phi_{m,c}\\ \cos\theta_{m,c} \end{array}\right]. \end{align}} The phase profiles of each $m$-th RIS are selected from a set $\mathcal{U}$ with cardinality $K$ such that $\mathbf{u}_{m,k}\in \mathcal{U}$ $\forall$$k=1,2,\ldots,K$. Note that, in general, $K$ may be larger or smaller than $T$. Assuming that $b$ is the phase resolution in bits per RIS phase-tunable unit element, we consider the $2^{b}$-element discrete set $\mathcal{F}\triangleq\{\exp\left(\jmath2^{1-b}\pi f\right)\}^{2^{b}-1}_{f=0}$ for the elements $[\mathbf{u}_{m,k}]_\ell$ $\forall m,k,\ell$, which results in a total of $K=2^{bL}$ phase profiles. \vspace{-2mm} \section{Proposed RIS-Enabled Localization Method} The proposed localization method comprises two stages: \textit{i}) AoA estimation {of the LOS channel component} in azimuth and elevation from each RIS; and \textit{ii}) user position estimation, by fusing the AoA measurements {of the LOS channel} from the individual RISs. {For the former stage, we apply a beamspace version of the Orthogonal Matching Pursuit (OMP) algorithm \cite{wu2013Support,wang2015Support}, which will be shown to perform accurate AoA estimations with relatively small values for $T$. The second stage for user localization is based on an ML approach, which is initialized with a line intersection technique that is based on the Least Squares (LS) criterion.} In terms of system architecture, we assume that the baseband measurements at the outputs of each RIS's RX RF chain are collected by a central controller or location server. This device can then estimate the AoA of the transmitted signal's {LOS component} at each RIS, and then, fuse all those $M$ AoA estimates to obtain the user position estimation, as will be detailed in the next section. It is noted that the AoA estimation can be performed at any RIS side at the cost of basic storage and computing capability. \vspace{-2mm} \subsection{AoA Estimation from Each Single-RX-RF RIS} {By stacking the $T$ phase profiles for a symbol observation in the $L\times T$ matrix $\mathbf{U}_m\triangleq[\mathbf{u}_{m,1}\,\mathbf{u}_{m,2}\,\cdots\,\mathbf{u}_{m,T}]$, we obtain the following $T$-element column vector using expression \eqref{eq:ObservedSignalmthRIS}: \begin{align}\label{eq:Rx_signal2} \mathbf{y}_{m} \triangleq \mathbf{U}_m^{\rm H}\sum_{c=1}^{C_m}h_{m,c}\boldsymbol{\alpha}\left(\phi_{m,c},\theta_{m,c}\right)s+\tilde{\mathbf{w}}_{m}, \end{align} where $\tilde{\mathbf{w}}_{m}\triangleq[\mathbf{u}_{m,1}^{\rm H}\mathbf{w}_{m,1}\,\mathbf{u}_{m,2}^{\rm H}\mathbf{w}_{m,2}\,\ldots\,\mathbf{u}_{m,T}^{\rm H}\mathbf{w}_{m,T}]^{\rm{T}}$.} {We next use the matrix $\boldsymbol{\Psi}\triangleq\mathbf{U}_m^{\rm H}\mathbf{A}\in\mathbb{C}^{T\times J}$ with $J\gg T$, where $\mathbf{A}\triangleq[\mathbf{a}(\bar{\phi}_1,\bar{\theta}_1)\,\mathbf{a}(\bar{\phi}_2,\bar{\theta}_2)\,\cdots\,\mathbf{a}(\bar{\phi}_{J},\bar{\theta}_{J})]\in\mathbb{C}^{L\times J}$ is a dictionary matrix with the spatial response vectors at the azimuth and elevation AoA pairs $(\bar{\phi}_j,\bar{\theta}_j)$ $\forall$$j=1,2,\ldots,J$, to approximate the received symbol vector at each $m$-th RIS as: \begin{equation}\label{eq:CS} \mathbf{y}_{m}\approx\boldsymbol{\Psi}\mathbf{x}_{m}+\tilde{\mathbf{w}}_{m}, \end{equation} where $\mathbf{x}_{m}\in\mathbb{C}^{J\times 1}$ is an approximately $C_{m}$-sparse vector including the gains of all channel paths via which the user's signal reaches the RIS. The latter formulation enables the deployment of compressed sensing tools for estimating $\mathbf{x}_{m}$, i.e., the AoAs and gains of all channel paths. In this paper, we deploy the OMP algorithm \cite{wu2013Support} to estimate $\phi_{m,1}$ and $\theta_{m,1}$ of the LOS channel, which will be then used for position estimation. This estimation can be obtained by running OMP with sparsity level $1$, when LOS is the strongest channel component. Otherwise, the support of $\mathbf{x}_{m}$ needs to be estimated, and then combined with a data association approach for estimating the LOS component.} \begin{rem} To recover the LOS component with the presented OMP, the measurement matrix $\boldsymbol{\Psi}$ needs to satisfy the first-order restricted isometry property \cite{wang2015Support}. One option for meeting this property is when $\boldsymbol{\Psi}$ is the Discrete Fourier Transform (DFT) matrix. In this paper, given the spatial response dictionary $\mathbf{A}$, we choose $\mathbf{U}_m$ as the DFT matrix, i.e., it must hold $T=L$, as well as a partial DFT matrix consisting of $T<L$ columns from the DFT matrix {\cite{candescompressed2011}}. For both cases, the elements of $\mathbf{U}_m$ for $\ell=1,2,\dots,L$ and $t=1,2,\dots,T$ are given by the following expression: \begin{equation}\label{eq:dft} [\mathbf{U}_m]_{\ell,t}=\frac{1}{\sqrt{L}}\exp\Big(-\frac{\jmath2\pi}{L}(\ell-1)(t-1)\Big). \end{equation} \end{rem} { \begin{rem} The AoA estimation performance of OMP can be improved by increasing the number of transmissions $T$, which proportionally increases the integrated SNR \end{rem}} \vspace{-2mm} \subsection{Centralized ML-Based Position Estimation} Given the known coordinates $\mathbf{p}_m=\left[x_m\;y_m\;z_m\right]^{\rm T}$ of the reference point at the $m$-th RIS as well as {the estimates $\hat{\phi}_{m,1}$ and $\hat{\theta}_{m,1}$ of the LOS AoAs $\phi_{m,1}$ and $\theta_{m,1}$}, the line where the single source lies can be estimated for each $m$-th RIS. Each point $\boldsymbol{\xi}\triangleq\left[x\;y\;z\right]^{\rm T}$ in this line can be obtained for $k\in\mathbb{R}$ as: \begin{equation} \boldsymbol{\xi}=\mathbf{p}_m+k\mathbf{v}_m, \end{equation} where $\mathbf{v}_m\in\mathbb{R}^{3\times1}$ is the direction vector, which is defined as {\begin{equation} \mathbf{v}_m\triangleq\left[\begin{array}{c} \sin{(\hat\theta_{m,1})}\cos{(\hat\phi_{m,1}+\beta_{m,1})}\\ \sin{(\hat\theta_{m,1})}\sin{(\hat\phi_{m,1}+\beta_{m,1})}\\ \cos{(\hat\theta_{m,1})} \end{array}\right]. \end{equation}} By assuming that the controller in the considered system model possesses all $M$ $\mathbf{p}_m$'s and calculates all $M$ angle pairs {$(\hat{\phi}_{m,1},\hat{\theta}_{m,1})$}, it is proposed to compute the estimation for the unknown position $\mathbf{p}$, as follows. The sum of the squared distances between the source and each of the $M$ estimated lines is given as a function of $\mathbf{p}$ by the expression \cite{dupre1992distance}: \begin{equation}\label{eq:LS_Distances} D(\mathbf{p})\triangleq\sum_{m=1}^{M}\left(\mathbf{p}_m-\mathbf{p}\right)^{\rm T}\mathbf{B}_m\left(\mathbf{p}_m-\mathbf{p}\right), \end{equation} where $\mathbf{B}_m\triangleq\mathbf{I}_3-\mathbf{v}_m\mathbf{v}_m^{\rm T}$. The estimation of the unknown $\mathbf{p}$ that minimizes this LS problem can be easily obtained as \begin{equation}\label{eq:intersection} \hat{\mathbf{p}}_{\text{LS}} = \Big(\sum_{m=1}^{M}\mathbf{B}_m\Big)^{-1}\Big(\sum_{m=1}^{M}\mathbf{B}_m\mathbf{p}_m\Big). \end{equation} The Root Mean Squared Error (RMSE) using the LS-based intersection of skew lines can be, in general, larger than the PEB, since all AoA estimates are treated equally. This fact may result in poor position estimation performance, if any or some of the $M$ AoA estimates is of poor quality. We next consider uncertainty in the AoA estimates to refine the position estimate. In particular, the estimation of AoAs for each $m$-th RIS can be expressed in the following form: {\begin{equation} \hat{\mathbf{{y}}}_m\left(\mathbf{p}\right)\triangleq\begin{bmatrix} \hat{\theta}_{m,1}\\ \hat{\phi}_{m,1} \end{bmatrix} = \begin{bmatrix} \theta_{m,1}\\ \phi_{m,1} \end{bmatrix}+\mathbf{z}_m=f_m\left(\mathbf{p}\right) + \mathbf{z}_m, \end{equation} where $f_m\left(\mathbf{p}\right)$ is a $2\times 1$ vector containing the azimuth and elevation angles with respect to the $m$-th RIS; this is a non-linear function of $\mathbf{p}$.} In addition, $\mathbf{z}_m\sim\mathcal{N}(0,\mathbf{G}_m)$ is a $2\times 1$ vector modeling the estimation errors for the AoAs. Given this uncertainty model, the ML estimation of the single transmitting user position, $\hat{\mathbf{p}}_{\rm ML}$, is obtained as follows: \begin{equation}\label{eq:ML} \begin{split} \hat{\mathbf{{p}}}_{\rm ML}\!\!\triangleq\!\operatorname*{argmin}_{\mathbf{p}}\! \sum^M_{m=1}[\hat{\mathbf{{y}}}_m\left(\mathbf{p}\right)-f_m\left(\mathbf{p}\right)]^{\rm{T}}\mathbf{G}^{-1}_m[\hat{\mathbf{y}}_m\left(\mathbf{p}\right)-f_m\left(\mathbf{p}\right)]. \end{split} \end{equation} This optimization problem does not possess a closed-form solution. We hence propose to solve it via any gradient-descent method using the LS-based position estimation in \eqref{eq:intersection}, as the initialization step. To determine each of the $2\times2$ covariance matrices $\mathbf{G}_m$ in \eqref{eq:ML} and establish a fundamental performance bound, we will next rely on a Fisher information analysis. \vspace{-4mm} \subsection{Fisher Information Analysis} \subsubsection{LOS Channel Parameters} {Let the vector $\bm{\eta}_m\triangleq\left[\sqrt{P_{L_{m,1}}}\;\varphi_m\;\phi_{m,1}\;\theta_{m,1}\right]^{\rm T}\in\mathbb{R}^{4\times1}$ include the unknown system parameters in \eqref{eq:ObservedSignalmthRIS}, referring to the received signal model via the LOS component at each $m$-th RIS. The $4\times4$ Fisher Information Matrix (FIM) for this unknown vector, based on the observation model in expression \eqref{eq:ObservedSignalmthRIS} when excluding the non-LOS channel paths, is defined as follows \cite{Kay97}:} \begin{equation}\label{eq:FIM_Initial} \mathbf{J}\left(\bm{\eta}_m\right)=\frac{2}{\rho}\sum_{t=1}^T\Re\left\{\left(\frac{\partial\mu_{m,t}}{\partial\bm{\eta}_m}\right)^{\rm H}\frac{\partial\mu_{m,t}}{\partial\bm{\eta}_m}\right\}, \end{equation} where {the function $\mu_{m,t}$ of the unknown vector $\bm{\eta}_m$ is defined as $\mu_{m,t} \triangleq \sqrt{P_{L_{m,1}}}\exp\left(j\varphi_{m}\right)\mathbf{u}_{m,t}^{\rm H}\boldsymbol{\alpha}\left(\phi_{m,1},\theta_{m,1}\right)s$, representing} the noiseless received signal at the $t$-th slot at the $m$-th RIS. Using Schur's complement, the Fisher information for the unknown AoAs {$\phi_{m,1}$ and $\theta_{m,1}$} can be computed as: {\begin{align} & \mathbf{G}^{-1}_m = \mathbf{J}\left(\phi_{m,1},\theta_{m,1}\right)=\left[\mathbf{J}(\bm{\eta}_{m})\right]_{3:4,3:4} \notag \\ & -\left[\mathbf{J}(\bm{\eta}_{m})\right]_{3:4,1:2}\left[\mathbf{J}(\bm{\eta}_{m})\right]_{1:2,1:2}^{-1}\left[\mathbf{J}(\bm{\eta}_{m})\right]_{1:2,3:4}. \label{eq:fim_schur} \end{align}} \subsubsection{Positioning} The Fisher information for each $m$-th RISs can be used for expressing the $3\times3$ FIM for the unknown position $\mathbf{p}$ as follows \cite{Kay97}: {\begin{equation}\label{eq:fim_position} \mathbf{J}\left(\mathbf{p}\right)=\sum_{m=1}^M\mathbf{T}_m\mathbf{J}\left(\phi_{m,1},\theta_{m,1}\right)\mathbf{T}_m^{\rm T}, \end{equation} where $\mathbf{T}_m\in\mathbb{R}^{3\times2}$ denotes the Jacobian $\mathbf{T}_m\triangleq[\frac{\partial\theta_{m,1}}{\partial\mathbf{p}} \frac{\partial\phi_{m,1}}{\partial\mathbf{p}}]$}. The derivatives needed for this Fisher information of the unknown AoAs and source position are given in the Appendix. The FIM for the unknown source position $\mathbf{p}$ can be finally used for computing the PEB, as follows: \begin{equation}\label{eq:peb} {\rm PEB}\triangleq\sqrt{{\rm Tr}\left\{\mathbf{J}^{-1}\left(\mathbf{p}\right)\right\}}\leq\sqrt{\mathbb{E}\left\{\left\|\hat{\mathbf{ p}}-\mathbf{p}\right\|^2\right\}}, \end{equation} which can serve as a lower bound for the RMSE of the position estimation $\mathbf{\hat p}$ for $\mathbf{p}$, when considering the model of Section~\ref{sec:System_Model}. \begin{rem} The bound in \eqref{eq:peb} is valid even in the presence of multipath, since in this scenario, multipath cannot improve positioning RMSE without data association among the RISs. \end{rem} \vspace{-2mm} \section{Numerical Results} \vspace{-1mm} \subsection{Simulated Scenario} We have considered a cubic room with dimensions $10\,{\rm m}\times 10\,{\rm m}\times 10\,{\rm m}$ and single-RX-RF RISs of half-wavelength, i.e., $\lambda/2$, inter-element spacing operating at $30$ GHz with the noise floor $\rho$ in \eqref{eq:ObservedSignalmthRIS} set to $-79$ dBm. Unless otherwise stated, we have assumed transmit power of $P=10$ dBm, $M=3$ RISs of size $L=8\times 8$, and $T=L$ RIS phase profiles resulting from the DFT beams. The RISs were considered placed on the room's vertical walls as depicted in Fig.~\ref{fig:system_setup}. We have generated a multipath channel with the same number of paths for all RISs (specifically, $C_{m}=3$ $\forall$$m$), comprising a LOS and two non-LOS components with $20$ dB power ratio, using both the far-field model in \eqref{eq:Spatial_response} for the steering vectors as well as a near-field model. For the latter model, we have used {the following formula for the LOS component (the non-LOS channel components were modeled similarly): \begin{equation}\label{eq:Spatial_response2} \left[\boldsymbol{\alpha}\left(\phi_{m,1},\theta_{m,1}\right)\right]_\ell \triangleq \exp\left(-\jmath2 \pi r_{m,1,\ell}/\lambda\right), \end{equation} where $r_{m,1,\ell}\triangleq\Vert \mathbf{p}- \mathbf{p}_{m,\ell}\Vert $} with $\mathbf{p}_{m,\ell}\in\mathbb{R}^{3\times1}$ being the absolute coordinate of the $\ell$-th element of the $m$-th RIS, which can be easily obtained from $\mathbf{q}_{m,\ell}$. It is noted that the proposed positioning techniques in Section~III were derived using \eqref{eq:Spatial_response}, and here, their performance over the multipath channel model resulting from \eqref{eq:Spatial_response2} is also investigated. \begin{figure} \centering \input{fig1_revised.tex} \caption{The empirical CDF of the PEB for various source positions with $z_p=5$ ${\rm m}$ and $P=10$ dBm, as well as $M=3$ RISs each with $L=8\times8$ unit elements. Different RIS placements on the room's walls were considered.} \vspace{-4mm} \label{fig:cdf_plot} \end{figure} \begin{figure} \centering \input{figure_2_camera_ready.tex} \caption{The RMSE of the positioning error in meters versus the number of RIS unit elements $L$, considering pilot symbol transmission with power $P=10$ dBm and the LS-based line intersection technique with $M=3$ RISs placed at $\mathbf{p}_1=[0\,5\,7]^{\rm{T}}$, $\mathbf{p}_2=[5\,0\,1]^{\rm{T}}$, and $\mathbf{p}_3=[10\,6\,8]^{\rm{T}}$. The user was located at the unknown position $\mathbf{p}=[4\,8\,2]^{\rm{T}}$. Different forms of the phase profiles for the RISs have been used.}\vspace{-4mm} \label{fig:rmse} \end{figure} \vspace{-2mm} \subsection{Discussion} \subsubsection{Impact of RISs' Placement on PEB and Coverage} In Fig.~\ref{fig:cdf_plot}, the empirical CDF of the PEB for various source positions with $z_p=5$ ${\rm m}$ and different placements of $3$ RISs with $8\times8$ elements is illustrated. As shown, the placement of the RISs on the room's walls impacts the localization performance of the proposed AoA-based positioning approach. For best overall coverage, placing the RIS on different walls is better, while for best localization performance near a single wall, it is preferred to place the RIS on that same wall. The heights of the placements of the RISs on the wall(s) play only a minor role, though the case of same heights appears better for localization performance, while the case of different heights leads to better overall coverage. \subsubsection{Impact of RISs' Size and Phase Profiles on LS Estimation} The RMSE positioning performance, as defined in \eqref{eq:peb}, is plotted versus $L$ in Fig.~\ref{fig:rmse}, {using the proposed ML positioning technique} in \eqref{eq:ML} for the case of $3$ RISs and various forms for their phase profiles. Specifically, we have considered position estimation with: \textit{i}) $T=L$ phase profiles using the DFT beams {in \eqref{eq:dft} and \textit{ii}) quantized DFT beams with $b=2,3$ according to $\mathcal{F}$} ; \textit{iii}) $T=\lfloor L/3 \rfloor$ of the DFT phase profiles in \textit{i}) pointing around the actual direction of the source with $30^{\degree}$ uncertainty range; \textit{iv}) the $b$-bit quantized versions of the phase profiles in \textit{iii}). % It is evident from the figure that, for all considered RIS phase profiles, the RMSE does not improve drastically with increasing $L$, and that the $T=L$ DFT profiles yield the best performance, with the directional $T\ll L$ DFT profiles requiring less overhead at a cost of a small performance loss. In addition, it is shown that quantization of both DFT and directive beams imposes performance loss, something that is less severe with higher $b$. Hybrid schemes with progressive refinement of the user location could form an interesting compromise between performance (RMSE) and observation latency ($T$). \begin{figure} \centering \input{fig3_revised.tex} \caption{The RMSE of the positioning error in meters versus the source transmit power $P$ in dBm considering $M=3$ and $4$ RISs, each with $L=8\times8$ unit elements, placed at $\mathbf{p}_1=[0\,5\,7]^{\rm{T}}$, $\mathbf{p}_2=[5\,0\,1]^{\rm{T}}$, $\mathbf{p}_3=[10\,6\,8]^{\rm{T}}$, and $\mathbf{p}_4=[4\,10\,6]^{\rm{T}}$. The user was positioned at {$\mathbf{p}=[4\,8\,2]^{\rm{T}}$ and $64$ quantized DFT phase profiles were used for each RIS. The proposed ML-based position technique was evaluated along with the PEB, considering both the Far-Field (FF) and Near-Field (NF) channel models.}} \vspace{-4mm} \label{fig:tr_power} \end{figure} \subsubsection{Impact of Number of RISs and Channel Model on Estimation Performance} The RMSE of the positioning error as a function of $P$ in dBm, considering $M\in \{3,4\}$ RISs, each with $L=8\times8$ elements and {$T=64$ quantized DFT phase profiles, is illustrated in Fig.~\ref{fig:tr_power}. We have considered the ML positioning technique with the far-field and near-field channel models. In addition, PEB curves are also included under the far-field model. It can be observed that, as expected, the PEB improves with increasing $P$ and $M$. Moreover, the ML-based technique performs sufficiently close to the PEB from low $P$ values. It is also shown for the latter technique that, for $P$ larger than $0$ dBm and the near-field channel model, the RMSE saturates around $0.1$ ${\rm m}$ for both $3$ and $4$ RISs and, for the $4$-RIS case with the far-field channel model, the RMSE saturates around $0.07$ ${\rm m}$. This shows that the ML technique exhibits an error floor due to the model mismatch in the case of the near-field, and due to multipath for the far-field case, but is still able to provide good positioning quality.} \section{Conclusion In this paper, we presented an ML-based localization method with multiple single-RX-RF RISs, which relies on a beamspace OMP technique for AoA estimation and LS-based line intersection. The presented numerical results showcased the accuracy of the proposed method under reasonable operating conditions for strong LOS multipath channels and single-source positioning, verifying our theoretical estimation analysis. We intend to extend the presented localization framework to hybrid RISs \cite{HRIS} and multiple mobile active users. \appendi {Using the notations $\nu\triangleq\phi_{m,1}$ and $\sigma\triangleq\theta_{m,1}$, it follows from the definition of the function ${\mu}_{m,t}$ in \eqref{eq:FIM_Initial} that:} \begin{equation} \frac{\partial {\mu}_{m,t}}{\partial\boldsymbol{\eta}_m}=\begin{bmatrix} \mathbf{u}_{m,t}^{\rm H}\boldsymbol{\alpha}\left(\nu,\sigma\right)\\ \jmath\sqrt{P_{L_{m,1}}}\mathbf{u}_{m,t}^{\rm H}\boldsymbol{\alpha}\left(\nu,\sigma\right)\\ \sqrt{P_{L_{m,1}}}\mathbf{u}_{m,t}^{\rm H}\frac{\partial\boldsymbol{\alpha}\left(\nu,\sigma\right)}{\partial\nu}\\ \sqrt{P_{L_{m,1}}}\mathbf{u}_{m,t}^{\rm H}\frac{\partial\boldsymbol{\alpha}\left(\nu,\sigma\right)}{\partial\sigma} \end{bmatrix}\exp\left(\jmath\varphi_{m}\right)s, \end{equation} where the included partial derivatives are derived as: \begin{equation}\frac{\partial\boldsymbol{\alpha}\left(\nu,\sigma\right)}{\partial\tau}=\exp\left(-\jmath\mathbf{q}^{\rm T}_{m}\mathbf{k}(\nu,\sigma)\right)\odot\jmath\mathbf{q}^{\rm T}_{m}\frac{\partial\mathbf{k}(\nu,\sigma)}{\partial\tau} \end{equation} with $\tau$ being either $\nu$ or $\sigma$ and $\mathbf{q}_{m}\triangleq[\mathbf{q}_{m,1}\,\mathbf{q}_{m,2}\,\cdots\,\mathbf{q}_{m,L}]$. The derivatives with respect to $\nu$ and $\sigma$ are computed as: \begin{equation} \frac{\partial\mathbf{k}(\nu,\sigma)}{\partial\nu}=-\frac{2\pi}{\lambda}\begin{bmatrix} -\sin{\sigma}\cos{\nu}\\ \sin{\sigma}\sin{\nu}\\ 0 \end{bmatrix}, \end{equation} \begin{equation} \frac{\partial\mathbf{k}(\nu,\sigma)}{\partial\sigma}=-\frac{2\pi}{\lambda}\begin{bmatrix} \cos{\sigma}\cos{\nu}\\ \cos{\sigma}\sin{\nu}\\ -\sin{\sigma} \end{bmatrix}. \end{equation} The Jacobian $\mathbf{t}_m$ required in \eqref{eq:fim_position} is calculated, as follows. We express the elevation angle as a function of the coordinates: \begin{equation} \sigma=\arccos\left(\dfrac{z_p-z_m}{\left\|\mathbf{p}-\mathbf{p}_m\right\|}\right), \end{equation} and then calculate the required partial derivative as: \begin{equation} \frac{\partial\sigma}{\partial\mathbf{p}} \triangleq \begin{bmatrix} \frac{\partial\sigma}{\partial x_p}\\ \frac{\partial\sigma}{\partial y_p}\\ \frac{\partial\sigma}{\partial z_p} \end{bmatrix}= \begin{bmatrix} \left(z_p-z_m\right)\left(x_p-x_m\right)(\kappa\chi)^{-1}\\ \left(z_p-z_m\right)\left(y_p-y_m\right)(\kappa\chi)^{-1}\\ \left(\frac{\left(z_p-z_m\right)^2}{\chi}-\frac{1}{\left\|\mathbf{p}-\mathbf{p}_m\right\|_2}\right)\kappa^{-1} \end{bmatrix}, \end{equation} where $\kappa\triangleq\sqrt{1-\frac{\left(z_p-z_m\right)^2}{\left\|\mathbf{p}-\mathbf{p}_m\right\|^2}}$ and $\chi\triangleq\left\|\mathbf{p}-\mathbf{p}_m\right\|^3$. The partial derivative of $\nu$ is obtained in a similar manner. \bibliographystyle{IEEEtran}
{'timestamp': '2022-03-01T02:56:19', 'yymm': '2202', 'arxiv_id': '2202.13939', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13939'}
arxiv
\section{Introduction}\label{sec:intro} Drawing samples from a given (often unnormalized) probability density plays a crucial role in many scientific and engineering problems that face uncertainty (either physically or algorithmically). Sampling algorithms are widely used in many areas such as statistical inference/estimation, operations research, physics, biology, and machine learning, etc \cite{bertsimas2004solving,durmus2018efficient,dyer1991random,gelman2013bayesian,kalai2006simulated,kannan1997random,krauth2006statistical,sites2003delimiting}. For instance, in Bayesian inference, one draws samples from the posterior distribution to infer its mean, covariance, or other important statistics. Sampling is also heavily used in molecular dynamics to discover new molecular structures. Over the past decades, many algorithms have been developed for sampling \cite{applegate1991sampling,chen2020fast,dyer1991random,lee2021structured,lee2018convergence,lovasz2006fast,NEURIPS2019_eb86d510}. A widely used framework for sampling from complex distributions is the Markov chain Monte Carlo (MCMC) algorithm \cite{chen2018fast,cheng2018convergence,cheng2018underdamped,durmus2019analysis,durmus2018efficient}. In MCMC, a Markov chain is constructed so that its invariant distribution is the given target distribution we want to sample from. Several widely used MCMC methods include Langevin Monte Carlo (LMC) \cite{dalalyan2017theoretical,grenander1994representations,parisi1981correlation,roberts1996exponential}, Metropolis-adjusted Langevin algorithm (MALA) \cite{bou2013nonasymptotic,roberts2002langevin,roberts1996exponential}, and Hamiltonian Monte Carlo (HMC) \cite{neal2011mcmc}. All these three algorithms use gradient information of the potential (negative log-density) to construct the Markov chain. Recently, many theoretical results (see \cite{chen2020fast,dalalyan2017theoretical,durmus2019analysis,dwivedi2018log,lee2021structured,lee2017eldan,roberts1998optimal,roberts1996exponential} and references therein) have been established to understand the complexities of these MCMC algorithms. A typical assumption in most of these theoretical results is that the target potential is smooth \cite{dalalyan2017theoretical,lee2021structured,wibisono2018sampling}, i.e., its gradient is Lipschitz continuous. In this work we consider sampling problems where the target potential is not smooth. Many applications of sampling involve potentials that lack smoothness. For instance, in Bayesian inference, the prior is naturally non-smooth when its support is constrained. Many problems in deep learning are also non-smooth, not only due to non-smooth activation functions like ReLU used in the neural networks, but also due to intrinsic scaling symmetries. Nevertheless, the study of such sampling problems without smoothness is nascent, compared with that for smooth potentials. This work is along the recent line of researches that lie in the interface of sampling and optimization \cite{durmus2019analysis,salim2020primal}. Indeed, sampling is closely related to optimization. On the one hand, optimization can be viewed as the limit of sampling when the temperature parameter, or equivalently the randomness in the problem, goes to 0. On the other hand, sampling can be viewed as an optimization over the manifold of probability distributions \cite{wibisono2018sampling,yang2020variational}. The popular gradient-based MCMC methods such as LMC, MALA, and HMC resemble the gradient-based algorithms in optimization and can be viewed as the sampling counterparts of them. However, in sharp contrast to optimization where a plethora of algorithms, e.g., subgradient method, proximal algorithm, bundle method have been developed for non-smooth optimization \cite{lemarechal1975extension,lemarechal1978nonsmooth,liang2020proximal,liang2021unified,mifflin1982modification,rockafellar1976monotone,wolfe1975method}, the sampling problem without smoothness remains largely unexplored, compared with its smooth counterpart. The goal of this paper is to develop an efficient algorithm to draw samples from potentials that lack smoothness. We consider two specific settings where the convex potential is either semi-smooth (i.e., the (sub)gradient of the potential is H\"older-continuous with exponent $\alpha\in [0,1]$) or composite with a semi-smooth component. This is a non-trivial extension of our previous work \cite{liang2021proximal} where the target potential is assumed to be convex and Lipschitz continuous. The core of our algorithm is a scheme to sample from a quadratically regularized version of the target potential. Our scheme is based on rejection sampling with a carefully designed Gaussian proposal whose center is an approximate minimizer of the regularized potential. We develop a novel technique to bound the complexity of our sampling scheme by estimating a modified Gaussian integral. Moreover, we establish an iteration-complexity bound for the proximal bundle optimization algorithm we use to compute an approximate minimizer of the regularized potential so that total complexity of our sampling scheme is properly bounded. To sample from the original target distribution, we utilize the alternative sampling framework (ASF) \cite{lee2021structured}. The latter is an application of Gibbs sampling over a specially designed distribution that augments the target one. The ASF has shown to exhibit remarkable convergence properties under mild assumptions \cite{CheCheSalWib22}. In particular, smoothness of the target potential is not required to ensure global convergence. To use ASF in practice, one needs to realize, in each iteration, a step known as the restricted Gaussian oracle (RGO) \cite{lee2021structured}. However, except for some very special cases e.g., the target potential is decomposable along each dimension, it was not clear how to implement RGO efficiently. It turns out that the sampling scheme we developed to sample from a quadratically regularized potential of the target potential is exactly an RGO for the target distribution. Thus, by combining ASF and the sampling scheme we developed, we establish an efficient algorithm to sample from any convex semi-smooth potential and any composite potential with a semi-smooth component. Moreover, the complexity of the resulting algorithm can be bounded by combining that of our sampling scheme and that of the ASF. We summarize our contributions as follows. \begin{itemize} \item[i)] We develop an efficient scheme to sample from a quadratically regularized potential that lacks smoothness and establish novel techniques to bound its complexity. \item[ii)] We combine our sampling scheme and the ASF to form a general sampling algorithm for convex semi-smooth potentials as well as composite potentials with semi-smooth components. The complexity of our algorithm is better than all existing results under the same assumptions. \item[iii)] Though these are not the focus of this work, we establish complexity bounds of the proximal bundle subroutine for convex semi-smooth functions and composite functions with semi-smooth components. These results can be readily used to bound the iteration-complexity of the proximal bundle algorithm in optimization for these functions. \end{itemize} {\bf Related Works:} Several new algorithms and theoretical results in sampling with semi-smooth and composite potentials have been established over the last few years. We begin with the literature on sampling from semi-smooth potentials or non-smooth potentials. In \cite{lehec2021langevin}, the author developed the projected LMC algorithm and analyzed its complexity for non-smooth potentials. In \cite{durmus2019analysis}, the authors presented an optimization approach to analyze the complexity of sampling and established a complexity result for sampling with non-smooth potentials. In \cite{chatterji2020langevin}, the authors proposed an LMC type algorithm for sampling from semi-smooth potentials based on Gaussian smoothing. In \cite{CheErdZha21,ErdHos20}, the authors analyzed LMC under functional inequalities and semi-smoothness (except the non-smooth case) and established corresponding complexity results. Next we consider sampling algorithms for composite potentials of the form $\exp(-f_1-f_2)$, where $f_1$ is convex and smooth, and $f_2$ is convex and non-smooth/semi-smooth. In \cite{mou2019efficient}, the authors developed an algorithm that needs an oracle to sample from the target potential regularized by a large isotropic quadratic term and to compute the corresponding partition function, akin to the RGO used in ASF \cite{shen2020composite}. In \cite{durmus2018efficient}, the authors introduced an algorithm by running LMC on the Moreau envelope of the potential. In \cite{durmus2019analysis}, the authors proposed an algorithm embedding the proximal map of $f_2$ into LMC and analyzed the convergence of the average of distributions over iterates. In \cite{freund2021convergence}, the authors improved the results in \cite{durmus2019analysis} for the cases where $f_2$ is an isotropic quadratic term. The paper \cite{salim2020primal} provided a primal-dual interpretation of the algorithm proposed in \cite{durmus2019analysis}, and established a slightly improved complexity result when the smooth part $f_1$ is also strongly convex. In \cite{bernton2018langevin}, the authors also examined the problem from an optimization perspective and established a complexity bound in the cases where $f_1$ is strongly convex. Another approach for sampling from the composite density $\exp(-f_1-f_2)$ is to apply LMC on the Gaussian smoothing of the potentials. In \cite{chatterji2020langevin}, the authors proposed this algorithm for sampling from composite densities. Following this paper, \cite{NguDanChe21} further developed algorithms based on generalized Gaussian smoothing and obtained improved results when $f_1$ is strongly convex. We compare these existing complexity bounds with our results in Tables \ref{tab:t1} and \ref{tab:t2}. We highlight only the dependence of the complexity on the dimension $d$, the accuracy $\varepsilon$, the level of smoothness $\alpha$ and the semi-smoothness coefficient $L_\alpha$, the smoothness coefficient $L_1$ of $f_1$, and the strong convexity coefficient $\lambda$ of $f_1$ if it is positive. To this end, we make the following simplifications. The initial distance (either in KL/R\'enyi or in $W_2^2$) to the target distribution is set to be $\tilde{\cal O}(d)$. The forth order moment ${\cal M}_4= {\cal O}(d^2)$. We also omit the dependence of the Poincar\'e coefficient if there is any. We make the following remarks regarding these complexity bounds. Complexity results established in \cite{durmus2019analysis} is for the average of distributions over iterates, while other results presented in Tables \ref{tab:t1} and \ref{tab:t2} are for the distributions over the last iterates. The non-smooth case (i.e., $\alpha=0$) is not covered in complexity results of \cite{CheErdZha21} and \cite{ErdHos20} in Table \ref{tab:t1}, and the result of \cite{NguDanChe21} in Table \ref{tab:t2}, as these bounds blow up as $\alpha \rightarrow 0$. Papers \cite{bernton2018langevin,chatterji2020langevin,durmus2019analysis,durmus2018efficient,salim2020primal} rely on the composite form $f_1+f_2$ of the composite potentials and the proximal map of $f_2$. In contrast, our algorithm does not depend the decomposition of the potential and does not necessarily require the proximal map of $f_2$. \begin{table}[H] \begin{centering} \begin{tabular}{|>{\centering}p{2cm}|>{\centering}p{4cm}|>{\centering}p{3cm}|>{\centering}p{3cm}|>{\centering}p{3cm}|} \hline {Source} & {Complexity} & {Assumption} & {Metric} \tabularnewline \hline {\cite{chatterji2020langevin}} & {$\tilde {\cal O} \left( \frac{L_\alpha^{6/(1+\alpha)} d^{8-3\alpha} } {\varepsilon^{(10+4\alpha)/(1+\alpha)}} \right)$} & {semi-smooth} & {TV} \tabularnewline \hline {\cite{durmus2019analysis}} & {$ {\cal O} \left( \frac{ L_0^2 d} {\varepsilon^{2}}\right)$} & {non-smooth} & {KL} \tabularnewline \hline {\cite{lehec2021langevin}} & {$ \tilde{\cal O}\left(\frac{L_0^2d^2}{\varepsilon^2} \right)$} & {non-smooth} & {$W_1^2$} \tabularnewline \hline {\cite{CheErdZha21}} & {$ \tilde{\cal O}\left(\frac{L_\alpha ^{2/\alpha}d^{2+1/\alpha} }{\varepsilon^{1/\alpha}}\right)$} & {semi-smooth} & {R\'enyi} \tabularnewline \hline {\cite{ErdHos20}} & {$ \tilde{\cal O}\left(\frac{ L_\alpha^{2/\alpha}d^{2+3/\alpha}}{\varepsilon^{1/\alpha}}\right) $} & {semi-smooth} & {KL} \tabularnewline \hline {this paper (Thm. \ref{thm:f})} & {$\tilde {\cal O} \left(\frac{L_\alpha^{2/(1+\alpha)} d^2}{\varepsilon} \right) $} & {semi-smooth} & {TV} \tabularnewline \hline {this paper (Thm. \ref{thm:Renyi})} & {$\tilde {\cal O} \left(L_\alpha^{2/(1+\alpha)} d^2 \right) $} & {semi-smooth} & {R\'enyi} \tabularnewline \hline \end{tabular} \par\end{centering} \caption{Complexity bounds for sampling from semi-smooth/non-smooth potentials.}\label{tab:t1} \end{table} \begin{table}[H] \begin{centering} \begin{tabular}{|>{\centering}p{2cm}|>{\centering}p{4cm}|>{\centering}p{3cm}|>{\centering}p{3cm}|>{\centering}p{3cm}|} \hline {Source} & {Complexity} & {Assumption} & {Metric} \tabularnewline \hline {\cite{chatterji2020langevin}} & {$\tilde {\cal O} \left( \frac{L_\alpha^{6/(1+\alpha)} d^{5-3\alpha}} {\lambda^3\varepsilon^{(7+\alpha)/(1+\alpha)}} \right)$} & {smooth+semi-smooth} & {TV} \tabularnewline \hline {\cite{durmus2018efficient}} & {$\tilde {\cal O} \left( \frac{ L_0^2d^5}{\varepsilon^{2}} \right)$} & {smooth+non-smooth} & {TV} \tabularnewline \hline {\cite{durmus2019analysis}} & {$ {\cal O} \left( \frac{L_1 d^2 + L_0^2 d} {\varepsilon^{2}}\right)$} & {smooth+non-smooth} & {KL} \tabularnewline \hline {\cite{salim2020primal}} & {$ \tilde{\cal O}\left(\frac{L_0^2+L_1d}{{\lambda}^2 \varepsilon} \right)$} & {smooth+non-smooth} & {$W_2^2$} \tabularnewline \hline {\cite{NguDanChe21}} & {$ \tilde{\cal O}\left(\frac{ (L_\alpha \vee L_1) ^{2/\alpha}d^{1/\alpha} }{\lambda^{1+1/\alpha}\varepsilon^{1/\alpha}}\right) $} & {smooth+semi-smooth} & {KL} \tabularnewline \hline {\cite{bernton2018langevin}} & {$ \tilde{\cal O}\left(\frac{ L_0^2 d}{{\lambda} \varepsilon^4}\right) $} & {smooth+non-smooth} & {$W_2$} \tabularnewline \hline {this paper (Thm. \ref{thm:all})} & {$\tilde {\cal O}\left( \frac{(L_\alpha^{2/(\alpha+1)}\vee L_1)d^2}{\varepsilon}\right) $} & {smooth+semi-smooth} & {TV} \tabularnewline \hline {this paper (Thm. \ref{thm:all})} & {$\tilde {\cal O}\left( (L_\alpha^{2/(\alpha+1)}\vee L_1)d^2\right) $} & {smooth+semi-smooth} & {R\'enyi} \tabularnewline \hline {this paper (Thm. \ref{thm:last})} & {$\tilde {\cal O}\left( \frac{(L_\alpha^{2/(\alpha+1)}\vee L_1)d}{{\lambda}}\right) $} & {smooth+semi-smooth} & {R\'enyi} \tabularnewline \hline \end{tabular} \par\end{centering} \caption{Complexity bounds for sampling from composite potentials.}\label{tab:t2} \end{table} \section{Problem formulation and the alternating sampling framework} \label{sec:formulation} We are interested in sampling problems associated with convex potentials that are not necessarily smooth. In particular, we consider two specific scenarios of sampling tasks with target distribution \begin{equation}\label{eq:target} \nu \propto \exp(-f(x)) \end{equation} in $\mathbb{R}^d$. In the first setting, the potential $f$ is assumed to be convex and semi-smooth, i.e., \begin{equation}\label{ineq:semi-smooth} \|f'(u) - f'(v)\| \le L_\alpha\|u-v\|^\alpha,\quad \forall u, v\in \mathbb{R}^d \end{equation} for some $\alpha \in [0,1]$ and coefficient $L_\alpha>0$, where $f'$ denotes a subgradient of $f$. Clearly, when $\alpha=0$, \eqref{ineq:semi-smooth} reduces to a Lipschitz continuous condition, and when $\alpha=1$, it reduces to a smoothness condition. In the second setting, the potential is assumed to be composite as $f(x) = f_1(x)+f_2(x)$ with $f_1$ being convex and smooth and $f_2$ being convex and semi-smooth. Most existing gradient-based sampling algorithms are not applicable to these problems due to the lack of smoothness. In this work, we develop {\bf a proximal algorithm for sampling from semi-smooth potentials and composite potentials}. Our method is based on the alternating sampling framework (ASF) introduced in \cite{lee2021structured}, which is a generic framework for sampling from a distribution $\pi^X(x) \propto \exp(-g(x))$. Starting from a point $x_0\in \mathbb{R}^d$, the alternating sampling framework with stepsize $\eta>0$ repeats the two steps as in Algorithm \ref{alg:ASF}. \begin{algorithm}[H] \caption{Alternating Sampling Framework \cite{lee2021structured}} \label{alg:ASF} \begin{algorithmic} \STATE 1. Sample $y_{k}\sim \pi^{Y|X}(y\mid x_k) \propto \exp[-\frac{1}{2\eta}\|x_k-y\|^2]$ \STATE 2. Sample $x_{k+1}\sim \pi^{X|Y}(x \mid y_{k}) \propto \exp[-g(x)-\frac{1}{2\eta}\|x-y_{k}\|^2]$ \end{algorithmic} \end{algorithm} Apparently, the ASF is a special case of Gibbs sampling \cite{GemGem84} of the joint distribution \begin{equation} \pi(x,y) \propto \exp(-g(x)-\frac{1}{2\eta}\|x-y\|^2). \end{equation} In Algorithm \ref{alg:ASF}, sampling $y_k$ given $x_k$ in step 1 can be easily done since $\pi^{Y|X}(y\mid x_k) = {\cal N}(x_k,\eta I)$ is a simple Gaussian distribution. Sampling $x_{k+1}$ given $y_k$ in step 2 is however a nontrivial task; it corresponds to the so-called restricted Gaussian oracle for $g$ introduced in \cite{lee2021structured}, which is defined as follows. \begin{definition} Given a point $y\in \mathbb{R}^d$ and stepsize $\eta >0$, the restricted Gaussian oracle (RGO) for $g:\mathbb{R}^d\to \mathbb{R}$ is a sampling oracle that returns a random sample from a distribution proportional to $\exp(-g(\cdot) - \|\cdot-y\|^2/(2\eta))$. \end{definition} The RGO is an analogy of the proximal map \[ {\rm Prox}_{\eta g}(y): = \mathrm{argmin}\,_{x} [g(x)+\frac{1}{2\eta}\|x-y\|^2] \] in optimization, which is widely used in proximal algorithms for optimization \cite{ParBoy14}. To use the ASF in practice, one needs to efficiently implement the RGO. Some examples of $g$ that admits a computationally efficient RGO have been presented in \cite{mou2019efficient,shen2020composite}. These instances of $g$ have simple structures such as coordinate-separable regularizers, $\ell_1$-norm, and group Lasso. For general $g$, especially non-smooth ones considered in this work, it was not clear how to realize the RGO efficiently. Assuming the RGO in the ASF can be realized, the ASF exhibits remarkable convergence properties. In \cite{lee2021structured} it was shown that Algorithm \ref{alg:ASF} converges linearly when $g$ is strongly convex. This convergence result is recently improved in \cite{CheCheSalWib22} under various weaker assumptions on the target distribution $\pi^X \propto \exp(-g)$. Below we present several convergence results established in \cite{CheCheSalWib22} that will be used in this paper, under the assumptions that $\pi^X$ is strongly-log-concave ($g$ is strongly convex), log-concave, or satisfies the Poincar\'e inequality. Recall that a probability distribution $\nu$ satisfies the Poincar\'e inequality (PI) with constant ${\lambda} > 0$ (${\lambda}$-PI) if for any smooth bounded function $\psi : \mathbb{R}^d\to\mathbb{R}$, \begin{align}\label{eq:pi} \mathbb{E}_\nu[(\psi-\mathbb{E}_\nu(\psi))^2] &\le \frac{1}{{\lambda}} \mathbb{E}_\nu[\norm{\nabla \psi}^2]\,. \end{align} In particular, any log-concave probability density satisfies the Poincar\'e inequality. To this end, for two probability distributions $\rho \ll \nu$, we denote by \[ H_\nu(\rho) := \int \rho \log\frac{\rho}{\nu},\quad \chi_\nu^2 (\rho):= \int \frac{\rho^2}{\nu}-1, \quad R_{q,\nu}(\rho): = \frac{1}{q-1}\log\int \frac{\rho^q}{\nu^{q-1}} \] the {\em KL divergence}, the {\em Chi-squared divergence}, and the {\em R\'enyi divergence}, respectively. Note that $R_{2,\nu}= \log (1+\chi_\nu^2)$, $R_{1,\nu} = H_\nu$, and $R_{q,\nu}\le R_{q',\nu}$ for any $1\le q \le q'<\infty$. We denote by $W_2$ the Wasserstein-2 distance defined by \cite{Vil21} \[ W_2^2(\nu,\rho) := \min_{\gamma\in \Pi(\nu,\rho)}\int \|x-y\|^2 {\mathrm d}\gamma, \] where $\Pi(\nu,\rho)$ represents the set of all couplings between $\nu$ and $\rho$. \begin{theorem}[{\cite[Theorem 3]{CheCheSalWib22}}]\label{thm:outer} Assume that $\pi^X \propto \exp(-g)$ is ${\lambda}$-strongly-log-concave (\textit{i.e.}, $g$ is ${\lambda}$-strongly convex). For any initial distribution $\rho_0^X$, the $k$-th iterate $\rho_k^X$ of Algorithm \ref{alg:ASF} with step size $\eta>0$ satisfies \begin{align} H_{\pi^X}(\rho_k^X) \le \frac{H_{\pi^X}(\rho_0^X)}{{(1 + {\lambda} \eta)}^{2k}}\,. \end{align} Furthermore, for all $q \ge 1$, \begin{align} R_{q,\pi^X}(\rho_k^X) \le \frac{R_{q,\pi^X}(\rho_0^X)}{{(1 + {\lambda} \eta)}^{2k/q}}\,. \end{align} \end{theorem} \begin{theorem}[{\cite[Theorem 2]{CheCheSalWib22}}]\label{Thm:LC} Assume that $\pi^X \propto \exp(-g)$ is log-concave (\textit{i.e.}, $g$ is convex). For any initial distribution $\rho_0^X$, the $k$-th iterate $\rho_k^X$ of Algorithm \ref{alg:ASF} satisfies \begin{align*} H_{\pi^X}(\rho_k^X) \le \frac{W_2^2(\rho_0^X, \pi^X)}{k\eta}\,. \end{align*} \end{theorem} \begin{theorem}[{\cite[Theorem 4]{CheCheSalWib22}}]\label{Thm:Poincare} Assume $\pi^X \propto \exp(-g)$ satisfies ${\lambda}$-PI. For any initial distribution $\rho_0^X$, the $k$-th iterate $\rho_k^X$ of Algorithm \ref{alg:ASF} with step size $\eta>0$ satisfies \begin{align} \chi_{\pi^X}^2(\rho^X_k) \le \frac{\chi_{\pi^X}^2(\rho^X_0)}{{(1 + {\lambda} \eta)}^{2k}}\,. \end{align} Furthermore, for all $q \ge 2$, \begin{align} R_{q,\pi^X}(\rho^X_k) \le \begin{cases} R_{q,\pi^X}(\rho_0^X) - \frac{2k \log(1+{\lambda}\eta)}{q}\,, &\text{if}~k\le \frac{q}{2\log(1+{\lambda}\eta)} \, (R_{q,\pi^X}(\rho_0^X) - 1)\,, \\ 1/{(1+{\lambda}\eta)}^{2(k-k_0)/q}\,, &\text{if}~k \ge k_0 := \lceil \frac{q}{2\log(1+{\lambda}\eta)} \, (R_{q,\pi^X}(\rho_0^X) - 1)\rceil\,. \end{cases} \end{align} \end{theorem} As discussed earlier, to use ASF in sampling problems, we need to realize the RGO with efficient implementations. In the rest of this paper, we develop efficient algorithms for RGO associated with the two scenarios of sampling we are interested in, and then combine them with the ASF to establish a proximal algorithm for sampling. The complexity of the proximal algorithm can be obtained by combining the above convergence results for ASF and the complexity results we develop for RGO. The rest of the paper is organized as follows. In Section~\ref{sec:RGO} we develop an efficient algorithm for RGO associated with semi-smooth potentials via rejection sampling. This is combined with ASF to obtain an efficient sampling algorithm from semi-smooth potentials in Section~\ref{sec:main}. In Section~\ref{sec:composite}, we further extend the algorithm and results to the second setting we are interested in which involves composite potentials (smooth $+$ semi-smooth). In Section~\ref{sec:conclusion}, we present some concluding remarks and possible extensions. Finally, in Appendices~\ref{sec:technical}-\ref{sec:hybridopt}, we present some technical results and proofs omitted in the paper. \section{The restricted Gaussian oracle for semi-smooth potentials}\label{sec:RGO} As mentioned in Section \ref{sec:formulation}, the bottleneck of using the ASF (Algorithm \ref{alg:ASF}) in sampling tasks with general distributions is the availability of RGO implementations. In this section, we address this issue for convex semi-smooth potentials by developing an efficient algorithm for the corresponding RGO. In fact, for a given convex semi-smooth potential $f(x)$ associated with a target distribution, we consider the RGO for \begin{equation}\label{eq:g} g=f+\frac\mu2 \|\cdot-x^0\|^2, \end{equation} a regularized potential. Here $\mu\ge 0$ and $x^0$ can be any fixed point in $\mathbb{R}^d$. The RGO for $f$ is of course a special case of it by setting $\mu=0$. This extra regularization allows us to leverage Theorem \ref{thm:outer} to establish a computational complexity for our proximal sampling algorithm, as will be seen in Section \ref{sec:main}. Our algorithm of RGO for $g$ is based on rejection sampling. We use a special proposal which is a Gaussian distribution centered at the (approximate) minimizer of \begin{equation}\label{def:geta} g_y^\eta(x):=g(x)+\frac{1}{2\eta}\|x-y\|^2 \end{equation} for a given $y$. With this proposal and a sufficiently small $\eta>0$, the expected number of rejection sampling steps to obtain one effective sample turns out to be bounded above by a dimension-free constant. To better present our RGO algorithm, we begin with a simpler case in Section \ref{subsec:opt-oracle} where the minimizer of $g_y^\eta(x)$ is assumed to be given. To bound the complexity of the rejection sampling, we develop a novel technique to estimate a modified Gaussian integral (see Proposition \ref{prop:key}). We then generalize the results to the setting when the precise minimizer of $g_y^\eta(x)$ is not accessible. In particular, in Section \ref{subsec:bundle} we develop a proximal bundle method to optimize $g_y^\eta(x)$ to certain precision and establish the iteration-complexity for it. In Section \ref{subsec:no opt-oracle} we extend the ideal complexity results in Section~\ref{subsec:opt-oracle} to the more practical case where the proposal is centered at an approximate minimizer of $g_y^\eta$ instead of the precise one. This is achieved by choosing a proper precision for the approximate minimizer of $g_y^\eta$ that balances the complexity of optimization and the efficiency of rejection sampling. Finally, in Section~\ref{subsec:smooth}, we consider a special case of the general implementation of RGO presented in Section~\ref{subsec:no opt-oracle}, i.e., when $f$ is $L_1$-smooth. We present consequences of general complexity results in the smooth setting, and also develop an alternative rejection sampling complexity result in this particular case. \subsection{Sampling with proximal map}\label{subsec:opt-oracle} In this section we develop an efficient algorithm for the RGO associated with $g$ in \eqref{eq:g} assuming the minimizer, denoted by \begin{equation}\label{def:x*} x^*(y)={\rm Prox}_{\eta g}(y), \end{equation} of $g_y^\eta$ in \eqref{def:geta} is accessible. We often use $x^*$ to denote the minimizer to simplify the notation when the value of $y$ is clear from the context. Our algorithm is based on rejection sampling. We use a Gaussian proposal distribution centered at $x^*$. The intuition is that this proposal is close to the target distribution $\pi^{X|Y}(x\mid y) \propto \exp(-g_y^\eta(x))$ when $\eta$ is small. We then develop a novel technique to achieve a tight bound on the expected runs for the rejection sampling. To this end, define \begin{subequations}\label{def:h1-h2} \begin{eqnarray}\label{def:h1-h2-1} h_1&:=& \frac{1}{2\eta_\mu}\|\cdot-x^*\|^2 + g_y^\eta(x^*), \\ h_2 &:=& \frac{1}{2\eta_\mu}\|\cdot-x^*\|^2 + \frac{L_\alpha}{\alpha+1}\|\cdot-x^*\|^{\alpha+1} + g_y^\eta(x^*), \label{def:h1-h2-2} \end{eqnarray} \end{subequations} where \begin{equation}\label{def:eta_mu} \eta_\mu:=\frac{\eta}{1+\eta\mu}. \end{equation} Note that, for the sake of simplicity, in \eqref{def:h1-h2} we have suppressed the dependence of $h_1, h_2$ on $x$ in the notation. These two functions $h_1, h_2$ bound the target potential $g_y^\eta$ in both directions as in the following result. \begin{lemma}\label{lem:h1h2} \begin{equation} h_1(x) \le g_y^\eta(x) \le h_2(x),\quad \forall x\in \mathbb{R}^d. \end{equation} \end{lemma} \begin{proof} It is a special case of a more general result (Lemma \ref{lem:h1h2delta}) and thus the proof is omitted. \end{proof} Consequently, we can use $h_1$ to generate proposed samples and $h_2$ to bound the expected runs. The detailed algorithm for the RGO is presented in Algorithm \ref{alg:RGO}. \begin{algorithm}[H] \caption{Rejection Sampling with Proximal Map} \label{alg:RGO} \begin{algorithmic} \STATE 1. Compute the minimizer $x^*$ as in \eqref{def:x*} \STATE 2. Generate sample $X\sim \exp(-h_1(x))$ \STATE 3. Generate sample $U\sim {\cal U}[0,1]$ \STATE 4. If \[ U \leq \frac{\exp(-g_y^\eta(X))}{\exp(-h_1(X))}, \] then accept/return $X$; otherwise, reject $X$ and go to step 2. \end{algorithmic} \end{algorithm} From the expression of $h_1$ in \eqref{def:h1-h2-1}, it is clear the proposal distribution is a Gaussian centered at $x^*$. To achieve a tight bound on the expected runs of the rejection sampling, we use a function $h_2$ which is not quadratic; the standard choice of quadratic function does not give as tight results due to the lack of smoothness. To use this $h_2$ in the complexity analysis, we need to estimate the integral $\int \exp(-h_2)$, which turns out to be {\em a highly nontrivial task}. Below we establish a technical result on a modified Gaussian integral, which will be used later to bound the integral $\int \exp(-h_2)$ and hence the complexity of the RGO rejection sampling in Algorithm \ref{alg:RGO}. \begin{proposition}\label{prop:key} Let $\alpha\in[0,1]$, $\eta>0$, $a\ge 0$ and $d\ge 1$. If \begin{equation}\label{eq:aeta} 2a(\eta d)^{(\alpha+1)/2} \le 1, \end{equation} then \begin{equation}\label{ineq:int} \int_{\mathbb{R}^d} \exp\left(-\frac{1}{2\eta}\|x\|^2 - a\|x\|^{\alpha+1}\right) \mathrm{d} x \ge \frac{(2\pi\eta)^{d/2}}2. \end{equation} \end{proposition} \begin{proof} Denote $r=\|x\|$, then \[ \mathrm{d} x= r^{d-1} \mathrm{d} r \mathrm{d} S^{d-1}, \] where $ \mathrm{d} S^{d-1} $ is the surface area of the $ (d-1) $-dimensional unit sphere. It follows that \begin{align} \int_{\mathbb{R}^d} \exp\left(-\frac{1}{2\eta}\|x\|^2 - a\|x\|^{\alpha+1} \right) \mathrm{d} x &= \int_0^\infty \int \exp\left(-\frac{1}{2\eta}r^2 - a r^{\alpha+1} \right) r^{d-1} \mathrm{d} r \mathrm{d} S^{d-1} \nonumber \\ &= \frac{2 \pi^{d/2}}{\Gamma\left( \frac d2 \right) } \int_0^\infty \exp\left( -\frac{1}{2\eta}r^2 - a r^{\alpha+1} \right) r^{d-1} \mathrm{d} r. \label{eq:int} \end{align} In the above equation, we have used the fact that the total surface area of a $ (d-1) $-dimensional unit sphere is $2 \pi^{d/2}/\Gamma\left( \frac d2 \right)$ where $\Gamma(\cdot)$ is the gamma function, i.e., \begin{equation}\label{eq:gamma} \Gamma(z)=\int_0^\infty t^{z-1} e^{-t} \mathrm{d} t. \end{equation} Defining \begin{equation}\label{def:F} F_{d,\eta}(a):= \int_0^\infty \exp\left( -\frac{1}{2\eta}r^2 - a r^{\alpha+1} \right) r^{d} \mathrm{d} r, \end{equation} to establish \eqref{ineq:int}, it suffices to bound $F_{d-1,\eta}(a)$ from below. It follows directly from the definition of $F_{d,\eta}$ in \eqref{def:F} that \[ \frac{\mathrm{d} F_{d-1,\eta}(a)}{\mathrm{d} a}=\int_0^\infty \exp\left( -\frac{1}{2\eta}r^2 - a r^{\alpha+1} \right) (-r^{\alpha+1}) r^{d-1} \mathrm{d} r =- F_{d+\alpha,\eta}(a). \] This implies $F_{d,\eta}$ is monotonically decreasing and thus $F_{d+\alpha,\eta}(a)\le F_{d+\alpha,\eta}(0)$. As a result, \[ \frac{\mathrm{d} F_{d-1,\eta}(a)}{\mathrm{d} a} \ge - F_{d+\alpha,\eta}(0) \] and therefore, \begin{equation}\label{ineq:F} F_{d-1,\eta}(a) \ge F_{d-1,\eta}(0) - a F_{d+\alpha,\eta}(0). \end{equation} Setting $t=r^2/(2\eta)$, we can write \begin{align} F_{d,\eta}(0) &=\int_0^\infty \exp\left( -\frac{1}{2\eta}r^2 \right) r^{d} \mathrm{d} r =\int_0^\infty e^{-t} (2\eta t)^{\frac{d-1}2} \eta \mathrm{d} t \nonumber \\ &= 2^{\frac{d-1}2} \eta^{\frac{d+1}2} \int_0^\infty e^{-t} t^{\frac{d-1}2} \mathrm{d} t. \end{align} In view of the definition of the gamma function \eqref{eq:gamma}, we obtain \begin{equation}\label{eq:F} F_{d,\eta}(0) =2^{\frac{d-1}2} \eta^{\frac{d+1}2} \Gamma\left(\frac{d+1}{2}\right). \end{equation} Applying the Wendel's double inequality \eqref{ineq:Wendel} yields \[ \frac{\Gamma\left(\frac{d+\alpha+1}{2} \right)}{\Gamma\left(\frac{d}{2} \right)} \le \left(\frac d2\right)^{\frac{\alpha+1}2}. \] Using \eqref{ineq:F}, \eqref{eq:F}, the above inequality and the assumption \eqref{eq:aeta}, we have \begin{align*} F_{d-1,\eta}(a) &\ge F_{d-1,\eta}(0) - a F_{d+\alpha,\eta}(0) \\ &= 2^{\frac d2-1} \eta^{\frac d2} \Gamma\left(\frac{d}{2}\right) - a 2^{\frac{d+\alpha-1}2} \eta^{\frac{d+\alpha+1}2} \Gamma\left(\frac{d+\alpha+1}{2}\right) \\ &= 2^{\frac d2-1} \eta^{\frac d2} \Gamma\left(\frac{d}{2}\right) \left(1 - a 2^{\frac{\alpha+1}2} \eta^{\frac{\alpha+1}2} \frac{\Gamma\left(\frac{d+\alpha+1}{2} \right)}{\Gamma\left(\frac{d}{2} \right)} \right)\\ &\ge 2^{\frac d2-1} \eta^{\frac d2} \Gamma\left(\frac{d}{2}\right) \left(1 - a (\eta d)^{\frac{\alpha+1}2} \right) \ge \frac14 (2\eta)^{\frac d2} \Gamma\left(\frac{d}{2}\right). \end{align*} The result \eqref{ineq:int} then follows from the above inequality and \eqref{eq:int}. \end{proof} With Proposition \ref{prop:key}, we are now equipped to bound the complexity of the rejection sampling in Algorithm \ref{alg:RGO} as below. \begin{proposition}\label{prop:rejection} Assume $f$ is convex and $L_\alpha$-semi-smooth and let $g$ be as in \eqref{eq:g}. Then $X$ generated by Algorithm \ref{alg:RGO} follows the distribution \[ \pi^{X|Y}(x\mid y) \propto \exp\left(-g(x)-\frac{1}{2\eta}\|x-y\|^2\right). \] If in addition \begin{equation}\label{ineq:eta_mu} \eta_\mu \le \frac{(\alpha+1)^{\frac{2}{\alpha+1}}}{(2L_\alpha)^{\frac{2}{\alpha+1}}d}\,, \end{equation} then the expected number of iteration in Algorithm \ref{alg:RGO} is at most $2$. \end{proposition} \begin{proof} It is a well-known result for rejection sampling that $X \sim \pi^{X|Y}(x\mid y)$ and the probability that $X$ is accepted is \begin{equation}\label{eq:probability} \mathbb{P}\left(U \leq \frac{\exp(-g_y^\eta(X))}{\exp(-h_1(X))}\right) =\frac{\int_{\mathbb{R}^d} \exp(-g_y^\eta(x)) \mathrm{d} x}{\int_{\mathbb{R}^d} \exp(-h_1(x)) \mathrm{d} x}. \end{equation} If follows directly from the definition of $h_2$ in \eqref{def:h1-h2-2} that \begin{align*} \int_{\mathbb{R}^d} \exp(-h_2(x)) \mathrm{d} x &= \exp(-g_y^\eta(x^*)) \int_{\mathbb{R}^d} \exp\left(-\frac{1}{2\eta_{\mu}}\|x-x^*\|^2 - \frac{L_\alpha}{\alpha+1}\|x-x^*\|^{\alpha+1}\right) \mathrm{d} x \end{align*} Applying Proposition \ref{prop:key} to the above yields \[ \int_{\mathbb{R}^d} \exp(-h_2(x)) \mathrm{d} x \ge \exp(-g_y^\eta(x^*)) \frac{(2\pi \eta_{\mu})^{d/2}}{2}. \] Note that the condition \eqref{eq:aeta} in Proposition \ref{prop:key} holds thanks to \eqref{ineq:eta_mu}. By Lemma \ref{lem:h1h2}, the above inequality leads to \begin{equation}\label{ineq:geta} \int_{\mathbb{R}^d} \exp(-g_y^\eta(x)) \mathrm{d} x \ge \int_{\mathbb{R}^d} \exp(-h_2(x)) \mathrm{d} x \ge \exp(-g_y^\eta(x^*)) \frac{(2\pi\eta_\mu)^{d/2}}2. \end{equation} On the other hand, it follows from the definition of $h_1$ in \eqref{def:h1-h2} and Lemma \ref{lem:Gaussian} that \begin{equation}\label{eq:h1int} \int_{\mathbb{R}^d} \exp(-h_1(x)) \mathrm{d} x = \exp(-g_y^\eta(x^*)) (2\pi\eta_\mu)^{d/2}. \end{equation} Combining \eqref{eq:probability}, \eqref{ineq:geta}, and \eqref{eq:h1int} we conclude \[ \mathbb{P}\left(U \leq \frac{\exp(-g_y^\eta(X))}{\exp(-h_1(X))}\right) \ge \frac12\,. \] Therefore, the expected number of iterations is bounded above by 2. \end{proof} \subsection{A proximal bundle method subroutine for semi-smooth optimization}\label{subsec:bundle} The sampling algorithm (Algorithm \ref{alg:RGO}) in Section \ref{subsec:opt-oracle} assumes accessibility of the exact minimizer of $g_y^\eta$. Due to the non-smoothness of $g_y^\eta$, a high precision approximation of the minimizer is difficult to compute, thus, the assumption for Algorithm \ref{alg:RGO} is not practical. To establish an implementable algorithm for the RGO of $g$, one needs to work with the approximate minimizer. In this section, we study the iteration-complexity of an optimization algorithm for $g_y^\eta$. This will be utilized in Section \ref{subsec:no opt-oracle} to form a practical algorithm for the RGO of $g$. We consider the optimization problem \begin{equation}\label{eq:subproblem} g_y^\eta (x^*)= \min \left\{ g_y^\eta(x)= g(x) + \frac{1}{2\eta}\|x-y\|^2: x\in \mathbb{R}^d\right \}, \end{equation} and we aim at obtaining a $\delta$-solution, i.e., a point $\bar x$ such that \begin{equation}\label{eq:deltasol} g_y^\eta(\bar x) - g_y^\eta(x^*) \le \delta. \end{equation} To achieve this goal, we borrow ideas from the proximal bundle method \cite{liang2020proximal,liang2021unified}, which is an efficient algorithm for solving convex non-smooth optimization problems. The proximal bundle method solves a non-smooth optimization via sequentially solving a sequence of sub-problems of the form \eqref{eq:subproblem} approximately. We adopt this subroutine in the proximal bundle method to obtain a $\delta$-solution to \eqref{eq:subproblem}. This is summarized in Algorithm \ref{alg:PBS}. We remark that though Algorithm \ref{alg:PBS} is widely used in the proximal bundle method and is not new, the complexity analysis (Theorem \ref{thm:bundle}) of it associated with a semi-smooth function $f$ is novel. To our best knowledge, Theorem \ref{thm:bundle} is the first iteration-complexity result for the optimization of the form \eqref{eq:subproblem} for semi-smooth functions. This result can be readily used for complexity analysis of the proximal bundle method for semi-smooth functions (This is not the focus of this paper and will not be explored here). \begin{algorithm}[H] \caption{Proximal Bundle Method Subroutine} \label{alg:PBS} \begin{algorithmic} \STATE 1. Let $y$, $\eta>0$, $\delta>0$ and $x^0$ be given, and set $x_0=\tilde x_0=y$, $C_1=\{y\}$ and $j=1$ \STATE 2. Update $f_j = \max \left\lbrace f(x)+\inner{f'(x)}{\cdot-x} : \, x \in C_j\right\rbrace$ \STATE 3. Define $g_j:=f_j + \mu\|\cdot-x^0\|^2/2$ and compute \begin{equation} x_j =\underset{u\in \mathbb{R}^d}\mathrm{argmin}\, \left\lbrace g_j^\eta(u):= g_j(u) +\frac{1}{2\eta}\|u- y\|^2 \right\rbrace, \label{def:xj} \end{equation} \begin{equation}\label{def:tx} \tilde x_j\in \mathrm{Argmin}\,\left\lbrace g_y^\eta(u): u\in \{x_j, \tilde x_{j-1}\}\right\rbrace \end{equation} \STATE 4. If $g_y^\eta(\tilde x_j) - g_j^\eta(x_j)\le \delta$, then {\bf stop} and {\bf return} $J=j, x_J, \tilde x_J$; else, go to step 5 \STATE 5. Set $C_{j+1}= C_{j}\cup \{x_j\}$, $ j $ \ensuremath{\leftarrow} $ j+1 $ and go to step 2. \end{algorithmic} \end{algorithm} The basic idea of Algorithm \ref{alg:PBS} is to approximate the non-smooth part of the objective function $g_y^\eta$ with piece-wise affine functions constructed by a collection of cutting-planes and solve the resulting simplified problem. As the approximation becomes more and more accurate, the solutions to the approximated problems converge to that of \eqref{eq:subproblem}. We make several remarks regarding Algorithm \ref{alg:PBS}. First, the update $C_{j+1}=C_j \cup \{x_j\}$ in step 5 results in the standard cutting-plane model $f_j$, and $\{f_j\}$ is a sequence of increasing functions underneath $f$. Second, \eqref{def:xj} can be reformulated into a convex quadratic programming with affine constraints and the number of constraints is equal to the cardinality of $C_j$. Since the subproblem \eqref{def:xj} becomes harder to solve as the size of $C_j$ grows, we are in favor of choosing a relatively large tolerance $\delta>0$. We next show Algorithm \ref{alg:PBS} can compute a $\delta$-solution to \eqref{eq:subproblem} within a reasonable number of iterations. To this end, we present a technical lemma for Algorithm \ref{alg:PBS}. This lemma is also useful in the complexity analysis in Section \ref{subsec:no opt-oracle} for sampling. \begin{lemma}\label{lem:bundle} Assume $f$ is convex and $L_\alpha$-semi-smooth and let $g$ be as in \eqref{eq:g}. Let $J, x_J, \tilde x_J$ be the outputs of Algorithm \ref{alg:PBS}, then the following statements hold: \begin{itemize} \item[a)] $f_j(x)\le f(x)$, $g_j(x) \le g(x)$ and $g_j^\eta(x_j) + \|x-x_j\|^2/(2\eta_\mu) \le g_j^\eta(x)$ for $\forall x\in \mathbb{R}^d$ and $\forall j$; \item[b)] $g_y^\eta(\tilde x_J) - g_J^\eta(x_J) \le \delta$; \item[c)] $-\mu(x^*-x^0) - \frac{1}{\eta} (x^*-y) \in\partial f(x^*)$ where $\partial f$ denotes the subdifferential of $f$. \end{itemize} \end{lemma} \begin{proof} a) The first two inequalities directly follow from the convexity of $f$, and the definitions of $g$ and $g_j$. The third inequality follows from \eqref{def:xj}. b) This statement immediately follows from step 3 of Algorithm \ref{alg:PBS}. c) This statement directly follows from the optimality condition of \eqref{eq:subproblem} and the fact that $g=f+\mu\|\cdot-x^0\|^2$. \end{proof} Clearly, when Algorithm \ref{alg:PBS} terminates, the output $\tilde x_J$ is a $\delta$-solution to \eqref{eq:subproblem}. To see this, note that, following the stop criteria in step 4 and Lemma \ref{lem:bundle}, \[ g_y^\eta(\tilde x_J) \le \delta + g_J^\eta(x_J) \le \delta + g_J^\eta(x^*) \le \delta + g_y^\eta(x^*). \] The following result states the iteration-complexity bound for Algorithm \ref{alg:PBS} to obtain a $\delta$-solution to \eqref{eq:subproblem}. \begin{theorem}\label{thm:bundle} Algorithm \ref{alg:PBS} takes $\tilde {\cal O}\left(\eta_\mu L_\alpha^{\frac{2}{\alpha+1}} \left(\frac{1}{\delta}\right)^{\frac{1-\alpha}{\alpha+1}} + 1\right)$ iterations to terminate. \end{theorem} \begin{proof} Appendix \ref{sec:proximalsemi}. \end{proof} \subsection{Sampling without proximal map}\label{subsec:no opt-oracle} In this section we consider the RGO for $g$, namely, the sampling task from $\exp(-g_y^\eta(x))$ when the minimizer of $g_y^\eta(x)$ is not available. We use the optimization algorithm (Algorithm \ref{alg:PBS}) developed in Section \ref{subsec:bundle} to compute a $\delta$-solution to \eqref{eq:subproblem}. Based on this $\delta$-solution, we modify Algorithm \ref{alg:RGO} so that the expected number of runs for the rejection sampling is still properly bounded. To this end, let $J, \tilde x_J, x_J$ be the outputs of Algorithm \ref{alg:PBS} and define \begin{subequations}\label{eq:newh} \begin{align} h_1 &:= \frac{1}{2\eta_\mu}\|\cdot-x_J\|^2 + g_y^\eta(\tilde x_J) - \delta, \label{def:tf} \\ h_2 &:= \frac{1}{2\eta_\mu}\|\cdot-x^*\|^2 + \frac{L_\alpha}{\alpha+1}\|\cdot-x^*\|^{\alpha+1} + g_y^\eta(x^*). \label{def:h} \end{align} \end{subequations} Note we overload the notation $h_1, h_2$ to keep it simple. While $h_1$ in \eqref{def:tf} differs from that in \eqref{def:h1-h2-1} due to the unavailability of $x^*$, $h_2$ in \eqref{def:h} is the same as \eqref{def:h1-h2-2}. Note that $h_2$ is only used for analysis and thus the fact it depends on $x^*$ is not an issue. Algorithms \ref{alg:RGO-bundle} describes the implementation of RGO for $g$ based on Algorithm \ref{alg:PBS} and rejection sampling. It differs from Algorithm \ref{alg:RGO} in that it uses Algorithm \ref{alg:PBS} to compute an approximate solution to \eqref{eq:subproblem} instead of calling the proximal map $f$ as in \eqref{def:x*} and the Gaussian proposal is centered around the approximated minimizer instead of the minimizer. \begin{algorithm}[H] \caption{Rejection Sampling without Proximal Map} \label{alg:RGO-bundle} \begin{algorithmic} \STATE 1. Run Algorithm \ref{alg:PBS} to compute $x_J$ and $\tilde x_J$ \STATE 2. Generate $X\sim \exp(-h_1(x))$ \STATE 3. Generate $U\sim {\cal U}[0,1]$ \STATE 4. If \[ U \leq \frac{\exp(-g_y^\eta(X))}{\exp(-h_1(X))}, \] then accept/return $X$; otherwise, reject $X$ and go to step 2. \end{algorithmic} \end{algorithm} The following lemma is a counterpart of Lemma \ref{lem:h1h2} in the context of RGO without a proximal map and plays an important role in the complexity analysis of Algorithm \ref{alg:RGO-bundle} (Proposition \ref{prop:expected}). It reduces to Lemma \ref{lem:h1h2} when $\delta = 0$. To see this, note that \[ g^\eta_y(\tilde x_J)-\delta \le g_J^\eta(x_J)\le g_J^\eta(x^*)\le g_y^\eta(x^*) \le g_y^\eta(\tilde x_J). \] When $\delta = 0$, $\tilde x_J = x_J = x^*$, and $h_1$ in \eqref{def:tf} reduces to \eqref{def:h1-h2-1}. \begin{lemma}\label{lem:h1h2delta} Assume $f$ is convex and $L_\alpha$-semi-smooth and let $g, g_y^\eta$ be as in \eqref{eq:g} and \eqref{def:geta} respectively. Then, for every $x\in \mathbb{R}^d$, \begin{equation}\label{ineq:sandwich} h_1(x) \le g_y^\eta(x) \le h_2(x) \end{equation} where $h_1$ and $h_2$ are as in \eqref{eq:newh}. \end{lemma} \begin{proof} Appendix \ref{subsec:proof-sec3}. \end{proof} We next show that, just like Algorithm \ref{alg:RGO}, the number of rejections in Algorithm \ref{alg:RGO-bundle} is bounded above by a small constant when $\delta$ is properly chosen. Thus, the inexactness of the optimization \eqref{eq:subproblem} does not affect the final complexity much. In particular, as shown in Proposition \ref{prop:expected}, it only gets worse by a factor of $\exp(\delta)$ and the factor does not depend on the dimension $d$. Hence, the implementation of RGO for $g$ remains computationally efficient in practice. The proof is postponed to Appendix \ref{subsec:proof-sec3}. \begin{proposition}\label{prop:expected} Assume $f$ is convex and $L_\alpha$-semi-smooth and let $g, g_y^\eta$ be as in \eqref{eq:g} and \eqref{def:geta} respectively. If $\eta_\mu$ satisfies \eqref{ineq:eta_mu}, then the expected number of iterations in the rejection sampling of Algorithm \ref{alg:RGO-bundle} is at most $2\exp( \delta)$. \end{proposition} \subsection{RGO for smooth potentials}\label{subsec:smooth} To better understand our rejection sampling based algorithm for RGO, in this section, we consider the implementation of RGO (i.e., Algorithms \ref{alg:PBS} and \ref{alg:RGO-bundle}) in the smooth setting, and view it as a special case of the implementation in the semi-smooth setting with $\alpha=1$. For the ease of presentation, we do not assume the existence of the proximal map of $f$. We discuss the consequences of general complexity results Theorem \ref{thm:bundle} and Proposition \ref{prop:expected}. We also present a different complexity result that is specialized to the smooth setting with slight improvement. In the smooth case, the subgradient $f'$ becomes the gradient $\nabla f$ and \eqref{ineq:semi-smooth} becomes the $L_1$ smooth condition of $f$. Moreover, Algorithm \ref{alg:PBS} can be viewed as the generalization of the standard constant stepsize gradient descent method for convex smooth optimization. However, instead of requiring a small stepsize $\eta\le 1/L_1$ as in the standard gradient algorithm, Algorithm \ref{alg:PBS} could use any stepsize $\eta>0$. The following corollary provides the corresponding complexity of Algorithm \ref{alg:PBS} for finding a $\delta$-solution to \eqref{eq:subproblem}. It is a consequence of Theorem \ref{thm:bundle} with $\alpha=1$. \begin{corollary} Assume $f$ is convex and $L_1$-smooth and let $g, g_y^\eta$ be as in \eqref{eq:g} and \eqref{def:geta}, respectively. Algorithm \ref{alg:PBS} takes $\tilde {\cal O}\left(\eta_\mu L_1 + 1\right)$ iterations to terminate. \end{corollary} Following the ideas in Section \ref{subsec:no opt-oracle}, we can bound the complexity of rejection sampling in Algorithm \ref{alg:RGO-bundle}. The following corollary is a consequence of Proposition \ref{prop:expected} with $\alpha=1$. \begin{corollary}\label{cor:smooth-rejection} Assume $f$ is convex and $L_1$-smooth and let $g, g_y^\eta$ be as in \eqref{eq:g} and \eqref{def:geta}, respectively. If $\eta_\mu \le 1/(L_1 d)$, then the expected number of iterations in the rejection sampling is at most $2\exp(\delta)$. \end{corollary} The observant reader may have noticed that the approximation used in Proposition \ref{prop:key} to bound complexity is not necessary when $\alpha=1$. When $\alpha=1$, $h_2$ in \eqref{def:h} is a quadratic function, the analysis of rejection sampling can be simplified without resorting to Proposition \ref{prop:key}. Indeed, in this case, $\exp(-h_2)$ can be evaluated in closed-form with the standard Gaussian integral (Lemma \ref{lem:Gaussian}). Using this idea, we establish an alternative complexity result for Algorithm \ref{alg:RGO-bundle}, compared with Corollary \ref{cor:smooth-rejection}. The proof is postponed to Appendix \ref{subsec:proof-sec3}. \begin{proposition}\label{prop:smooth} Assume $f$ is convex and $L_1$-smooth and let $g, g_y^\eta$ be as in \eqref{eq:g} and \eqref{def:geta}, respectively. If $\eta_\mu \le 1/(L_1 d)$, then the expected number of iterations in the rejection sampling is at most $\exp(1/2+ \delta)$. \end{proposition} The result in Proposition \ref{prop:smooth} slightly improves that in Corollary \ref{cor:smooth-rejection} by only a factor of $\exp(1/2)/2$. Note that the complexity in Proposition \ref{prop:smooth} is tight since the bound $h_2$ is tight and the evaluation of $\exp(-h_2)$ is accurate. This implies that, our complexity results in Proposition \ref{prop:expected} for general convex semi-smooth potentials is tight to some degree. \section{Sampling from semi-smooth potentials}\label{sec:main} We now proceed to bound the total complexity to sample from a log-concave distribution $\nu$ in \eqref{eq:target} with a semi-smooth potential $f$. We combine our efficient algorithm (Algorithm \ref{alg:RGO-bundle}) of RGO for semi-smooth potentials in Section \ref{sec:RGO} and the convergent results for ASF (Algorithm \ref{alg:ASF}) in Section \ref{sec:formulation} to achieve this goal. With the three convergent results, Theorem \ref{thm:outer}, Theorem \ref{Thm:LC}, and Theorem \ref{Thm:Poincare} for ASF, we can establish three different total complexity for sampling. Since a general semi-smooth $f$ cannot be globally strongly convex in $\mathbb{R}^d$, to apply Theorem \ref{thm:outer}, we need to regularize $f$ with a quadratic function to make it strongly convex first. This regularization is carried out in Section \ref{subsec:strongly convex}, where we present the complexity to sample from $\exp(-f(x)-\mu \|x-x^0\|^2/2)$. This result is then used in Section \ref{subsec:convex} to bound the complexity to sample from $\nu\propto \exp(-f)$ with a proper $\mu>0$ to balance the complexity and the biased induced by the regularization. Note that apart from being a transition step to our result for sampling from $\nu$, the results in Section \ref{subsec:strongly convex} provide an efficient method to sample from composite potentials of the form $f+\mu\|\cdot-x^0\|^2/2$ and may be of independent interest. Finally, in Section \ref{sec:samplecomplexity} we apply ASF directly to our target distribution $\nu\propto \exp(-f)$ by setting $g=f$ in Algorithm \ref{alg:ASF}. Since Theorem \ref{Thm:LC}, and Theorem \ref{Thm:Poincare} do not require $\pi^X$ to be strongly-log-concave, we combine them with Proposition \ref{prop:expected} and Theorem \ref{thm:bundle} to give another two alternative estimations of the total complexity of the proximal sampling algorithm. \subsection{Complexity of sampling for regularized convex semi-smooth potentials}\label{subsec:strongly convex} Using the efficient implementation (Algorithm \ref{alg:RGO-bundle}) of RGO developed in Section \ref{sec:RGO} and the ASF (Algorithm \ref{alg:ASF}), we can sample from $\exp(-g(x))$ effectively as stated in the follow theorem. \begin{theorem}\label{thm:g} Let $x^0\in\mathbb{R}^d$, $\varepsilon>0$, $0\le\alpha\le 1$, $L_{\alpha}>0$, and $\mu>0$ be given. Assume $f$ is convex and $L_\alpha$-semi-smooth and let $g$ be as in \eqref{eq:g}. Set \begin{equation}\label{ineq:eta} \delta^{\frac{1-\alpha}{\alpha+1}}=\frac{1}{d}, \quad \eta= \frac{(\alpha+1)^{\frac{2}{\alpha+1}}}{(2L_\alpha)^{\frac{2}{\alpha+1}}d}. \end{equation} Then the ASF (Algorithm \ref{alg:ASF}) with Algorithm \ref{alg:RGO-bundle} as a RGO achieves $\varepsilon$ error in terms of KL divergence with respect to the target distribution $\pi^X \propto \exp(-g)$ in \begin{equation}\label{cmplx:mu} \tilde {\cal O}\left( \frac{L_\alpha^{\frac{2}{\alpha+1}} d}{\mu} \right) \end{equation} iteration, and each iteration queries ${\cal O}(1)$ subgradient oracle of $f$ and ${\cal O}(1)$ Gaussian distribution sampling oracle. \end{theorem} \begin{proof} By Theorem \ref{thm:outer}, starting from initial distribution $\rho_0^X$, it takes \begin{equation}\label{eq:iteration} \frac{1}{2\mu \eta} \log \frac{H_{\pi^X}(\rho_0^X)}{\varepsilon} \end{equation} iterations for Algorithm \ref{alg:ASF} to achieve $\varepsilon$ error to $\pi^X$ with respect to KL divergence. With the parameter choice \eqref{ineq:eta}, by Theorem \ref{thm:bundle} and Proposition \ref{prop:expected}, Algorithm \ref{alg:RGO-bundle} queries the subgradient oracle of $f$ ${\cal O}(1)$ times to terminate. The total complexity \eqref{cmplx:mu} then follows by plugging \eqref{ineq:eta} into \eqref{eq:iteration}. \end{proof} It is worth noting that even if the proximal map of $f$ is accessible and one instead uses Algorithm \ref{alg:RGO} for RGO, the total complexity for Algorithm \ref{alg:ASF} remains the same. This is because, with the choice of sampling stepsize $\eta$ and accuracy $\delta$ as in \eqref{ineq:eta}, the iteration complexity of Algorithm \ref{alg:PBS} is bounded by a small constant, adding no additional cost. \subsection{Complexity of sampling for convex semi-smooth potentials}\label{subsec:convex} Building upon Theorem \ref{thm:g} for sampling from $\pi^X\propto\exp(-g(x))=\exp(-f(x) - \mu\|x-x^0\|^2/2)$, we establish a complexity result, in the following theorem, to sample from the original target distribution $\nu\propto \exp(-f)$ by choosing a proper regularization constant $\mu$. \begin{theorem}\label{thm:f} Let $\nu\propto \exp(-f(x))$ be the target distribution where $f$ is convex and $L_\alpha$-semi-smooth. Let $x^0\in\mathbb{R}^d$ and $\varepsilon>0$ be given and set \begin{equation}\label{eq:mu} \mu = \frac{\varepsilon}{\sqrt{2}\left(\sqrt{{\cal M}_4} + \|x^0-x_\text{min}\|^2 \right)} \end{equation} where ${\cal M}_4=\int_{\mathbb{R}^d}\|x-x_\text{min}\|^4 d\nu(x)$ and $x_\text{min} \in \mathrm{Argmin}\, \{f(x): x\in \mathbb{R}^d\}$. Choose $\delta>0$ and $\eta>0$ such that \eqref{ineq:eta} holds and consider Algorithm \ref{alg:ASF} using Algorithm \ref{alg:RGO-bundle} as an RGO for step 1, applied to $\pi^X\propto \exp(-g)=\exp(-f-\mu\|\cdot-x^0\|^2/2)$. Then, the iteration-complexity bound to achieve $\varepsilon$ error to $\nu$ in terms of total variation is \begin{equation}\label{cmplx:mu1} \tilde {\cal O}\left( \frac{L_\alpha^\frac{2}{\alpha+1} d\left(\sqrt{{\cal M}_4} + \|x^0-x_\text{min}\|^2 \right) }{\varepsilon}\right). \end{equation} \end{theorem} \begin{proof} Let $\rho^X$ denote the distribution of the samples generated by Algorithm \ref{alg:ASF} using Algorithm \ref{alg:RGO-bundle} as an RGO. Following the proof of Corollary 4.1 of \cite{chatterji2020langevin}, we obtain \[ \|\rho^X- \nu\|_{\text{TV}} \le \|\rho^X-\pi^X\|_{\text{TV}} + \|\pi^X - \nu\|_{\text{TV}} \] and \begin{align*} \|\pi^X &- \nu\|_{\text{TV}} \le \frac12 \left( \int_{\mathbb{R}^d} [f(x)-g(x)]^2 \mathrm{d} \nu(x) \right)^{1/2} = \frac12 \left( \int_{\mathbb{R}^d} \left(\frac{\mu}{2}\|x-x^0\|^2 \right) ^2 \mathrm{d} \nu(x) \right)^{1/2}\\ &\le \frac\mu2 \left( \int_{\mathbb{R}^d} \left(\|x-x_\text{min}\|^2 + \|x_\text{min}-x^0\|^2 \right)^2 \mathrm{d} \nu(x) \right)^{1/2} \\ &\le \frac{\mu}2 \left( \int_{\mathbb{R}^d} \left(2\|x-x_\text{min}\|^4 + 2\|x_\text{min}-x^0\|^4 \right) \mathrm{d} \nu(x) \right)^{1/2} \\ &= \frac{\sqrt{2}\mu}2 \left( {\cal M}_4 + \|x_\text{min}-x^0\|^4 \right)^{1/2} \le \frac{\sqrt{2}\mu}{2} \left(\sqrt{{\cal M}_4} + \|x_0-x_\text{min}\|^2 \right) = \frac{\varepsilon}{2} \end{align*} where the last identity is due to the definition of $\mu$ in \eqref{eq:mu}. Hence, it suffices to derive the iteration-complexity bound for Algorithm \ref{alg:ASF} to achieve $\|\rho^X-\pi^X\|_{\text{TV}}\le \varepsilon/2$, which is \eqref{cmplx:mu1} in view of Theorem \ref{thm:g} with $\mu$ as in \eqref{eq:mu}. Note that even though the complexity result in Theorem \ref{thm:g} is with respect to KL divergence, one can get the same order of complexity with respect to total variation using Pinsker inequality. \end{proof} \subsection{Other complexity results of sampling for semi-smooth potentials}\label{sec:samplecomplexity} The ASF exhibits nice convergent property even when $g$ is not strongly convex, as shown in Theorem \ref{Thm:LC}, and Theorem \ref{Thm:Poincare}. We next combine our algorithm (Algorithm \ref{alg:RGO-bundle}) of RGO and these results to establish several different complexity bounds to sample from log-concave distribution $\nu\propto \exp(-f)$ with semi-smooth $f$. First, using Theorem \ref{Thm:LC} we establish the following. \begin{theorem} Assume $f$ is convex and $L_\alpha$-semi-smooth, then Algorithm \ref{alg:ASF} (with $g=f$), initialized with $\rho_0^X$ and stepsize $\eta \asymp 1/(L_\alpha^\frac{2}{\alpha+1} d)$, using Algorithm \ref{alg:RGO-bundle} (with $\mu=0$) as a RGO has the iteration-complexity bound \begin{equation} {\cal O}\left(\frac{L_\alpha^\frac{2}{\alpha+1} d W_2^2(\rho_0^X,\nu)}{\varepsilon}\right) \end{equation} to achieve $\varepsilon$ error to the target $\nu\propto \exp(-f)$ in terms of KL divergence. \end{theorem} \begin{proof} The result follows directly from Theorem \ref{Thm:LC}, Theorem \ref{thm:bundle} and Proposition \ref{prop:expected} with the choice of stepsize $\eta \asymp 1/(L_\alpha^\frac{2}{\alpha+1} d)$. \end{proof} Any log-concave satisfies the Poincar\'e inequality. Thus, we can use Theorem \ref{Thm:Poincare} to establish the following. \begin{theorem}\label{thm:Renyi} Assume $f$ is convex and $L_\alpha$-semi-smooth, then Algorithm \ref{alg:ASF} (with $g=f$), initialized with $\rho_0^X$ and stepsize $\eta \asymp 1/(L_\alpha^\frac{2}{\alpha+1} d)$, using Algorithm \ref{alg:RGO-bundle} (with $\mu=0$) as a RGO has the iteration-complexity bound \begin{equation} \tilde{\cal O}\left(C_{\rm PI}L_\alpha^\frac{2}{\alpha+1} d \right) \end{equation} to achieve $\varepsilon$ error to the target $\nu\propto \exp(-f)$ in terms of Chi-squared divergence, and \begin{equation} \tilde {\cal O}\left(C_{\rm PI} L_\alpha^\frac{2}{\alpha+1} qd R_{q,\nu}(\rho_0^X)\right) \end{equation} to achieve $\varepsilon$ error in terms of R\'enyi divergence $R_{q,\nu}$ ($q\ge 2$). Here $C_{\rm PI}$ denotes the Poincar\'e constant of $\nu$. \end{theorem} \begin{proof} The result is a direct consequence of Theorem \ref{Thm:Poincare}, Theorem \ref{thm:bundle} and Proposition \ref{prop:expected} with the choice of stepsize $\eta \asymp 1/(L_\alpha^\frac{2}{\alpha+1} d)$. \end{proof} \section{Sampling from composite potentials}\label{sec:composite} In this section, we consider sampling from a log-concave distribution $\nu\propto\exp(-f(x))$ associated with a composite potential $f$. In particular, we consider the setting where $f = f_1+f_2$, and $f_1, f_2$ are convex, $L_1$-smooth and convex, $L_\alpha$-semi-smooth, respectively. Clearly, such a $f$ satisfies that, for every $u, v\in \mathbb{R}^d$, \begin{equation}\label{ineq:subgradient} \|f'(u) - f'(v)\| \le L_\alpha\|u-v\|^\alpha + L_1\|u-v\|. \end{equation} We shall call such a potential $(L_1,L_\alpha)$-smooth-semi-smooth. Note that all the results in this section apply to any convex and $(L_1,L_\alpha)$-smooth-semi-smooth potentials. These potentials do not have to be a composite one as above and our algorithms do not rely on the decomposition of the potential. This setting is a generalization of the semi-smooth setting studied in the previous sections since it reduces to the latter when $L_1=0$. It turns out that both Algorithm \ref{alg:ASF} and the implementation for RGO, Algorithm \ref{alg:RGO-bundle}, developed for semi-smooth sampling can be applied directly to this new setting with properly chosen step sizes. Below we extend the analysis in Section \ref{sec:RGO} and Section \ref{sec:main} to this more general setting and establish several iteration-complexity results for sampling from composite $f$. Before presenting the results, we make some observations of the $(L_1,L_\alpha)$-smooth-semi-smooth assumption \eqref{ineq:subgradient}. If $L_\alpha=0$, then \eqref{ineq:subgradient} becomes to $\|\nabla f(u) - \nabla f(v)\| \le L_1\|u-v\|$, and hence $f$ is $L_1$-smooth. If $L_1=0$, then \eqref{ineq:subgradient} reduces to \eqref{ineq:semi-smooth}, and hence $f$ is $L_\alpha$-semi-smooth. To bound the expected number of runs in Algorithm \ref{alg:RGO-bundle}, we need to construct a different $h_2$ to bound $g_y^\eta$; the one \eqref{def:h} no longer works in the setting with composite potentials. Based on the property of $(L_1,L_\alpha)$-smooth-semi-smooth potentials, we construct $h_2$ as follows. The proof is postponed to Appendix \ref{subsec:proof-sec5}. \begin{lemma}\label{lem:composite} Assume $f$ is convex and $(L_1,L_\alpha)$-smooth-semi-smooth and let $g, g_y^\eta$ be as in \eqref{eq:g} and \eqref{def:geta}, respectively. Define \begin{equation}\label{def:h2-hybrid} h_2(x) := \frac{L_\alpha}{\alpha+1} \|x-x^*\|^{\alpha+1} + \frac{1}{2\eta_{\mu,L_1}}\|x-x^*\|^2 + g_y^\eta(x^*) \end{equation} where \begin{equation}\label{def:eta-mu-L} \eta_{\mu,L_1}:=\frac{\eta}{1+\eta\mu + \eta L_1} \end{equation} Then, $h_2(x)\ge g_y^\eta(x)$ for $\forall x\in \mathbb{R}^d$. \end{lemma} With Lemma \ref{lem:composite} in hand, we can bound the complexity of Algorithm \ref{alg:RGO-bundle} as follows. The proof is postponed to Appendix \ref{subsec:proof-sec5}. \begin{proposition}\label{prop:composite} If \begin{equation}\label{ineq:assumption3} \eta_\mu \le \min \left\lbrace \frac{(\alpha+1)^{\frac{2}{\alpha+1}}}{(2L_\alpha)^{\frac{2}{\alpha+1}}d}, \frac{1}{L_1 d} \right \rbrace, \end{equation} then the expected number of iterations of Algorithm \ref{alg:RGO-bundle} in rejection sampling is at most $2\exp(1/2+ \delta)$. \end{proposition} To use Algorithm \ref{alg:RGO-bundle}, we need to obtain a $\delta$-solution to \eqref{eq:subproblem}. Algorithm \ref{alg:PBS} is applicable but the complexity analysis is absent. Below we establish an iteration-complexity bound of Algorithm \ref{alg:PBS} in obtaining a $\delta$-solution to \eqref{eq:subproblem}. \begin{theorem}\label{thm:bundle-hybrid} Algorithm \ref{alg:PBS} takes $\tilde {\cal O}\left(\eta_\mu L_1 + \eta_\mu L_\alpha^{\frac{2}{\alpha+1}} \left(\frac{1}{\delta}\right)^{\frac{1-\alpha}{\alpha+1}} + 1\right)$ iterations to terminate. \end{theorem} \begin{proof} Appendix \ref{sec:hybridopt}. \end{proof} Through the above arguments, we show that our algorithm of the RGO designed for semi-smooth potentials is equally effective for $(L_1,L_\alpha)$-smooth-semi-smooth potentials. Combining Lemma \ref{lem:composite} and Theorem \ref{thm:bundle-hybrid} with the convergence results for ASF we obtain the following iteration-complexity bound for sampling from $(L_1,L_\alpha)$-smooth-semi-smooth potentials. The proof is similar to that in Section \ref{sec:main} and is thus omitted. \begin{theorem}\label{thm:all} Assume $f$ is a convex and $(L_1,L_\alpha)$-smooth-semi-smooth potential. Consider Algorithm \ref{alg:ASF}, initialized with $\rho_0^X$ and stepsize $\eta \asymp \min\{1/(L_\alpha^\frac{2}{\alpha+1} d), 1/(L_1d)\}$, using Algorithm \ref{alg:RGO-bundle} as a RGO.\\ 1. Applying Theorem \ref{thm:outer}, the total complexity is \[ \tilde {\cal O}\left( \frac{(L_\alpha^\frac{2}{\alpha+1}\vee L_1)d \sqrt{{\cal M}_4} }{\varepsilon}\right) \] to achieve $\varepsilon$ error in terms of total variation.\\ 2. Applying Theorem \ref{Thm:LC}, the total complexity is \[ {\cal O}\left(\frac{(L_\alpha^\frac{2}{\alpha+1}\vee L_1) d W_2^2(\rho_0^X,\nu)}{\varepsilon}\right) \] to achieve $\varepsilon$ error in terms of KL divergence.\\ 3. Applying Theorem \ref{Thm:Poincare}, the total complexity is \[ \tilde{\cal O}\left((L_\alpha^\frac{2}{\alpha+1}\vee L_1) d C_{\rm PI}\right) \] to achieve $\varepsilon$ error in terms of Chi-squared divergence, and \[ \tilde{\cal O}\left((L_\alpha^\frac{2}{\alpha+1}\vee L_1) qd C_{\rm PI} R_{q,\nu}(\rho_0^X)\right) \] to achieve $\varepsilon$ error in terms of R\'enyi divergence $R_{q,\nu}$ ($q\ge 2$). \end{theorem} If in addition $f$ is ${\lambda}$-strongly convex, then Theorem \ref{thm:outer} can be applied to establish stronger complexity results as follows. The proof is straightforward and is again omitted. \begin{theorem}\label{thm:last} Assume $f$ is a $\lambda$-strongly convex and $(L_1,L_\alpha)$-smooth-semi-smooth potential, then Algorithm \ref{alg:ASF} (with $g=f$), initialized with $\rho_0^X$ and stepsize $\eta \asymp \min\{1/(L_\alpha^\frac{2}{\alpha+1} d), 1/(L_1d)\}$, using Algorithm \ref{alg:RGO-bundle} (with $\mu=0$) as a RGO has total complexity \[ \tilde{\cal O}\left(\frac{(L_\alpha^\frac{2}{\alpha+1}\vee L_1) d}{\lambda}\right) \] to achieve $\varepsilon$ error in terms of KL divergence, and \[ \tilde{\cal O}\left(\frac{(L_\alpha^\frac{2}{\alpha+1}\vee L_1) qd}{\lambda}\right) \] to achieve $\varepsilon$ error in terms of R\'enyi divergence $R_{q,\nu}$ ($q\ge 1$). \end{theorem} \section{Conclusion}\label{sec:conclusion} In this paper we presented a novel sampling algorithm from convex semi-smooth potentials or convex composite potentials with semi-smooth components. Our algorithm is based on the recent ASF which utilizes Gibbs sampling over an augmented distribution. In each iteration of the ASF, one needs to sample from a quadratically regularized version of the target potential, which is itself a challenging task due to the non-smoothness of the problem. In this work we presented a rejection sampling based scheme with a tailored proposal to sample from the regularized version of the target potential. Moreover, we developed a novel technique to bound the complexity of this scheme. By combining our scheme with the ASF we established a sampling algorithm for convex semi-smooth potentials or convex composite potentials with semi-smooth components, with better complexity than all the existing methods. In the future, we plan to investigate the sampling settings where the potential is semi-smooth or composite with a semi-smooth component, but not necessarily convex. \section*{Acknowledgement} This work was supported by NSF under grant 1942523 and 2008513. \bibliographystyle{plain}
{'timestamp': '2022-03-01T02:57:37', 'yymm': '2202', 'arxiv_id': '2202.13975', 'language': 'en', 'url': 'https://arxiv.org/abs/2202.13975'}
arxiv
\section{Introduction} This demo file is intended to serve as a ``starter file'' for IEEE conference papers produced under \LaTeX\ using IEEEtran.cls version 1.8b and later. I wish you the best of success. \hfill mds \hfill August 26, 2015 \subsection{Subsection Heading Here} Subsection text here. \subsubsection{Subsubsection Heading Here} Subsubsection text here. \section{Conclusion} The conclusion goes here. \subsection{Reviewer number 2} We have addressed both of your comments. The ranges for Cartesian and the Polar representations were added to Section~\ref{sec:data_representation} and the typos in Section~\ref{sec:model} were fixed. \subsection{Reviewer number 3} \subsubsection{Problem with the literature methods and contribution of the paper} The main contribution of the paper over literature methods is that CNNs can learn the features. Traditional methods rely on hand-crafted features, which are rigid and pre-determined, i.e. once it is set, it can not adapt to the input data. Based on your comment we emphasised this point in the introduction. \subsubsection{Using EMNIST rather than a more challenging dataset} Our intention is to introduce a new CNN model that deals with non-common space of contours, not to tackle a specific unsolved dataset. We chose the EMNIST dataset due to its size, simple objects (letters and digits). We needed a dataset to verify the applicability and initial performance of our model. \subsubsection{Separating the letters and digits subsets} This is done to avoid ambiguity among some of the letters and the digits. We revised Section~\ref{sec:dataset} to include this. \subsubsection{Use of letter subset for comparison} Conducting the comparison between the activation layers, pooling layers, and the different data representations on both the digits and letters subsets would be redundant. We chose the letters subset over the digits' because it is more complex. The model was trained and tested on the official train and test split of the dataset. This was added to Section~\ref{sec:experiments}. \subsubsection{... why not use the Alexnet itself}. Our intention is to introduce a new CNN model that deals with non-common space of contours which is not handled by AlexNet. \subsubsection{There is no comparison with literature methods} Please refer to our response to comments 1 and 5. \subsubsection{input of the model} This was clarified in Section~\ref{sec:model}. \subsubsection{Extracting contour from images} The extraction algorithm we used was added to Section~\ref{sec:dataset}. \subsubsection{The rest of the comments} All of the other issues you pointed out in the rest of your comments were fixed/addressed in the paper. \subsection{Reviewer number 4} \subsubsection*{General comments} \begin{itemize} \item Title was fixed \item We unified the mentions of the priority pooling layers \item We clarified the figures and labeled unlabeled axis-es. Regarding the confusion matrices; it was an issue of resolution. In order to solve this, we regenerated the confusion matrices in Figures~\ref{fig:contour_AL_confusion_matrix} and~\ref{fig:contour_letters_confusion_matrix}. Note that in order to regenerate the confusion matrices we retrained the models from scratch. \end{itemize} \subsubsection*{Specific Suggestions} Here we would like to respond to a few comments. Regarding the rest, in most cases, we revised the paper as per your suggestions. 4. As per your suggestion we unified the notation of the depth. The reason D is mentioned in the description of equation (1), but not in it is that we needed a depth value to describe the kernel and the input sizes. 6. Yes, you understood correctly, kernel is applied on vertex with the lowest magnitude and their adjacent neighbors. We used a kernel of size 3, however the kernel can be larger. We refined our explanation. \section{Conclusion \& Future work} \label{sec:conclusion} This paper presents ContourCNN, a CNN for contour data analysis. We introduced 1D circular convectional layer for convolution on a circular data representation, which preserves the circularity of the data after the operation. To deal with the varying sparsity level of information of the contour data we introduced a number of priority pooling layers that pools only the vertices with the lowest feature magnitude. We showed the effectiveness of the model by classifying the contours of the digits and letters from the EMNIST dataset and compared the results to the similarly structured CNN, AlexNet. In addition, we provided a comparison of the accuracy and loss between the different priority pooling layers, activation function, and the input data representation. In future work, we plan to explore the use of ContourCNN for contour segmentation using an encoder-decoder architecture of the model, where the pooled vertices are remembered in the down-sampling stage of the encoder and unpooled in the up-sampling stage of the decoder. We will also consider extending the ContourCNN to process nested contour. Lastly, we would like to end on the following note: while we used the proposed model to analyse contours, we realized it can be used to process other similar data forms (data with circular structure or data sequences that include redundant information). \section{Dataset} \label{sec:dataset} Existing shapes dataset such as MPEG-7~\cite{latecki2000shape} (1400 shapes of 70 classes) and Animal Shapes~\cite{bai2009integrating} (2000 shapes of 20 classes) contain insufficient number of samples to train CNNs models. In order to test the proposed model, we needed a sufficiently large dataset suitable for training deep-learning models. We chose to extract the contours from the EMNIST dataset~\cite{cohen2017emnist} which contain a large number of hand-written digits, uppercase and lowercase letter images. The contours were extracted using the algorithm~\cite{suzuki1985topological} implemented in the OpenCV library.\\ Our experiments were conducted on two separate subset of the EMNIST dataset. The subsets of digits consisting of images from 10 digit classes (0-9), a total of 402,953 images (344,307 for training and 58,646 for testing); and the subset of uppercase letters consisting of images from 26 classes (A-Z), a total of 220,304 images (208,364 for training and 11,941 for testing). We chose to split those two subset to avoid ambiguity between some of the letters and some of the digits, for example, in some cases the digits 1 and 0 cannot be differentiated from the letters I and O respectively. \subsection{Data representation} \label{sec:data_representation} We experimented with two different representation of the contour data. The first is a normalized Cartesian representation- each contour is represented as a sequence of the normalized $x,y \in [0,1]$ position points of its vertices. In the second, each contour is represented as a sequence of an angles and a line lengths, we'll refer to this representation as the "Polar representation". Each angle and line length $(\alpha, L)$ represents a vertex on the contour. As shown in Figure~\ref{fig:contour_data_representation}, in each $(\alpha, L)$ vertex representation, $\alpha \in [-\pi, \pi]$ equals the angle between the two adjacent lines, and $L$ is the length of the line between the given vertex and the next vertex in the sequence.\\ \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/angle_length.png} \caption{Polar representation of a contour. The vertex $v_1$ is represented by the angle $\alpha$ (the angle between the two lines), and the line length $L$ the length of the line between the vertex $v_1$ and the next vertex in the sequence $v_2$} \label{fig:contour_data_representation} \end{figure} \section{Experimental Evaluation} \label{sec:experiments} To evaluate the performance of our model, we conducted several experiments comparing activation functions, the different priority pooling layers, and the Cartesian and Polar representations (discussed in Section~\ref{sec:data_representation}). Furthermore, we compare the performance of our model with AlexNet. Those comparison were conducted on the letters subset, because it offer more complex and varied data than the digits subset. Finally, we report the results of the best performing model on the letter and the digits subsets from EMNIST. In each one of the experiments the model was trained and tested using the official train and test split of EMNIST. \subsubsection{Activation function} In this experiment we compared the performance of the model with different activation functions. We trained three networks with the activation functions, Sgimoid, TanH, and ReLU using the letters subset, the Cartesian representation, and with the Remove One priority pooling layers. Figure~\ref{fig:contour_activation_results} shows the test loss and accuracy of each network during the training process. We can see that the two networks using Sigmoid and ReLU activation function reached similar accuracy and loss values. Using the ReLU activation function the network reached a higher accuracy faster than using the Sigmoid function. While using TanH activation function the network was unable to learn and got stuck in a local minima. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/activation_test_accuracy.png} \includegraphics[width=0.5\textwidth]{images/activation_test_loss.png} \caption{The loss and accuracy of a number of networks using different activation functions on the test set during the training process} \label{fig:contour_activation_results} \end{figure} \subsubsection{Priority pooling layers} In this experiment we compare the different priority pooling layer introduced in Section~\ref{sec:priority_pooling}. Similar to the previous experiment, three networks with different priority pooling layers and ReLU activation function were trained using the letters subset and the Cartesian representation. Note that this compression only affect the first three priority pooling layers, the global average pooling layer preceding the full connected layers remains unchanged. Figure~\ref{fig:contour_pooling_results} shows the accuracy and loss of the networks on the test subset. As can be seen the networks which include the Remove One and the Max priority pooling layers reached similar accuracy. However, the two networks achieve different loss values on the test set. This suggests, the network with the Remove One priority pooling is more confident concern its classification, i.e. it gives a higher probability to the correct classification. As seen, the networks with the average priority pooling layer converges and obtained around 90\% accuracy rate on the test subset, but it did not reach a higher accuracy as the other two networks. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/pooling_test_accuracy.png} \includegraphics[width=0.5\textwidth]{images/pooling_test_loss.png} \caption{The loss and accuracy of networks using different priority pooling layers on the test set during the training process} \label{fig:contour_pooling_results} \end{figure} \subsubsection{Experimenting with data representations} In the following experiment we trained two identical networks with Remove One priority pooling layers and ReLU activation function on the letters subsets with the Cartesian and Polar data representations mentioned in Section~\ref{sec:data_representation}. Figure~\ref{fig:contour_data_representation_accuracy} shows the accuracy of the two networks on the test subset during training. Unsurprisingly, the network trained using the Cartesian representation reached higher accuracy faster than the network using the Polar representation. There will always be ambiguity between certain letters in the Polar representation. As can be seen in Figure~\ref{fig:contour_m_e_AL}, the letters M, W, and E have an almost identical Polar representation, since this representation is rotation invariant, rotating the letter M $180^{\circ}$ results in the letter W with the same Polar representation as the letter M. Such ambiguity can be seen in the confusion matrix of the model in Figure~\ref{fig:contour_AL_confusion_matrix}. \paragraph{Shape simplification effects} the priority pooling layers pools/removes a selected features corresponding to points on input contour. Thus, we can visualize the progress of the network by redrawing the contour after each priority pooling without the pooled points. Interestingly, we observed that the network trained using the Polar representation seemingly simplifies the contour shape. As can be seen in Figure~\ref{fig:contour_letters_simplification}, when drawing the contour after each priority pooling layer in the network, the contour of the letters is simplified as it traverse down the network's pooling layers. This can be attributed to the fact that the activation of vertices that contain more information are larger than the activations of those with fewer information. Therefore, the priority pooling layers will first pool/remove redundant contour vertices or those with little information. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/representation_test_accuracy.png} \caption{The accuracy of two networks on the test set during training. The two networks were trained using two different data representations, the Cartesian representation and the Polar representation} \label{fig:contour_data_representation_accuracy} \end{figure} \begin{figure} \centering \includegraphics[width=0.15\textwidth]{images/M.jpg} \includegraphics[width=0.15\textwidth]{images/W.jpg} \includegraphics[width=0.15\textwidth]{images/E.jpg} \caption{Example contour instances of the letters M, W and E in the test subset} \label{fig:contour_m_e_AL} \end{figure} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/confusion_matrix_AL.png} \caption{The confusion matrix of the network trained using the Polar representation. The color of each cell represent the number of samples classified in it. Lighter color means more samples (as shown in the color bar to the right)} \label{fig:contour_AL_confusion_matrix} \end{figure} \begin{figure} \centering \includegraphics[width=0.11\textwidth]{images/pooling_labels.jpg} \includegraphics[width=0.11\textwidth]{images/pooling_M.jpg} \includegraphics[width=0.11\textwidth]{images/pooling_O.jpg} \includegraphics[width=0.11\textwidth]{images/pooling_T.jpg} \caption{This figure show the simplification effect happening in the network. The row shows the input contour of the letter, the resulting contour after each pooling layer. The coloured circles represent the activations of each contour vertices; the size and colour of the circles reflect the magnitude of each activation} \label{fig:contour_letters_simplification} \end{figure} \subsubsection{Comparing with regular CNN classification model} Here we compare our approach with a more established 2D classification CNN. Since the ContourCNN model are able to process one layer contours, training a 2D CNN using the original data would give it an unfair advantage. Because the original images include information missing from the contour data (e.g. the holes inside the letters A,B, D, and O). Therefore, in order to compare the two approaches, we generated 2D images by drawing the filled polygon represented by the extracted contour data (the silhouette of the letters) as can be seen in Figure~\ref{fig:2d_generated_data}. This way we insure that the two approaches are trained in a fair manner, i.e. using the same level of detail/information. Since AlexNet~\cite{krizhevsky2012imagenet} has a similar architecture to our model, we chose to train it on the generated 2D images. The configuration of the network can be seen in Table~\ref{tab:alexnet_network_conf}. As can be seen in Figure~\ref{fig:contourcnn_alexnet_accuracy} the two approaches reach similar accuracy of around 96\%. This results shows the effectiveness of the proposed model as it managed to achieve similar accuracy results to a more established model such as AlexNet. \begin{figure} \centering \includegraphics[width=0.15\textwidth]{images/2d_O.png} \includegraphics[width=0.15\textwidth]{images/2d_s.png} \includegraphics[width=0.15\textwidth]{images/2d_t.png} \caption{Example of the generated 2D images from the contour data of the letters O, S, and T} \label{fig:2d_generated_data} \end{figure} \begin{table}[htb] \centering \begin{tabular}{c} \hline Conv2D $f_{in} \times 64$\\ MaxPool2D $k=3, s=2$\\ Conv2D $64 \times 192$\\ MaxPool2D $k=3, s=2$\\ Conv2D $192 \times 384$\\ Conv2D $384 \times 256$\\ MaxPool2D $k=3, s=2$\\ AvgPool $\rightarrow (6,6)$\\ FCN $6\cdot 6 \cdot 256 \times 4096$\\ FCN $4096 \times f_{out}$\\ \hline \\ \end{tabular} \caption{AlexNet configuration} \label{tab:alexnet_network_conf} \end{table} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/test_accuracy_alexnet_contourcnn.png} \caption{The test accuracy of two approaches; ContourCNN: training using contour data, AlexNet: CNN training using the generated 2D images.} \label{fig:contourcnn_alexnet_accuracy} \end{figure} \subsubsection{Results of the best model on the letters and digits subsets} The best results were reached by the model with Remove One priority pooling layer, ReLU activation function, and trained using the Cartesian representation. This model achieved around a 96\% accuracy rate on the uppercase letters subset and round a 96.7\% accuracy on the digits subset. The Figures~\ref{fig:contour_letters_confusion_matrix} and~\ref{fig:contour_digits_confusion_matrix} show the confusion matrices for the results of the trained network on the uppercase letters and digits subsets. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/confusion_matrix_xy.png} \caption{The confusion matrix of the classification results of the network trained on the letters subset. The color of each cell represent the number of samples classified in it. Lighter color means more samples (as shown in the color bar to the right)} \label{fig:contour_letters_confusion_matrix} \end{figure} \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/confusion_matrix_digits.png} \caption{The confusion matrix of the classification results of the network trained on the digits subset. The color of a cell indicates the number of samples were used for classification. Lighter color means more samples (as shown in the color bar to the right)} \label{fig:contour_digits_confusion_matrix} \end{figure} \section{Introduction} \label{sec:introduction} In many computer vision tasks such as object detection, classification, and instance segmentation, object's shape offers vital information for the task at hand. This paper focuses on 2D objects, which often represented using its bounding contour. Bounding contours are commonly represented as circular sequences of points or polygons. Such a representation plays an important role in many shape analysis tasks such as shape matching, classification, and segmentation. However, a significant challenge of representing shapes using contour is the lack of common space, i.e. a shape can be represented by a huge number of contour representations, since the origin point can be defined anywhere on the contour of the shape, and the contour can have an arbitrarily sparsity level of points on the shape's contour. Over the years a number of shape analysis methods were proposed that make the use of a designed smart features such as shape context for matching~\cite{belongie2002shape, ling2007shape}. Others such as~\cite{ramesh2015shape, bai2014shape} combine local and global features using the Bag of Words model for shape classification. In addition, there has been a number methods that uses machine learning algorithms such as SVM~\cite{ramesh2015shape} and deep Bayesian networks~\cite{li2016learning} to classify shapes using their features. Over the last decades, convolutional neural networks (CNNs) have proved their effectiveness in addressing complex tasks such as classification, detection, and segmentation. CNNs can learn and extract features as opposed to traditional learning free methods that rely on hand-crafted features. However, CNNs are geared toward regular representation, such as vectors and matrices. Due to the irregular representation of contours, CNNs have not been used in shape analysis tasks. In this paper, we propose a new CNN for contour analysis. The proposed network handles the lack of common space of the contour data mentioned above. It includes a circular convolutional layers and a priority pooling layers. The circular convolutional layers deal with the circularity of the contour representation. To deal with the varying sparsity level of the contours, we introduce a number of priority pooling layers inspired by the pooling layer used in MeshCNN~\cite{hanocka2019meshcnn}, in which only points with low feature magnitude are pooled. To show the effectiveness of the proposed network, we apply it to classify shapes of digits and letters extracted from the EMNIST dataset . The remainder of this paper is organised as follows: In section~\ref{sec:related_works} we summarize a number of related work done in the area of shape classification. We describe the proposed model in section~\ref{sec:model}. Training datasets and data representation are discussed in section~\ref{sec:dataset}. In section~\ref{sec:experiments}, experimental results are presented and discussed. Finally, we conclude and discuss future works in section~\ref{sec:conclusion} \section{Model} \label{sec:model} We propose a novel convolutional neural network that includes a custom-built 1D convolutional and pooling layers. Where the input of this network is a sequence of points representing a one layer contour. We introduce a 1D circular convolution layer, and a number of priority pooling layers. \subsection{1D Circular convolutional layer} A sequence of circular data (such as a contour) is roll invariant, i.e. the sequence can be shifted (in a circular manner) and still represent the same data. Regular convolutional layers assume a unique start and end points in the input data, which removes the circularity of the data sequence. Thus, we apply circular convolutional layer. The circular convolution operation is defined as follow: \begin{equation} u_{i} = (\sum_{j=0}^{M-1}{k_j\cdot x_{(i-\frac{M-1}{2} + j)\ mod\ N}}) + b_k \end{equation} where $x$ is the input 1D tensor with length $N$ and depth $D$, i.e. $x = [x_1, x_2, ..., x_N]$, where each $x_i$ is of size $1\times D$. $k$ is a 1D kernel of size $M$ and depth $D$ with bias $b_k$, and $u$ is the 1D output tensor of the convolution operation. As can be seen in Figure~\ref{fig:cirular_conv}, circular convolution work similar to regular convolution, but handles the end vertices differently. When the kernel is on a boundary of the input it wraps around to the other end. \begin{figure} \centering \includegraphics[width=0.4\textwidth]{images/circular_conv.png} \caption{Circular convolution} \label{fig:cirular_conv} \end{figure} \subsection{Priority pooling layers} \label{sec:priority_pooling} The different vertices on a contour carry various levels of geometric information. A vertex that lies on a straight line which is defined by its immediate neighbours has little information; its position can be inferred from its two adjacent vertices. \begin{figure} \centering \includegraphics[width=0.4\textwidth]{images/reg_pooling.png} \caption{Illustration of the regular pooling operation with kernel of size three and stride value equal to two} \label{fig:regular_pooling} \end{figure} Typical pooling operations, such as average and max, are applied uniformally in a local manner, regardless of the global relative importance of the input vertices (as illustrated in Figure~\ref{fig:regular_pooling}). To overcome this limitation and apply irregular global pooling, we introduce priority pooling layers, that reduce the dimensions of an input tensor by iteratively considering the magnitude of the features. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/r_o_p_pooling.png} \caption{Illustration of the Remove One priority pooling operation. The colored bars represent the magnitude of each one of the feature vectors.} \label{fig:remove_one_priority_pooling} \end{figure} {\bf Remove One priority pooling} accepts an input tensor of dimensions $1\times N \times D$, where $N$ is the length of the input and $D$ is its depth (the number of features for each data point). The magnitude of each feature vertex is calculated using $L_2$ and utilized to prioritized the list of vertices, then the vertex with the lowest priority is removed (see Figure~\ref{fig:remove_one_priority_pooling}). This operation is repeated iteratively until the input tensor reaches a desired dimension. The desired dimensions we used are shown in Table~\ref{tab:contourcnn_network_conf}. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{images/m_a_p_pooling.png} \caption{Illustration of the Max and Average priority pooling operation with kernel of size three. The colored bars represent the magnitude of each one of the feature vectors.} \label{fig:max_avg_priority_pooling} \end{figure} {\bf Max and Average priority pooling} layers work similar to the Remove One priority pooling. However, instead of removing the feature vertex with the lowest priority, the vertex with the lowest priority is pooled (either average or max). After each pooling operation the features' magnitudes of the remaining vertices are recalculated (see Figure~\ref{fig:remove_one_priority_pooling}). Similar to the Remove One, this priority pooling is applied iteratively until the input tensor reaches a desired dimension. \subsection{Network architecture} Similar to a typical 2D classification CNNs, our network architecture consists of two sub-networks: a feature extraction convolutional network, and a fully connected classification network. The feature extraction network consists of four blocks of circular convolutional layers, a batch normalization layer, and a priority pooling layer. The extracted features are average pooled and fed to a fully connected classification network.\\ The architecture and configuration of the network can be seen in Table~\ref{tab:contourcnn_network_conf}. Such architecture were used to imitate AlexNet's and the parameters were further tuned through experiments. \begin{table}[htb] \centering \begin{tabular}{c} \hline CircConv $f_{in} \times 32$\\ PriorityPool $\rightarrow 40$\\ CircConv $32 \times 64$\\ PriorityPool $\rightarrow 30$\\ CircConv $64 \times 128$\\ PriorityPool $\rightarrow 20$\\ GlobalAvgPool\\ FCN $128 \times 80$\\ FCN $80 \times f_{out}$\\ \hline \\ \end{tabular} \caption{Network configuration. CircConv $a \times b$ is a circular convolutional layer, where $a$ is the number of features (the depth) of the input, and $b$ is the output. PriorityPool $\rightarrow N$ is a priority pooling layer, where $N$ is the length of the output. FCN $c\times d$ is a fully connected layer with $c$ input neurons and $d$ output neurons. $f_{in}$ is the number of features of the input of the network and $f_{out}$ is the number of outputs, i.e. number of classes} \label{tab:contourcnn_network_conf} \end{table} \section{Related work} \label{sec:related_works} Existing solutions to the problem of shape classification can be split into two categories, learning and non-learning based solutions. Huttenlocher~\etal~\cite{huttenlocher1993comparing} and Liu~\etal~\cite{liu2010fast} compare and match shapes by calculating the similarity between two shapes using the Hausdorff and the Chamfer distance function, respectively. Other approaches extract shape descriptors such as the Shape Context~\cite{belongie2002shape}, Inner Distance Shape Context~\cite{ling2007shape} and Height Functions~\cite{wang2012shape} to match and classify shape objects. Felzenszwalb~\etal~\cite{felzenszwalb2009object} represent shapes' contours as a hierarchical structure of its fragments. This representation is used to classify the shape objects by a dynamic programming based matching algorithm. The Bag of Words (BoW) model was also applied to pool local features and generate a global descriptors for shape matching~\cite{ramesh2015shape, bai2014shape}. Several learning based approaches were proposed to tackle shape matching. Approaches such as~\cite{ramesh2015shape, wang2014bag, shen2016shape} pool shape features using the BoW model and classify them using a SVM. Rameshet~\etal~\cite{ramesh2015shape} uses the spectral magnitude of the log-polar transform as local feature and bi-grams from the spatial co-occurrence matrix as contextual features, while~\cite{wang2014bag} describes a shape as local shape context features of its fragments. Ramesh\etal~\cite{shen2016shape} combines contour and skeleton information into local features to describe a shape object. Li~\etal~\cite{li2016learning} uses a deep Bayesian network trained by Markov chain Monte Carlo (MCMC) based optimization to classify shape descriptors of height features introduces by~\cite{wang2012shape}.
{'timestamp': '2020-10-01T02:15:20', 'yymm': '2009', 'arxiv_id': '2009.09412', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09412'}
arxiv
\section{Introduction} \label{sec:intro} \input{sections/intro} \section{Related Work} \label{sec:related} \input{sections/related} \section{Method} \label{sec:method} \input{sections/method} \section{SHARP ECCV 2020 Challenge} \label{sec:challenge} \input{sections/challenge} \section{Discussion and Conclusions} \label{sec:conclusions} \input{sections/conclusions} \bibliographystyle{splncs04} \subsection{Texture Inference} \label{subsec:method.texture_inference} We learn to complete the texture of a given partial 3D surface, $\mathcal{T}_i$. For this, we learn a texture field, that is, a mapping of points $\mathbf{p}$, on a complete but untextured surface, to a color at that point. As input $\mathbf{x}$ to the texture field prediction, we additionally use a complete untextured surface geometry of the object. During training the complete surface geometry is provided by the ground truth surfaces, $\mathcal{S}_i$, during inference it is predicted as described in Sec \ref{subsec:method.geometry_reconstruction}. \paragraph{Encoding} We construct an input encoding \textit{aligned} with the input data. That is, using a 3D CNN we neurally process the input to feature grids, that lie in the same Euclidean space as the input. By recursively applying $n$ times, 3D convolutions followed by down scaling through max pooling, we create \emph{multi-scale deep feature grids} $\fgrid_1,..,\fgrid_n$. The feature grids at the early stages capture texture and shape details, whereas feature grids at the late stages have large receptive fields and capture global structure, for example to segment garments for giving them a coherent texture. See \cite{chibane20ifnet} for details.\\ To adapt the procedure for texture inference, we feed 4 channels of input data into the encoder, 3 channels for the textured partial observation - one channel per rgb - and the fourth channel encodes the complete surface geometry. For usage with a 3D CNN we need to voxelize the surfaces, we do this by densely sampling surface points and marking their nearest neighbor in an enclosing voxel grid. For the partial textured input, we mark the nearest neighbour voxels by the rgb intensities in $\{0,\dots,255\}$ and all other with $-1$. For the complete surface geometry, we mark voxels selected as nearest neighbours with 1 and all other with 0. We denote the encoder as $g(\mathbf{x}) \defeq \fgrid_1,..,\fgrid_n$, where our input is denoted as $\mathbf{x}$. \paragraph{Decoding} We create a point $\point$ specific encoding $\fgrid_1(\point),..,\fgrid_n(\point)$ by extracting deep features at the location $\point$ from the global encoding $g(\mathbf{x}) = \fgrid_1,..,\fgrid_n$. This is possible because $g(\mathbf{x})$ is kept aligned with Euclidean space. Since our feature grids are discrete, we use trilinear interpolation to query continuous 3D points $\point \in \mathbb{R}^3$. See \cite{chibane20ifnet} for details.\\ The point encoding $\fgrid_1(\point),..,\fgrid_n(\point)$, is then fed into a point-wise decoder $f(\cdot)$, parameterized by a fully connected neural network with ReLU activations, to regress the rgb color at $\point$. \paragraph{Training} At training time we use the textured partial surfaces, $\mathcal{T}_i$. and ground truth complete surface, $\mathcal{S}_i$, without texture, as inputs for the network. The task of the network is then, to learn to regress the correct color $\mathrm{rgb(\point,\mathcal{S}_i)}$ at a surface point $\point \in \mathcal{S}_i$ of the ground truth surface. We construct training data by sampling points $\point$ uniform at random on the surface $\mathcal{S}_i$ and find their ground truth $\mathrm{rgb(\point,\mathcal{S}_i)}$ values. More specifically, we have $\mathcal{S}_i$ available as mesh .obj-files with attached texture atlases. Therefore, to find $\mathrm{rgb(\point,\mathcal{S}_i)}$, we check for the triangle $\point$ is on, find the uv-coordinates of $\point$ by Barycentric interpolation of the uv-coordinates of the triangle vertices and extract the rgb value from the texture atlas at the found uv location. We use an L1 mini-batch loss: \begin{equation} \small \mathcal{L}_\mathcal{B}({\mathbf{w}}) \defeq \sum_{\mathbf{x} \in \mathcal{B}} \sum_{\point \in \mathcal{P}} ||f^{\mathbf{w}}(g_{\mathbf{w}}(\mathbf{x},\point)) - \mathrm{rgb}(\point,\mathcal{S}_{\mathbf{x}})||_1\\ \label{eq:loss} \end{equation} where $\mathcal{B}$ is a input mini-batch, $\mathcal{P}$ is a sub-sample of points, $\mathbf{w}$ are the neural parameters of encoder and decoder, and $g_{\mathbf{w}}(\mathbf{x},\point) \defeq \fgrid_1^\mathbf{w}(\point),\hdots, \fgrid_n^\mathbf{w}(\point)$. \paragraph{Inference} At inference time we feed the partial textured surface, $\mathcal{T}_i$, and its surface reconstruction (untextured) (Sec. \ref{subsec:method.geometry_reconstruction}) as input into the texture inference. The surface reconstruction is a mesh and for all its vertices we regress the rgb value and attach it to the mesh. This yields our final colored surface reconstruction. See Figure \ref{fig:method_overview} for an overview of our method. \subsection{Geometry Reconstruction} \label{subsec:method.geometry_reconstruction} During inference, we predict the geometry using an IF-Net and condition the texture generation (Sec. \ref{subsec:method.texture_inference}) on this geometry. For learning the geometry reconstruction, we use a standard IF-Net~\cite{chibane20ifnet}. Our training data consists of pairs $(\mathcal{T}_i,\mathcal{S}_i)_{i}$, of partial surfaces, $\mathcal{T}_i$, and complete ground truth surfaces, $\mathcal{S}_i$. The shape prediction given $\mathcal{T}_i$, of IF-Nets is done implicitly, by predicting for any point $\mathbf{p}$ in the continuous space $\mathbb{R}^3$, if $\mathbf{p}$ is inside (classification as $1$) or outside (classification as $0$) of the ground truth $\mathcal{S}_i$. For inference of surfaces, these predictions are evaluated on a dense gird in $\mathbb{R}^3$ and converted to a mesh using marching cubes~\cite{c_marching_cubes}. \paragraph{Encoding \& decoding} is done with the same architecture described above. However, the input to the encoder consists \textit{only} of one (untextured) channel, created from the partial surface. To encode the surface we again, sample points on it and create a voxel grid. We mark a voxel with 1, if it is a nearest neighbour of a point, and 0 else. We use a grid resolution of $256^3$. Instead of 3 values for rgb we decode into one value for the above mentioned occupancy classification. \paragraph{Training} For each ground truth surface, $S_i$, we sample 100.000 points and compute their occupancy. Samples are created in the surface vicinity to concentrate the model capacity on details. To this end, we first uniformly at random sample surface points $\point_\mathcal{S}$ and apply Gaussian distributed displacements $\mathbf{n} \sim \mathcal{N}(0, \boldsymbol{\Sigma})$, i.e. $\point \defeq \point_\mathcal{S} + \mathbf{n}$. We use a diagonal co-variance matrix $\boldsymbol{\Sigma} \in \mathbb{R}^{3\times{3}}$ with entries $\boldsymbol{\Sigma}_{i,i} = \sigma$. To capture detail we sample $50\%$ of the point samples very near the surface with a small $\sigma_1 = 0.015$, and to learn about the global, more homogeneously filled space, we sample $50\%$ with a larger $\sigma_2 = 0.2$. During training 50.000 points are sub-sampled and learning is unaltered from \cite{chibane20ifnet}. \subsection{Challenge 1} \subsubsection{Track 1} For track 1 we were kindly given access to the 3DBodyTex.v2 dataset, similar in quality to 3DBodyTex~\cite{3DBodyTex}\footnote{https://cvi2.uni.lu/datasets/}. It consists of about 2500 of human scans with high diversity in poses. Some humans wear minimal fitness clothing others are fully clothed in varying clothing. We train our algorithm solely on the officially provided training set. The task is to reconstruct a completed textured 3D surface from a 3D human scan with large missing areas. The ground truth surfaces, $\mathcal{S}_i$, are the raw scans. The textured partial surfaces, $\mathcal{T}_i$, are generated synthetically from the ground truth shapes, using the provided script with default values\footnote{https://gitlab.uni.lu/cvi2/eccv2020-sharp-workshop/-/tree/master}. For each ground truth mesh we generate 4 partial scans with different incompleteness patterns. The partial data should simulate an acquisition produced by a hand-held 3D scanner. For all scans we found the bounding box with $$(min_x, max_x, min_y, max_y,, min_z, max_z) = (-0.8, 0.8, -0.15, 2.1, -0.8, 0.8)$$ to be sufficient and use it to place our voxel grid encoding (see Sec. \ref{subsec:method.texture_inference}). In Fig. \ref{fig:result_track1} we show the results obtained with our method from Sec. \ref{sec:method}. \begin{figure}[t] \begin{overpic}[width=1\linewidth]{figures/track1.png} \put(0,18){\tiny a)} \put(35,18){\tiny b)} \put(68,18){\tiny c)} \put(0,1){\tiny d)} \put(35,1){\tiny e)} \put(68,1){\tiny f)} \end{overpic} \caption{Six testing results a)-f) from our method (unseen during training), left to right: textured, partial input, textured reconstruction, ground truth. Our geometry reconstructions notably show generated body parts in correct positions even for largely missing body parts, see right arm of person e). Our texture generation is visibly coherent with the reconstructed geometry, through the geometry conditioning, see transition from shirt to leggings of b). The texture generation learned can rely on symmetry for generation, see the right foot of person in c). } \label{fig:result_track1} \end{figure} \subsubsection{Track 2} In Track 2, the task is to reconstruct fine geometry details of the body such as ears, fingers, feet or a nose, without texture. For this we are given around 1000 detailed ground truth meshes, $\mathcal{S}_i$, obtained by fitting a human body model to human data in minimal clothing from 3DBodyTex.v2. See \cite{8803819,AutomaticFitting} for methods on automatic and robust model fitting proposed by the dataset authors. On these ground truth meshes a scanning process of the Shapify booth is simulated in software. Additionally, we again shoot holes into the mesh using the provided script in its default setting, shooting holes also at other body parts. Again, we generate 4 partial scans with different incompleteness patterns. Only when the evaluation data was released, we found, that holes only occur at ears, fingers, feet or noses. Therefore, an obvious enhancement for our training would be to concentrate model capacity to those regions by only shooting holes there. We reuse the bounding box found for Track 1. In Fig. \ref{fig:result_track2} we show qualiatative results obtained with our method, IF-Nets. \begin{figure}[t] \begin{overpic}[width=1\linewidth]{figures/track2.png} \put(0,14){\tiny a)} \put(33,14){\tiny b)} \put(63,14){\tiny c)} \end{overpic} \caption{Results on evaluation data (GT disclosed), for reconstruction of the ear region a), hand b) and feet c) regions. Although trained for geometry reconstruction of holes at arbitrary regions, plausible shape completion for these regions is achieved.} \label{fig:result_track2} \end{figure} \subsection{Challenge 2} In this challenge we are given a dataset (3DObjectTex.v1) of 2000, high quality, textured 3D ground truth scans, $\mathcal{S}_i$, of very diverse objects (real and stuffed animals, statues, technology, furniture,...). When scanning with a hand-held 3D scanner, technical infeasibility of reaching some parts of an object can lead to partial textured scans. Therefore, the task of this challenge is to reconstruct a textured, complete mesh from such partial data. In contrast to challenge 1, the diversity of objects makes it infeasible to build object specify shape priors. As before, we create 4 partial scans per ground truth. Due to huge size variations, we rescale all objects to lie in [-0.5,0.5] in each dimension, by subtracting each vertex with the object center and multiplying by the inverse of its longest bounding box edge. In Fig. \ref{fig:result_challenge2} we show qualitative results obtained with our IF-Nets. \begin{figure}[t] \includegraphics[width=1\linewidth]{figures/challenge2.png} \caption{Results on challenge evaluation data (GT disclosed), for reconstruction of textured, arbitrary objects. This is a highly challenging dataset and problem: objects come from no common class. Thus, no shape prior of objects can be learned - the textured reconstruction can solely rely on surface statistics common in any object. Our network performs reasonable textured reconstruction of what we believe to be a head, orange juice, a shoe and an Egyptian statue.} \label{fig:result_challenge2} \end{figure}
{'timestamp': '2020-09-22T02:18:08', 'yymm': '2009', 'arxiv_id': '2009.09458', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09458'}
arxiv
\section{Overview} \label{section:lf:overview} \subsection{Design criteria} \label{subsection:lf:design:criteria} A fundamental requirement of any formal foundation is that it should be \emph{appropriate} to the task at hand. The underlying language should allow us to describe the objects we want to describe and say what we want to say about them, and we should be convinced that formal expressions in the system adequately represent our intended meaning. Moreover, we need to have faith that the formal methods of reasoning are sound and yield correct results. This is a matter of theology as much as science: we rely on our intuition, training, and respect for the history and culture of mathematics to support the judgment that our informal mathematical methods of reasoning are trustworthy, and we rely further on our intuition, and the shorter but still venerable tradition of formal logic, to support the judgment that the formal system adequately captures these forms of reasoning. A formal foundation should also be \emph{simple}. The foundation is the abstract specification of the language and rules that are implemented by the system, and the more complicated the specification is, the harder it is to get the implementation right. The complexity also bears on the time it takes a proof assistant or verified checker to verify an individual proof. Most proof assistants have a small, trusted computing base, the kernel, which is used to certify correctness. Some proof assistants additionally support recording and exporting proofs so that they can be checked by independent reference checkers. A number of ambitious projects have tried to increase confidence that the implementation of a foundation meets its abstract specification; one approach is to bootstrap the verification process by verifying the correctness of the kernel itself relative to an independent specification of the system or its semantics, sometimes even down to the level of machine code \cite{DBLP:conf/mkm/Carneiro20,DBLP:journals/jar/DavisM15,DBLP:conf/cade/Harrison06,DBLP:conf/popl/KumarMNO14,DBLP:journals/pacmpl/SozeauBFTW20}. Finally, we also want the formal foundation to be \emph{expressive}. When we are working with a proof assistant, it is not enough to know that our theorems can be stated and proved in principle; we want it to be convenient to do so in practice, and that requires that interaction with the system be close to our natural forms of communication. We want it to be easy to define objects, state theorems, construct proofs, interpret error messages, find theorems in the library, and read and maintain code written by others. All these requirements bear on our choice. In addition to the gap between the kernel implementation of a formal foundation and its abstract specification, there is also a gap between the user interface and the kernel. Users state and prove claims in an idealized language, much like a programming language, which has to be translated to the representations that are checked by the kernel. A \emph{parser} converts user input to internal representations, typically invoking an \emph{elaborator} to disambiguate expressions and infer information that can conveniently be left implicit. There is a tension between the desire for simplicity and the desire for expressivity. Traditionally, foundational reduction has helped mediate between the two, allowing us to choose a simple foundation and then interpret a more expressive language and higher-level inferences on top of that. But then a proof assistant has to either transform the higher-level input to match the low-level specification, or trust a higher-level specification, which becomes the de facto foundation. So, although it is possible to narrow the gap between the user input and the standard of correctness by adopting a more elaborate foundation, there is an unavoidable tradeoff between expressivity and simplicity. The challenge, therefore, is to strike the right balance between the two. \subsection{The landscape} \label{subsection:lf:the:landscape} To muddy the waters even further, the appropriate design criteria for a proof assistant depend on what we want to do with it. If we are interested in formalizing mathematics, our choice should depend on the type of mathematics we want to formalize, and if we are interested in verifying hardware or software, it should depend on the kinds of systems and properties we want to reason about. Some preferences even come down to a matter of taste, and arguments over the merits of different provers incite flame wars similar to those about the merits of different programming languages. This explains why there are so many different foundations on offer. The best we can do here is to map out the design landscape and to clarify some of the advantages and disadvantages of the various choices. One paramount consideration is whether the foundation we choose is typed or untyped, and, if it is typed, how elaborate the type system is. In set theory, every object is a set, much the way that in (an idealized version of) the Lisp programming language, every object can be viewed as a list. In other words, in set theory, there is fundamentally only one type of object. In a typed foundation, as in a typed programming language, every expression has a type, and the type constrains what one can do with the expression. Having types makes it easier for a system to catch and flag errors, such as sending the wrong number of arguments to a function. It can also make user input more convenient, since information can be inferred from an expression's type. For example, in an expression $x + y$, if $x$ and $y$ are known to be integers, the system can infer the $+$ denotes integer addition. These benefits come at a price: expressions then \emph{have} to conform to the type discipline, constraining the user in ways that are sometimes unnatural. Another consideration is whether the logical framework is classical or constructive. Constructive frameworks are designed to support a computational reading of definitions and theorems, whereby a proof of an existence statement comes either implicitly or explicitly with a construction of the object asserted to exist. Modern mathematics is thoroughly classical in that it allows us to define noncomputable functions and establish the existence of other noncomputable objects. But constructive foundations are often appealing to researchers in computer science, who prefer to think in computational terms. Perhaps more to the point is the question as to how well the logical framework supports reasoning about computation. Constructive foundations often specify a notion of evaluation for terms in the language, which allows us to view terms as computer programs and reason about their behavior. But classical systems can also support extraction of code from sufficiently computable definitions, and there are various ways that provability in the system can be taken to establish properties of the extracted code. This enables one to reason about computational systems within a classical mathematical framework. In this chapter, we will consider three families of foundations: \begin{itemize} \item set theory; \item simple type theory; \item dependent type theory. \end{itemize} Set theory was designed to provide a powerful and flexible foundation for mathematics, with axioms that are fairly simple and easy to understand. Set-theoretic foundations, implemented by systems like Mizar \cite{DBLP:journals/jfrea/GrabowskiKN10}, Isabelle/ZF \cite{MR2051585}, and Metamath \cite{DBLP:conf/tphol/Megill06}, are typically based on classical first-order logic. The second family, simple type theory, descends from a tradition that began with Gottlob Frege, was further developed in the \emph{Principia Mathematica} of Alfred Whitehead and Bertrand Russell, and reached maturity in presentations by Alonzo Church. In the early 1980s, Michael J.~C.~Gordon, interested in hardware verification, inaugurated its use in proof assistants. It is typically implemented as a classical system and forms the basis for HOL4 \cite{DBLP:conf/tphol/SlindN08}, Isabelle/HOL \cite{DBLP:books/sp/NipkowPW02}, ProofPower \cite{DBLP:conf/tphol/Arthan01}, and HOL Light \cite{DBLP:conf/tphol/Harrison09a}. The third family, dependent type theory, extends simple type theory with more elaborate means of defining types and expressions of those types. Such a type theory was the basis of N.~G. de~Bruijn's seminal \emph{Automath} proof assistant from the late 1960s. Most systems in use today descend more directly from systems of constructive mathematics introduced by Per Martin-L\"of, Jean-Yves Girard, and others in the 1970s. As we will see, the fact that they are based on functions and types as primitives brings them closer to the realm of programming languages, but there are also classical variations. Contemporary systems based on dependent types include Coq \cite{DBLP:series/txtcs/BertotC04}, PVS \cite{DBLP:conf/tphol/OwreS08}, Agda \cite{DBLP:conf/tphol/BoveDN09}, Nuprl \cite{DBLP:books/daglib/0068834}, Matita \cite{DBLP:conf/cade/AspertiRCT11}, and Lean \cite{DBLP:conf/cade/MouraKADR15}. \subsection{A brief history of logic and foundations} \label{subsection:lf:a:brief:history} In the \emph{Prior Analytics}, Aristotle presented his theory of syllogisms, which are schematic rules of inference from two premises to a conclusion. The theory is based on the insight that some patterns of inference are \emph{valid}, meaning that every instance with true premises has a true conclusion. In other words, the validity of an inference does not depend on its contents, but, rather, its logical form. In this account, Aristotle provided a systematic characterization of the valid syllogistic forms. Aristotle's logic was further developed in the scholastic philosophical tradition of the monastic schools and universities in the middle ages. In 1666, Leibniz proposed the development of a \emph{characteristica universalis}, a symbolic language for expressing propositions, and a \emph{calculus ratiocinator}, a calculus of reasoning. Most of his efforts in that regard, however, were not published or appreciated until the nineteenth century. A work by Antoine Arnauld and Pierre Nicole first published in 1662, \emph{La Logique ou l'Art de penser}, was more influential. Commonly known as the \emph{Port-Royal Logic} for the abbey near Paris where it was written, it incorporated but also critiqued the Aristotelian tradition, and combined it with the philosophical rationalism of Descartes. It also aimed to clarify the relationship between words, ideas, and objects and the nature of predication. Logic became a part of mathematics in the nineteenth century with the work of George Boole and Augustus De Morgan, who viewed calculation with propositions as an instance of algebraic reasoning. Charles Peirce, Ernst Schr\"oder, and others extended the algebraic framework to include quantifiers. In his two-volume \emph{Grundgesetze der Mathematik} of 1893/1903, Gottlob Frege presented an axiomatic foundation for mathematics with functions, relations, quantifiers, and higher types. (In 1902, Russell showed that Frege's system is inconsistent, but eliminating the offending axiom results in essentially a version of higher-order logic.) Around the turn of the twentieth century, Giuseppe Peano also developed formal accounts of mathematical reasoning. The nineteenth century also brought developments in the \emph{informal} foundations of mathematics. Augustin-Louis Cauchy, Georg Cantor, and Richard Dedekind all provided definitions of the real numbers in terms of sets or sequences of rationals, and Frege and Dedekind gave essentially set-theoretic constructions of the natural numbers. Axiomatic foundations came of age in the twentieth century. Ernst Zermelo proposed the fundamental axioms of set theory in 1908, and in 1921 Abraham Fraenkel couched them in the framework of first-order logic and added the axiom of replacement. Russell and Whitehead presented a system of \emph{ramified type theory} in their landmark three-volume work, \emph{Principia Mathematica}, of 1910--1913. In 1940, Church introduced \emph{simple type theory}, incorporating ideas by Frank Ramsey and Leon Chwistek. The modern theories of constructive dependent type theory that are due to Per Martin-L\"of on the one hand and Thierry Coquand and G\'erard Huet on the other, discussed in Section~\ref{section:lf:dependently:typed:foundations}, owe a lot to the intuitionistic principles put forth by L.~E.~J.~Brouwer in the 1910s and formalized by Arend Heyting in the 1930s. They also draw on the \emph{Curry--Howard correspondence}, a relationship between logic and computation elucidated by Haskell Curry, William Howard, William Tait, and N.~G. de~Bruijn. \section{First-Order Logic} Philosophers often distinguish between a \emph{logical foundation} and a \emph{mathematical foundation}. The first is supposed to provide the general rules of reasoning in any domain, whereas the second is supposed to provide the rules for reasoning about mathematical objects in particular. First-order logic is an important foundation for logical reasoning in the first sense, since it is designed to model fundamental patterns of reasoning involving terms like ``and,'' ``or,'' ``not,'' ``every,'' and ``some.'' It can be interpreted as establishing patterns of inference that are valid in any domain that has at least one element. \subsection{Syntax} \label{subsection:lf:first:order:logic:syntax} A first-order \emph{language} is a collection function symbols and relation symbols, each with an associated \emph{arity}, that is, a specification of the number of arguments. A $0$-ary function symbol is simply a constant symbol, whereas one can think of a $0$-ary relation symbol as standing for a fixed proposition. The syntax is then specified in two stages. Given a stock of variables $x, y, z, \dotsc$, the set of \emph{terms} is defined inductively, as follows: \begin{itemize} \item Each variable $x$ and constant symbol $c$ is a term. \item If $f$ is an $n$-ary function symbol with $n \ge 1$ and $t_0, \ldots, t_{n-1}$ are terms, then $f(t_0, \ldots, t_{n-1})$ is a term. \end{itemize} The set of formulas is defined inductively, as follows: \begin{itemize} \item If $s$ and $t$ are terms, then $s = t$ is a formula. \item If $R$ is an $n$-ary relation symbol and $t_0, \ldots, t_{n-1}$ are terms, then $R(t_0, \ldots, t_{n-1})$ is a formula. \item $\bot$ is a formula, and if $A$ and $B$ are formulas, so are $A \And B$, $A \Or B$, and $A \Implies B$. \item If $A$ is a formula and $x$ is a variable, then $\Forall x A$ and $\Exists x A$ are formulas. \end{itemize} Defining $\neg A$ to be $A \Implies \bot$, the set of propositional connectives chosen here is suitable for both classical and intuitionistic logic. For classical logic, smaller sets of connectives will do, and for both classical and intuitionistic logic, we can define $A \Iff B$ to be $(A \Implies B) \And (B \Implies A)$. The universal and existential quantifiers in the last clause are said to \emph{bind} the variable $x$. For example, $\Forall x {R(x, y)}$ says that everything is related to $y$, which is a statement about $y$ but not $x$. Intuitively, this formula says the same thing as $\Forall z {R(z, y)}$. Formulas that are the same up to a renaming of their bound variables are said to be \emph{$\alpha$-equivalent}, and many implementations use internal representations that identify $\alpha$-equivalent formulas (for example, using \emph{De Bruijn indices} \cite{DBLP:books/daglib/0067558}). Variables that are not bound are said to be \emph{free}, and a formula with no free variables is called a \emph{sentence}. If $A$ is a first-order formula, $t$ is a term, and $x$ is a variable, then $A[t/x]$ denotes the result of substituting $t$ for $x$ in $A$. One has to be careful to rename bound variables when carrying out a substitution. For example, when interpreted as a statement about the natural numbers, $\Forall x {\Exists y} y > x$ says that for every number $x$, there is something larger than it. One should be able to replace $x$ by any expression, but naively replacing $x$ by $y + 1$ results in the statement $\Exists y {y > y + 1}$, which is patently false. \subsection{Deductive systems} \label{subsection:lf:first:order:logic:deductive:systems} The following axiomatic deductive system was used by David Hilbert and his students in the 1920s: \begin{enumerate} \item $A \Implies (B \Implies A)$. \item $(A \Implies (B \Implies C)) \Implies ((A \Implies B) \Implies (A \Implies C))$. \item $A \Implies (B \Implies A \And B)$. \item $A \And B \Implies A$. \item $A \And B \Implies B$. \item $A \Implies A \Or B$. \item $B \Implies A \Or B$. \item $(A \Implies C) \Implies ((B \Implies C) \Implies (A \Or B \Implies C))$. \item $\bot \Implies A$. \item $(\Forall x A) \Implies A[t/x]$. \item $A[t/x] \Implies \Exists x A$. \item $\Forall x {x = x}$. \item $\Forall {x, y} {x = y \Implies t[x/z] = t[y/z]}$. \item $\Forall {x, y} {x = y \Implies (A[x/z] \Implies A[y/z])}$. \end{enumerate} For classical logic, replace 9 with $\neg \neg A \Implies A$. The rules of inference are as follows: \begin{enumerate} \item From $A \Implies B$ and $A$ conclude $B$. \item From $A \Implies B$ conclude $A \Implies \Forall x B$, provided $x$ is not free in $A$. \item From $A \Implies B$ conclude $(\Exists x A) \Implies B$, provided $x$ is not free in $B$. \end{enumerate} The first is known as \emph{modus ponens}. If $\Gamma$ is a set of sentences of first-order logic, then $\Gamma \vdash A$, read ``$\Gamma$ proves $A$,'' expresses the statement that there is a formal proof of $A$ from hypotheses in $\Gamma$. The system of axioms above satisfies the \emph{deduction theorem}, namely, that if $\Gamma \cup \{ A \} \vdash B$ then $\Gamma \vdash A \Implies B$. Many proof assistants implement systems of logical reasoning that are based on Gerhard Gentzen's systems of \emph{natural deduction}, which he first presented in the 1930s. In one formulation, formal derivations are taken to establish not formulas but \emph{sequents} of the form $\Gamma \vdash A$, where $\Gamma$ is a finite set of formulas. As the notation suggests, the sequent $\Gamma \vdash A$ is supposed to indicate that $A$ follows from $\Gamma$. In this context, it is convenient to write $\Gamma{,}\; A$ for $\Gamma \cup \{ A \}$ and to write $\Gamma{,}\; \Delta$ for $\Gamma \cup \Delta$. A novel feature of the natural deduction framework is that hypotheses can be introduced temporarily in a derivation. For example, the rule for showing that an implication $A \Implies B$ follows from $\Gamma$ is as follows: if $\Gamma{,}\; A \vdash B$ then $\Gamma \vdash A \to B$. In other words, the deduction theorem is incorporated as a basic rule of the calculus. The full set of rules is given in Figure~\ref{fig:natural:deduction}. \setlength{\tabcolsep}{12pt} \begin{figure} \begin{center} \begin{tabular}{cc} \multicolumn{2}{c}{ \AXM{\strut} \UIN{\strut\Gamma{,}\; A \fCenter A} \DP } \\ \\ \AXN{\strut\Gamma \fCenter A} \AXN{\strut\Delta \fCenter B} \BIN{\strut\Gamma{,}\; \Delta \fCenter A \And B} \DP & \AXN{\strut\Gamma \fCenter A \And B} \UIN{\strut\Gamma \fCenter A} \DP \quad \AXN{\strut\Gamma \fCenter A \And B} \UIN{\strut\Gamma \fCenter B} \DP \\ \\ \AXN{\strut\Gamma \fCenter A} \UIN{\strut\Gamma \fCenter A \Or B} \DP \quad \AXN{\strut\Gamma \fCenter B} \UIN{\strut\Gamma \fCenter A \Or B} \DP & \AXN{\strut\Gamma \fCenter A \Or B} \AXN{\strut\Delta, A \fCenter C} \AXN{\strut\Pi, B \fCenter C} \TIN{\strut\Gamma{,}\; \Delta{,}\; \Pi \fCenter C} \DP \\ \\ \AXN{\strut\Gamma{,}\; A \fCenter B} \UIN{\strut\Gamma \fCenter A \Implies B} \DP & \AXN{\strut\Gamma \fCenter A \Implies B} \AXN{\strut\Delta \fCenter A} \BIN{\strut\Gamma{,}\; \Delta \fCenter B} \DP \\ \\ \multicolumn{2}{c}{ \AXN{\strut\Gamma \fCenter \bot} \UIN{\strut\Gamma \fCenter A} \DP } \\ \\ \AXN{\strut\Gamma \fCenter A} \UIN{\strut\Gamma \fCenter \Forall x A} \DP & \AXN{\strut\Gamma \fCenter \Forall x A} \UIN{\strut\Gamma \fCenter A[t/x]} \DP \\ \\ \AXN{\strut\Gamma \fCenter A[t/x]} \UIN{\strut\Gamma \fCenter \Exists x A} \DP & \AXN{\strut\Gamma \fCenter \Exists x A} \AXN{\strut\Delta, A \fCenter B} \BIN{\strut\Gamma{,}\; \Delta \fCenter B} \DP \\ \\ \multicolumn{2}{c}{ \AXM{\strut} \UIN{\strut\Gamma \fCenter t = t} \DP } \\ \\ \AXN{\strut\Gamma \fCenter r = s} \UIN{\strut\Gamma \fCenter t[r/x] = t[s/x]} \DP & \AXN{\strut\Gamma \fCenter r = s} \AXN{\strut\Delta \fCenter A[r/x]} \BIN{\strut\Gamma{,}\; \Delta \fCenter A[s/x]} \DP \end{tabular} \end{center} \caption{Natural Deduction} \label{fig:natural:deduction} \end{figure} For classical logic, the rule {\em ex falso sequitur quodlibet} (from $\bot$ conclude anything) should be strengthened to {\em reductio ad absurdum}: \begin{prooftree} \AXN{\strut\Gamma{,}\; \lnot A \fCenter \bot} \UIN{\strut\Gamma \fCenter A} \end{prooftree} Natural deduction satisfies the \emph{weakening} property, which is to say, if $\Gamma \fCenter A$ and $\Delta \supseteq \Gamma$ then $\Delta \fCenter A$. As a result, it is possible to present the rules in such a way that sets of hypotheses are preserved when reading a proof upwards. In this style, the introduction rule for conjunction would be written as follows:\strut \begin{center} \AXN{\strut\Gamma \fCenter A} \AXN{\strut\Gamma \fCenter B} \BIN{\strut\Gamma \fCenter A \And B} \DP \end{center} This manner of description is better suited to proof search: it says that if you are looking for a proof of $A \And B$ from $\Gamma$, it suffices to find a proof of $A$ and $B$ from $\Gamma$. We will also use this style of presentation to describe typing judgments in Section~\ref{section:lf:dependently:typed:foundations}. A set of sentences closed under provable consequences is called a \emph{theory}. So, if $T$ is a theory, $T \vdash A$ is equivalent to $A \in T$. If $\Gamma$ is set of sentences, the set $\{ A \mid \Gamma \vdash A \}$ is a theory, called the \emph{theory axiomatized by $\Gamma$}. It is often useful to use the vector notation $\vec x$ to denote a tuple of variables and similarly for a tuple of terms $\vec t$, and we will use this notation below. \subsection{Sorts} \label{subsection:lf:sorts} In first-order logic, quantifiers range over a single, monolithic universe of objects. But we can \emph{relativize} a quantifier to a predicate, $A(x)$, as follows: $\Forall x {A(x) \Implies B(x)}$ says that every $A$ is a $B$, and $\Exists x {A(x) \And B(x)}$ says that some $A$ is a $B$. In a language with an order relation, the notation $\Forall {x < y} B(x)$ and $\Exists {x < y} B(x)$ are commonly used to abbreviate $\Forall x x < y \Implies B(x)$ and $\Exists x x < y \And B(x)$, respectively. Similarly, $\Forall {x \in y} A(x)$, $\Forall {x \subseteq y} A(x)$, $\Exists {x \in y} A(x)$, and $\Exists {x \subseteq y} A(x)$ are commonly used with the language of set theory. In a slight variant of first-order logic known as \emph{many-sorted logic}, one has quantifiers and variables ranging over different domains of objects, and the function symbols and relation symbols come with a specification of the sorts of objects they expect. For example, a language designed to reason about geometry may have variables $p, q, r, \ldots$ ranging over points, variables $L, M, N, \ldots$ ranging over lines, and a relation $\fn{on}(p, L)$ that expresses that point $p$ is on line $L$. The sentence $\Forall {p, q} \Exists L {\fn{on}(p, L) \And \fn{on}(q, L)}$ expresses that there is a line through any two points, and \[ \Forall {p, q, L, M} {p \ne q \And \fn{on}(p, L) \And \fn{on}(q, L) \And \fn{on}(p, M) \And \fn{on}(q, M) \Implies L = M} \] expresses that there is at most one line between two distinct points. Many-sorted logic can easily be interpreted in first-order logic without sorts by introducing predicate symbols for the sorts and relativizing quantifiers. But keeping track of an object's sort is such a fundamentally important task that many implementations prefer to build it into the logical framework. \subsection{Definitional extensions} \label{subsection:lf:definitional:extensions} Fundamental to any proof assistant is the ability to extend a language with \emph{definitions}. Given any formula $A(\vec x)$, one can introduce a new relation symbol $R(\vec x)$ and the axiom $\Forall {\vec x} {R(\vec x) \Iff A(\vec x)}$. This is a \emph{conservative extension} in the sense that the new symbol~$R$ can be translated away, namely, by replacing it everywhere by $A$. The formula $\Exists y {B(y) \And \Forall z {B(z) \Implies z = y}}$, which asserts that there is a unique~$y$ satisfying $B(y)$, is often abbreviated $\ExistsUnique y {B(y)}$. If a first-order theory proves $\Forall {\vec x} {\ExistsUnique y {A(\vec x, y)}}$, we can introduce a new function symbol $f(\vec x)$ to denote \emph{the} $y$ such that $A(\vec x, y)$ holds, together with the axiom $\Forall {\vec x} {A(\vec x, f(\vec x))}$. The formula $A(\vec x, y)$ provides what is known as a \emph{definite description} of the function $f$. The result is once again a conservative extension, and there is a tedious though straightforward way to eliminate the use of $f$ in favor of its definite description. Extending a first-order theory with relations and functions defined in this way results in a \emph{definitional extension} of the original theory. If one drops the uniqueness requirement in the definition of a definite description and requires only that the theory proves $\Forall {\vec x} {\Exists y {A(\vec x, y)}}$, the formula $A$ is known as an \emph{indefinite description}. It is an important fact that with classical logic, adding a function symbol $f(\vec x)$ satisfying $\Forall {\vec x} {A(\vec x, f(\vec x))}$ still results in a conservative extension. The same is true with intuitionistic logic if we add the axiom of \emph{decidable equality}, namely, $\Forall {x, y} {x = y \Or x \ne y}$. In classical logic, one can use an indefinite description to specify a function $f(\vec x)$ that returns a value $y$ satisfying $B(\vec x, y)$ if such a value exists. Such a function is known as a \emph{Skolem function}. In the presence of such a function, the formula $\Exists y {B(\vec x, y)}$ is equivalent to $B(\vec x, f(\vec x))$, so a Skolem function can be used to replace an existential quantifier. For that reason, Skolem functions are commonly used in automated reasoning. \subsection{Partial functions and undefined terms} \label{subsection:lf:partial:functions:and:undefined:terms} In first-order logic, every function is assumed to return a value. But we often want to reason about partial functions: division by zero on the real numbers is undefined, a partial computable function may not return a value, the limit of a sequence may not exist, and a derivative may not exist at a point. In all three of the families of formal foundations we discuss below, as in first-order logic, every term is assumed to denote an object. Various options are then available for modeling a partial function: \begin{enumerate} \item Replace the partial function by a total version by specifying values where they would otherwise be undefined. For example, in many calculations, it is convenient to define $x / 0$ to be $0$ for every real number $x$. This device does not change the meaning of any statement that does not mention the division symbol; it merely introduces an alternative to division with similar properties. \item Replace the partial function by a total version but leave the new values unspecified. For example, foundational frameworks often provide the means to specify an arbitrary real value $a$ without making any additional assumptions about it. One can then define $x / 0$ to be $a$. \item Replace the partial function by a total function that returns a special value, $\bot$, interpreted as the value \emph{undefined}. With this approach, division on the reals is represented as a function from $\mathbb{R} \times \mathbb{R}$ to $\mathbb{R} \cup \{ \bot \}$. \item Replace the partial function by a total function on a smaller domain. With this approach, division on the reals is represented on a function from $\mathbb{R} \times \{ x \in \mathbb{R} \mid x \ne 0 \}$ to $\mathbb{R}$. \end{enumerate} The last two approaches presuppose that the logical framework has mechanisms for reasoning about functions with various domains and codomains. For example, to adopt the third approach in type theory, for any data type $\alpha$, a new data type $\ty{Option} \, \alpha$ can be used to represent the extension of $\alpha$ by a new element to represent the value \emph{undefined}. But then in order to interpret an expression like $x / y + z$, the \emph{domains} of the operations of arithmetic also have to be extended to include undefined terms. We will see that dependent type theory provides helpful means of implementing the fourth approach, so that the expression $x / y$ comes with an explicit syntactic guarantee that $y$ is not $0$. Implementing the third and fourth approaches in a logic of total objects is, in any case, challenging. One may reasonably maintain that definedness is so fundamental to mathematical and logical reasoning that it should be built into the logic rather than layered on top of it. Variations on first-order logic based on partial terms have been thoroughly studied in the literature \cite{MR786465,MR1396840,MR966421:modified}, and the IMPS proof assistant was based on a version of simple type theory with partial functions \cite{DBLP:journals/jar/FarmerGT93}. \subsection{Semantics} \label{subsection:lf:first:order:logic:semantics} It is common to distinguish between a logical system's \emph{syntax} and its \emph{semantics}. A semantics for a logical system is an account of the meaning of its expressions and an indication as to what the formal rules of inference are supposed to accomplish. If we think of the syntax of a formal system as a specification of what it means for an implementation in a proof assistant to be correct, the semantics, in a sense, specifies what it means for the syntax to be correct. In the classical, model-theoretic approach, terms in a system are supposed to denote objects in an intended interpretation and formulas are supposed to say things about an intended interpretation. The deductive apparatus is then supposed to establish the valid entailments, so that $\Gamma \vdash A$ implies that $A$ is true in any interpretation that satisfies the assumptions in $\Gamma$. More precisely, a \emph{model} or \emph{structure} $\mdl M$ for a first-order language $L$ consists of a set of objects, $| \mdl M |$, called the \emph{universe} of the model, an interpretation of each $n$-ary function symbol of $L$ as an $n$-ary function on the universe of $\mdl M$, and an interpretation of each $n$-ary relation symbol as an $n$-ary relation on the universe of $\mdl M$. Given a term $t$ and an assignment $\sigma$ of values in the universe of $\mdl M$ to its free variables, we can recursively define the interpretation of $t$ in $\mdl M$, which we denote $\tval{t}^{\mdl M, \sigma}$. Similarly, given a formula $A$ and an assignment $\sigma$, we can specify what it means for $A$ to be \emph{true} in $\mdl M$ under that assignment, written $\mdl M \models_\sigma A$. If $\Gamma$ is a set of sentences, we say $\mdl M$ \emph{is a model of} $\Gamma$ if every sentence in $\Gamma$ is true in $\mdl M$. We say \emph{$\Gamma$ logically entails $A$} and write $\Gamma \models A$ if every model of $\Gamma$ is a model of $A$. For first-order logic, we have the important fact that the syntactic and semantic notions of entailment coincide: $\Gamma \vdash A$ if and only if $\Gamma \models A$. The forward direction, which says that the deductive rules of first-order logic make sense with respect to model-theoretic semantics, is known as \emph{soundness}. The reverse direction, which says that every logical entailment is formally derivable, is known as \emph{completeness}. It was first established by Kurt G\"odel. According to the semantic definitions, $\mdl M \models A \Or \neg A$ for any model $\mdl M$ and sentence $A$. Developing a model-theoretic semantics for intuitionistic logic therefore requires more work, but it can be done. For example, a \emph{Kripke model} $\mdl K$ is a family of structures indexed by a partial order $P$, called \emph{worlds}, or \emph{nodes}. These can be thought of as representing partial states of information, and the definition specifies that if a node $\alpha$ is greater than a node $\beta$ in the partial order, then the universe of the structure at $\alpha$ includes the universe of the structure at $\beta$, and any atomic formula true at $\beta$ is also true at $\alpha$. The classical semantic relation $\mdl M \models_\sigma A$ is replaced by a relation $\mdl K, \alpha \Vdash_\sigma A$, which says that $A$ is true at node $\alpha$ in $\mdl K$ under assignment $\sigma$. Soundness and completeness for intuitionistic first-order logic now takes the following form: $\Gamma$ proves $A$ if and only if $A$ is true at any node of any Kripke model at which every sentence in $\Gamma$ is true. Soundness and completeness also hold with respect to a generalization of Kripke semantics known as \emph{Beth semantics}. \emph{Algebraic semantics} generalizes model-theoretic semantics by assigning truth values in other algebraic structures. In classical first-order logic, formulas can be evaluated in any \emph{complete boolean algebra}, and in intuitionistic first-order logic, formulas can be evaluated in any \emph{complete Heyting algebra}. For intuitionistic logic especially, \emph{categorical logic} provides natural semantics as well. For example, intuitionistic first-order logic is sound and complete with respect to evaluation in any \emph{locally cartesian closed category} with finite coproducts, where sentences are interpreted as objects and a provable entailment $A \vdash B$ gives rise to an arrow between the corresponding objects. There are also computational approaches to the semantics of intuitionistic logic, and even classical logic. Such approaches are better at capturing the intuitive meaning of the intuitionistic connectives, and will be discussed in Section~\ref{subsection:lf:simply:typed:lambda:calculus:semantics}. \subsection{Decidability and incompleteness} \label{subsection:lf:decidability:and:incompleteness} We will see in Section~\ref{section:lf:simply:typed:lambda:calculus} that logic provides a means to reason about computation, and that formal derivations can have computational content. Conversely, from a metatheoretic standpoint, we can carry out computations involving terms, formulas, and derivations. A first-order theory $T$ is \emph{decidable} if there is an algorithm that, on input $A$, determines whether or not $T$ proves $A$. As it turns out, some of the theories that come up in logic are decidable and some are not, and it is often an interesting challenge to determine which is the case. We should not expect a reasonably expressive theory to be decidable. For example, imagine we have a formal language in which we can express the statement ``Turing machine $M$ halts when started on empty input.'' Suppose moreover that we have a theory, $T$, with the property that if $M$ halts on empty input then $T$ is strong enough to prove that fact, and, conversely, if $T$ proves that $M$ halts on empty input, then it does. Then deciding whether or not $M$ halts on empty input is tantamount to deciding whether or not $T$ proves that fact, so the halting problem is reducible to $T$. If the theory $T$ just described has a computable set of axioms, then the halting problem is in fact equivalent to $T$: given a formula $A$, we can describe an algorithm that searches for a proof of $A$ from the axioms of $T$, and the question as to whether $A$ is in $T$ reduces to the question as to whether that Turing machine halts. A theory $T$ is said to be \emph{consistent} if $T$ does not prove $\bot$, and \emph{complete} if, for every sentence $A$, either $T$ proves $A$ or $T$ proves $\neg A$. In other words, a theory is complete if it is strong enough to settle the truth of every sentence in its language. A complete, computably axiomatized first-order theory $T$ is necessarily decidable: if $T$ is inconsistent, then it proves everything and the decision procedure is trivial, and if $T$ is consistent, there is an algorithm that decides whether or not $T$ proves $A$ by systematically searching for a proof of $A$ or $\neg A$ from the axioms of $T$. Combining this observation with the one in the previous paragraph shows that no reasonably expressive theory of mathematics is complete. G\"odel's \emph{first incompleteness theorem} strengthens this result and makes it precise. The following formulation relies on a finite set of axioms defined by Raphael Robinson, denoted $Q$, that embodies very modest assumptions about basic arithmetic on the natural numbers \cite{MR1640326}. The theorem applies to any theory in the language of arithmetic that includes $Q$. It applies more generally to any theory $T$ that \emph{interprets} $Q$ in the sense that it is possible to translate the language of arithmetic into the language of $T$ in such a way that the axioms of $Q$ are provable. \begin{theorem} There is no complete, consistent, computably axiomatized theory that interprets $Q$. \end{theorem} \noindent G\"odel's original proof (of a slightly weaker statement) involves constructing a sentence in any such theory that says ``I am not provable,'' but one can also arrive at the result via computability considerations similar to the ones above. The \emph{second incompleteness theorem}, which we will not state precisely here, says, roughly, that no reasonable theory of mathematics can prove its own consistency. The undecidability result sketched above can also be strengthened. A theory $T$ in the language of arithmetic is undecidable if it is \emph{consistent} with $Q$, that is, $T \cup Q$ is consistent. More generally, a theory is undecidable if it is consistent with a translation of the axioms of $Q$ to its language. Since $Q$ can be interpreted in set theory and pure first-order logic is consistent with that interpretation, provability in first-order logic in a language with a single binary relation symbol is undecidable. The intuition behind this result is that the binary relation \emph{could be} the element-of relation in set theory, which means that a provability query can encode a question about natural numbers representing Turing machine computations. This is worse than guilt by association; it is guilt by virtue of having the mere capacity to commit a crime. Imagine a police officer pulling theory $T$ over and saying ``Hey, you! You look like a theory of arithmetic!'' Theory $T$ says ``What? Me? A theory of arithmetic? I don't know anything about arithmetic!'' The police officer takes a good look at $T$ and says, ``Well, you look like you \emph{could} be a theory of arithmetic. Get outta here! You're undecidable!'' The fact that interesting mathematical theories are undecidable, however, provides job security for people working in automated and interactive theorem proving. It tells us, in a sense, that proof search and user input are unavoidable. A number of important first-order theories are decidable. If $\mdl M$ is a model, the \emph{theory of $\mdl M$} is the set of sentences $\{ A \mid \mdl M \models A \}$. The following are all decidable: \begin{enumerate} \item The theory of the natural numbers, $\mathbb{N}$, or the integers, $\mathbb{Z}$, in a language with $0$, $1$, $+$, and $\le$, but without multiplication. These are known as \emph{Presburger arithmetic} or \emph{integer linear arithmetic}. \item The theory of the real numbers, $\mathbb{R}$, in the same language. This is known as \emph{linear arithmetic}. It can be axiomatized as the theory of a densely ordered abelian group (additively written) with $0 < 1$, and so the theory does not change if $\mathbb{R}$ is replaced by any densely ordered subgroup, like $\mathbb{Q}$. \item The theory of the real numbers, $\mathbb{R}$, in the same language together with multiplication. This is known as the theory of \emph{real closed fields}. \item The theory of the complex numbers as a field. This is known as the theory of \emph{algebraically closed fields}. \end{enumerate} In addition, some useful fragments of first-order logic are decidable. For example, a sentence of first-order logic is said to be \emph{universal} if it can be written $\Forall {\vec x} A$, where $A$ is quantifier-free. An algorithm known as \emph{congruence closure} can be used to decide the universal fragment of first-order logic with equality. Results like these form the basis for \emph{decision procedures}, and are useful in the context of interactive theorem proving because users can rely on them to prove statements within their scope automatically. In that context, we generally want a procedure that not only decides the truth of a sentence but also provides an explicit proof of the sentence when the answer is positive. \subsection{Arithmetic} \label{subsection:lf:arithmetic} Theories of the natural numbers have held an important place in the logical tradition, not only because the natural numbers are so fundamental, but also because they can be used to \emph{code} or \emph{represent} other finite objects. As a result, a theory of the natural numbers can be seen as providing a foundation for finitary mathematics. The set of \emph{primitive recursive functions} is the set of functions from $\mathbb{N}$ to $\mathbb{N}$, of various arities, defined inductively as follows: \begin{itemize} \item The constant $0$ (as a $0$-ary function) and the function $\fn{succ}(x) = x + 1$ are primitive recursive. \item If $t(\vec x)$ is any term involving primitive recursive functions that have previously been defined, the function $f$ defined by $f(\vec x) = t(\vec x)$ is primitive recursive. \item If $g(\vec y)$ and $h(x, z, \vec y)$ are primitive recursive, so is the function $f(x, \vec y)$ recursively defined by the following equations: \begin{align*} f(0, \vec y) & = g(\vec y) \\ f(x+1, \vec y) & = h(x, f(x, \vec y), \vec y) \end{align*} \end{itemize} In words, the set of primitive recursive functions is the smallest set containing zero and successor and closed under \emph{explicit definition} and \emph{primitive recursion}. As an example of an explicit definition, if $g(x, y, z)$ and $h(x)$ have previously been defined, we can introduce a new primitive recursive function $f(x, y)$ with defining equation $f(x, y) = g(x, h(x), h(y))$. This clause can be replaced by a more rigid schema for composing functions if we include projections $p^n_i(x_0, \ldots, x_{n-1}) = x_i$ among the basic functions. \emph{Primitive recursive arithmetic}, or $\na{PRA}$, is a first-order theory with a symbol for each (description of a) primitive recursive function. Its axioms consist of the defining equations for functions defined by explicit definition or primitive recursion, axioms that say that $\fn{succ}(x)$ is injective and zero is not the successor of induction, and a schema of induction for quantifier free formulas $A(x)$: \[ \Forall {\vec z} {A(0) \And (\Forall x {A(x) \Implies A(\fn{succ}(x))}) \Implies \Forall x A(x)} \] Here $\vec z$ denotes the free variables of $A(x)$ other than $x$. $\na{PRA}$ can also be presented as a quantifier-free calculus, or even as nothing more than a calculus of equations of the form $s = t$ between terms in the language. Some historians have argued that $\na{PRA}$ represents the informal notion of \emph{finitistic mathematics} put forth by David Hilbert in the early twentieth century \cite{tait:81}. First-order arithmetic is essentially primitive recursive arithmetic together with the schema of induction for \emph{all} formulas in the language. More precisely, \emph{Heyting arithmetic}, or $\na{HA}$, is the version of this theory based on intuitionistic logic, and \emph{Peano arithmetic}, or $\na{PA}$, is the version based on classical logic. These theories are usually formulated in a smaller language consisting of $0$, $\fn{succ}$, $+$, $\times$, and $\le$. Using coding to represent sequences of numbers and using induction, one can then introduce the primitive recursive functions in a definitional extension. By the first incompleteness theorem, $\na{HA}$, $\na{PA}$, and $\na{PRA}$ are undecidable. All of the mathematical foundations we will consider here support definition by primitive recursion and proof by induction, and most are vastly more powerful than these theories. But even $\na{PRA}$ turns out to be a surprisingly robust theory for finite mathematics. Remarkably, we do not know of any published theorems of mathematics that can naturally be expressed in $\na{PRA}$ but not proved there, short of theorems that were designed by logicians specifically to have that property \cite{MR2006194}. The original Boyer--Moore theorem prover, \emph{NQTHM}, and its successor, \emph{ACL2}, are based on quantifier-free logics similar in spirit to primitive recursive arithmetic. ACL2 was later extended with a principle of induction up to the ordinal $\varepsilon_0$, which makes the system slightly stronger than first-order arithmetic. For details, see \cite{DBLP:books/daglib/0098268}. Theories even weaker than primitive recursive arithmetic have been studied, especially in relation to computational complexity. See, for example, \cite{MR1640326}. \section{Simply Typed Lambda Calculus} \label{section:lf:simply:typed:lambda:calculus} Just as first-order logic provides a framework for modeling logical reasoning, the simply typed lambda calculus provides a framework for reasoning about functions. It includes notions of \emph{lambda abstraction} and \emph{computational reduction} that are fundamental to a number of contemporary proof assistants. \subsection{Syntax} \label{subsection:lf:simply:typed:lambda:calculus:syntax} The set of \emph{simple types} over a collection $\mathcal B$ of \emph{basic types} is defined inductively, as follows: \begin{itemize} \item Every basic type $B \in \mathcal B$ is a type. \item If $\alpha$ and $\beta$ are types, so is $\alpha \to \beta$. \end{itemize} Types are just syntactic expressions, but the idea is that an object of type $\alpha \to \beta$ is a function from $\alpha$ to $\beta$. The simple types are also called the \emph{finite types} because they are built up using finitely many iterations of the arrow construction. Given a collection $\mathcal C$ of constant symbols, each with an assigned type, the set of terms of the simply typed lambda calculus and their associated types are defined inductively as follows: \begin{itemize} \item Each constant $c \in \mathcal C$ is a term of its assigned type. \item There are infinitely many variables $x, y, z, \ldots$ of each type. \item If $t$ is a term of type $\beta$ and $x$ is a variable of type $\alpha$, the term $\Lam x t$ is a term of type $\alpha \to \beta$. \item If $t$ is a term of type $\alpha \to \beta$ and $s$ is a term of type $\alpha$, the term $t \, s$ is a term of type $\beta$. \end{itemize} In the intended interpretation, $\Lam x t$ denotes the function that maps $x$ to $t$, and $t \, s$ is the result of applying $t$ to $s$. The fact that a term $t$ has type $\alpha$ is often written $t : \alpha$. For example, suppose we start with the basic type $\ty{Nat}$ and constants $0 : \ty{Nat}$ and $\fn{succ} : \ty{Nat} \to \ty{Nat}$. Then assuming the variable $x$ has type $\ty{Nat}$ and the variable $f$ has type $\ty{Nat} \to \ty{Nat}$, the term $\Lam f {\Lam x {f \, (\fn{succ} \, (\fn{succ} \, x))}}$ has type $(\ty{Nat} \to \ty{Nat}) \to (\ty{Nat} \to \ty{Nat})$. Intuitively, this term denotes the function that maps any function $f$ to the function $x \mapsto f(x + 2)$. Just as a quantifier binds a variable in a first-order formula, lambda abstraction binds a variable in a lambda expression. Terms that are equivalent up to renaming bound variables are said to be $\alpha$-equivalent and are generally treated as syntactically identical. As with first-order logic, some care is needed to define the notion $t[s/x]$ of substituting $s$ for $x$ in $t$, renaming bound variables if necessary. \subsection{Reduction} \label{subsection:lf:simply:typed:lambda:calculus:reduction} Terms in the simply typed lambda calculus can be \emph{reduced}. A term of the form $(\Lam x t) \, s$ is called a \emph{$\beta$-redex}, and it \emph{$\beta$-contracts} to $t[s/x]$. A term $s$ \emph{$\beta$-reduces to} a term $t$ if $t$ can be obtained from $s$ by iteratively contracting $\beta$-redexes that occur anywhere in the term. One can show that reduction does not change the type of a term, a property known as \emph{subject reduction}. A term that has no $\beta$-redexes is said to be \emph{irreducible} or in \emph{$\beta$-normal form}, and reducing a term to one in normal form is known as \emph{normalization}. You can think of normalization as a notion of computation. In the simply typed lambda calculus with a basic type $\ty{Nat}$ and constants $0$ and $\fn{succ}$, the only closed terms of type $\ty{Nat}$ are numerals, that is, expressions of the form $\fn{succ} \, (\fn{succ} \, \cdots \, (\fn{succ} \, 0) \cdots )$. So, in that setting, reducing a term to normal form is tantamount to evaluating it to a natural number. The computational interpretation of normalization is bolstered by the fact that the simply typed lambda calculus is \emph{strongly normalizing} and \emph{confluent}. Strong normalization means that, starting from any term, there is no infinite sequence of nontrivial one-step reductions, so that any method of reducing a term eventually results in a normal form. Confluence means that if a term $s$ reduces to both $t$ and $u$, then $t$ and $u$ in turn can be reduced to a common term $v$. This implies that normal forms are unique. $\beta$-reduction is often combined with other reductions. An expression $\Lam x t x$ is said to \emph{$\eta$-contract} to $t$ if $x$ is not free in $t$. Whereas $\beta$-contraction for lambda abstraction eliminates an abstraction followed by application, $\eta$-contraction works the other way around, eliminating an application followed by an abstraction. The $\eta$ rule is almost always considered together with $\beta$, giving rise to the notion of $\beta\eta$-reduction, $\beta\eta$-normal form, and so on. The simply typed lambda calculus is strongly normalizing and confluent with respect to $\beta\eta$-reduction as well. \subsection{Equational theories} \label{subsection:lf:simply:typed:lambda:calculus:equational:theories} There are deductive systems for the simply typed lambda calculus associated with $\beta$- and $\beta\eta$-reduction, designed to establish equations $s = t$ between terms. In addition to rules expressing the reflexivity, symmetry, and transitivity of equality, we include the following two rules, which say that equality is preserved under lambda abstraction and application. In the first rule, $s$ and $t$ are assumed to have the same type, and in the second rule, $s$ and $t$ are assumed to have a function type $\alpha \to \beta$, and $u$ and $v$ are assumed to have type $\alpha$.\strut \begin{center} \AXM{\strut s = t} \UIM{\strut (\Lam x s) = (\Lam x t)} \DP \quad \AXM{\strut s = t} \AXM{\strut u = v} \BIM{\strut s \, u = t \, v} \DP \end{center} For $\beta$-reduction, we add axioms $(\Lam x t) \, s = t [s / x]$. It is not hard to show that an equation $s = t$ is provable in this system if and only if $s$ and $t$ have the same $\beta$-normal form. If we add axioms $(\Lam x {t \, x}) = t$, it is similarly not hard to show that $s = t$ is provable if and only if $s$ and $t$ have the same $\beta\eta$-normal form. Using the first $\eta$ axiom, the following is a derived rule, where the variable $x$ is not free in $s$ or $t$:\strut \begin{center} \AXM{\strut s \, x = t \, x} \UIM{\strut s = t} \DP \end{center} To see this, notice that from the premise we can derive $s = (\Lam x {s \, x}) = (\Lam x {t \, x}) = t$. This rule can be viewed as expressing a principle of \emph{extensionality}, since it says that if $s$ and $t$ are functions that have the same values for every input, then $s$ and $t$ are equal. As a result, the equational theory corresponding to $\beta\eta$-reduction is called the \emph{extensional} theory of the simply typed lambda calculus, in contrast to the \emph{intensional} theory corresponding to $\beta$-reduction alone. \subsection{Extensions} \label{subsection:lf:simply:typed:lambda:calculus:extensions} The simply typed lambda calculus can be extended in various ways. For example: \begin{itemize} \item We can add a basic type $\ty{Nat}$ of natural numbers with constants $0 : \ty{Nat}$, $\fn{succ} : \ty{Nat} \to \ty{Nat}$ and \emph{recursors} $\fn{R}$ of appropriate types such that $\fn{R} \, f \, g \, 0$ reduces to $f$ and $\fn{R} \, f \, g \, (\fn{succ} \, x)$ reduces to $g \, x \, (\fn{R} \, f \, g \, x)$. \item We can add a basic type $\ty{Bool}$ of booleans with constants $\fn{tt} : \ty{Bool}$ and $\fn{ff} : \ty{Bool}$ and a conditional function $\fn{cond}$ such that $\fn{cond} \, f \, g \, \fn{tt}$ reduces to $f$ and $\fn{cond} \, f \, g \, \fn{ff}$ reduces to $g$. \item We can add \emph{product types} $\alpha \times \beta$ whose elements are ordered pairs $(s, t)$ with $s : \alpha$ and $t : \beta$. In addition to the pairing operation, product types come equipped with projections $\pi_0$ and $\pi_1$ such that $\pi_0 \, (s, t)$ reduces to $s$ and $\pi_1 \, (s, t)$ reduces to $t$. One sometimes also adds an analogue of $\eta$ reduction whereby $(\pi_0 \, p, \pi_1 \, p)$ reduces to $p$ for any $p : \alpha \times \beta$. \item We can add \emph{sum types} $\alpha + \beta$, whose elements represent either an element of $\alpha$ or an element of $\beta$, tagged to indicate which is the case. These types come equipped with functions $\iota_0 : \alpha \to \alpha + \beta$ and $\iota_1 : \beta \to \alpha + \beta$ that insert elements from $\alpha$ and $\beta$, respectively. Each sum type also come with a $\fn{cases}$ function: given $f : \alpha \to \gamma$ and $g : \beta \to \gamma$, $\fn{cases} \, f \, g \, (\iota_0 \, a)$ reduces to $f \, a$ and $\fn{cases} \, f \, g \, (\iota_1 \, b)$ reduces to $g \, b$. \end{itemize} All these extensions preserve strong normalization and confluence. Notice the common features: in each case, we add a new type construction, canonical means of defining new elements of the new types, and a recursion principle with cases for each canonical construction. With these extensions, the simply typed lambda calculus begins to look more like a programming language, one in which every program is guaranteed to terminate. Simple type theory, discussed in Section~\ref{section:lf:simple:type:theory}, adds a type $\ty{Prop}$ of propositions (or truth values) and can be seen as an even more far-reaching extension of the simply typed lambda calculus. \subsection{Semantics} \label{subsection:lf:simply:typed:lambda:calculus:semantics} There are various kinds of semantics for the simply typed lambda calculus that are similar to the model-theoretic semantics for first-order logic. An \emph{extensional model} interprets each basic type $\alpha$ as a set $\tval{\alpha}$, and each type $\alpha \to \beta$ as a set of functions from $\tval{\alpha}$ to $\tval{\beta}$, in such a way that there are enough functions to interpret the lambda terms. In the \emph{full set-theoretic model}, $\tval{\alpha \to \beta}$ is interpreted as the set of \emph{all} functions from $\tval{\alpha}$ to $\tval{\beta}$, but there are smaller models, for example, where function types are interpreted as suitable sets of computable functions. The simply typed lambda calculus can also be interpreted in any \emph{cartesian closed category} in such a way that types are interpreted as objects and terms are interpreted as arrows. The extensional equational theory described in Section~\ref{subsection:lf:simply:typed:lambda:calculus:equational:theories} is sound and complete for all of these. It is harder to describe a complete semantics for the intensional theory, since it is possible that $(\Lam x {s \, x}) = (\Lam x {t \, x})$ is derivable for a variable $x$ that does not occur in $s$ or $t$ but $s = t$ is not. \emph{Domain theory} provides one way of going about it. In the theory of programming languages, approaches like these, which assign a mathematical object to every expression, are instances of \emph{denotational semantics}. In contrast, an \emph{operational semantics} gives meaning to a programming language by describing its computational behavior. For example, one can take the meaning of the simply typed lambda calculus to be given by a particular evaluation strategy for terms. Alternatively, one can take the meaning to be given by the family of evaluation strategies corresponding to $\beta$- or $\beta\eta$-reduction. In this sense, the meaning of a term is a specification of how we compute with it. The \emph{Curry--Howard correspondence}, or \emph{propositions-as-types interpretation}, can be used to translate a computational interpretation of a system like the simply typed lambda calculus to a computational interpretation of a corresponding system of logical deduction. According to the informal \emph{Brouwer--Heyting--Kolmogorov} interpretation of intuitionistic logic, a proof of $A \Implies B$ is a procedure that maps any proof of $A$ to a proof of $B$, a proof of $A \And B$ is a pair consisting of a proof of $A$ and a proof of $B$, a proof of $A \Or B$ is either a proof of $A$ or a proof of $B$ tagged to indicate which is the case, and so on. The Curry--Howard isomorphism makes this precise by associating with each proposition in a logical system a type in a corresponding system of types, in such a way that proofs in the logical system correspond to terms in a calculus with those types. To illustrate, let us consider an alternative presentation of the simply typed lambda calculus with products, in which types are assigned to variables by a finite set or sequence of specifications $x : \alpha{,}\; y : \beta{,}\; \ldots$ known as a \emph{context}. If $\Gamma$ is a context, a \emph{typing judgment} $\Gamma \vdash t : \alpha$ says that $t$ has type $\alpha$ assuming the variables occurring in $t$ have the types specified by $\Gamma$. With these conventions, the formation rules for terms look like this:\strut \begin{center} \AXN{\strut\Gamma{,}\; x : \alpha \fCenter t : \beta} \UIN{\strut\Gamma \fCenter \Lam x t : \alpha \to \beta} \DP \quad\quad \AXN{\strut\Gamma \fCenter t : \alpha \to \beta} \AXN{\strut\Gamma \fCenter s : \alpha} \BIN{\strut\Gamma \fCenter t \, s : \beta} \DP \\ \medskip \AXN{\strut\Gamma \fCenter s : \alpha} \AXN{\strut\Gamma \fCenter t : \beta} \BIN{\strut\Gamma \fCenter (s, t) : \alpha \times \beta} \DP \quad\quad \AXN{\strut\Gamma \fCenter t : \alpha \times \beta} \UIN{\strut\Gamma \fCenter \pi_0 \, t : \alpha} \DP \quad\quad \AXN{\strut\Gamma \fCenter t : \alpha \times \beta} \UIN{\strut\Gamma \fCenter \pi_1 \, t : \beta} \DP \end{center} Now notice that if we replace the types by formulas, function types by implications, and cartesian products by conjunctions, these are exactly the rules in natural deduction for implication and conjunction with the addition of the terms in the conclusion. If we read the term $t : A$ as saying that $t$ is a proof of $A$, we can interpret the simply typed lambda calculus as a calculus of \emph{proof terms} for the corresponding fragment of intuitionistic logic. Thus, when propositions correspond to types, proofs correspond to terms. A procedure for normalizing terms in the simply typed lambda calculus becomes a procedure for normalizing proofs, and we can therefore take the meaning of an intuitionistic proof to be given by its computational behavior. The correspondence can be extended to other logical constructions. For example, disjunction corresponds to sum types. To extend the correspondence to first-order logic, an equation $s = t$ should correspond to a type, $\ty{Id} \, s \, t$. But now notice that these identity types are parameterized by terms, which is to say, they are \emph{dependent types}. A universally quantified proposition $\Forall x A$ corresponds to a \emph{Pi type}, $\PiT x \alpha$, where $\alpha$ can depend on $x$. Similarly, $\Exists x A$ corresponds to a \emph{Sigma type}, $\SigmaT x \alpha$. We will return to the syntax of dependent type theory in Section~\ref{section:lf:dependently:typed:foundations}. A \emph{realizability relation} provides another way of associating computational content with derivations. The general idea is to define a relation ``\emph{$e$ realizes $A$}'' between formulas $A$ and suitable data $e$, and show that whenever $A$ is provable in a certain deductive system, there exists an $e$ that realizes it. In Stephen Kleene's original version of realizability, $A$ is a formula in the language of first-order arithmetic and $e$ is a natural number. A realizer for $A \Implies B$ is an index for a computable function that takes any number realizing $A$ to a number realizing $B$, a realizer for $A \And B$ is a number coding a pair consisting of a realizer for $A$ and a realizer for $B$, and so on. The propositions-as-types correspondence can be viewed as a kind of realizability in which the formula $A$ itself is a specification of the type of realizers, the typing judgment $e : A$ says that $e$ realizes $A$, and the system used to prove $A$, the system used to define $e$, and the system used to establish that $e$ realizes $A$ are all one and the same. Approaches based on realizability are more flexible in that they allow us to tease these components apart. \section{Set Theory} \label{section:lf:set:theory} Set theory was designed in the early twentieth century to provide a uniform foundation for the methods of modern mathematics, including forms of algebraic abstraction and nonconstructive reasoning about infinite domains that were introduced in the late nineteenth century. It has the advantage that the underlying logic, first-order logic, is simple, and the axioms are intuitive and plausible. It has been so successful at describing modern methods that many mathematicians think of it as providing the gold standard for mathematical proof. \subsection{The axioms} \label{subsection:lf:set:theory:the:axioms} The axioms of \emph{Zermelo--Fraenkel set theory} are expressed in classical first-order logic in a language with a single binary relation symbol, $\in$. We think of the entire mathematical universe as consisting of nothing but sets, and if $x$ and $y$ are sets, $x \in y$ says that $x$ \emph{is an element of} $y$. The first axiom says that two sets are equal if they have the same elements: \begin{itemize} \item Extensionality:\enskip $\Forall{x, y} {(\Forall{z}{z \in x \Iff z \in y}) \Implies x = y}$. \end{itemize} Alternatively, we can formulate set theory in first-order logic without equality and take the antecedent of the implication as a definition of $x = y$. In that case, we need the following axiom in order to prove the substitution property of equality: \begin{itemize} \item $\Forall{x, y} {x = y \Implies \Forall{z} {x \in z \Iff y \in z}}$. \end{itemize} The next four axioms postulate the existence of the empty set, denoted $\emptyset$, with no elements; the unordered pair $\{ x, y \}$, whose elements are $x$ and $y$; the union $\bigcup x$, whose elements $z$ are exactly the members of some set $w$ in $x$; and the power set, $\mathcal{P}(x)$, whose members are exactly the subsets of $x$. In the statement of the power set axiom, $z \subseteq x$ abbreviates $\Forall {w \in z} {w \in x}$. \begin{itemize} \item Empty set:\enskip $\Exists x {\Forall y {y \notin x}}$. \item Pairing:\enskip $\Forall {x, y} {\Exists z {\Forall w {w \in z \Iff w = x \Or w = y}}}$. \item Union:\enskip $\Forall x {\Exists y {\Forall z {z \in y \Iff \Exists w {w \in x \And z \in w}}}}$. \item Power set:\enskip $\Forall x {\Exists y {\Forall z {z \in y \Iff z \subseteq x}}}$. \end{itemize} The next axiom is a schema. For each formula $A(w, \vec x)$, it says that for any choice of parameters $\vec x$ and any set $y$, there is a set $\{ w \in y \mid A(w, \vec x) \}$ whose elements are exactly the elements $w$ of $y$ that satisfy $A$. \begin{itemize} \item Separation:\enskip $\Forall {\vec x, y} {\Exists z {\Forall w {w \in z \Iff w \in y \And A(w, \vec x)}}}$. \end{itemize} The axiom is restricted to separating elements from another set $y$ to avoid Russell's paradox: an unrestricted comprehension axiom would allow us to build the set $\{ w \mid w \not\in w \}$. The variable $z$ is not allowed to appear in $A$; otherwise, taking $A(w)$ to be $w \not\in z$ and taking $y$ to be any nonempty set would lead to a contradiction. The next axiom asserts the existence of an infinite set: \begin{itemize} \item Infinity:\enskip $\Exists x \emptyset \in x \And \Forall y y \in x \Implies y \cup \{ y \} \in x$. \end{itemize} We will discuss this axiom further in Section~\ref{subsection:lf:inductively:defined:sets} and explain how it allows us to define the natural numbers. Nothing so far rules out the possibility that a set can be an element of itself. The axiom of foundation does so. In words, it says that every nonempty set $x$ has an $\in$-least element $y$, that is, an element $y$ such that there is no $z$ in $x$ such that $z$ is in $y$. \begin{itemize} \item Foundation:\enskip $\Forall x {(\Exists y {y \in x}) \Implies \Exists {y \in x} {\Forall {z \in x} {z \notin y}}}$. \end{itemize} The axiom of foundation does not add logical strength. In set theory without that axiom, we can define what it means for a set to be \emph{well founded} and show that the well-founded sets again satisfy the axioms of set theory, as well as the axiom of foundation. Once we have defined the set $\mathbb{N}$ of natural numbers, we can use the power set axiom repeatedly to define sets $\mathcal{P}(\mathbb{N})$, $\mathcal{P}(\mathcal{P}(\mathbb{N}))$, $\mathcal{P}(\mathcal{P}(\mathcal{P}(\mathbb{N})))$, \ldots. But it is consistent with the axioms we have seen so far that there is no single set that contains all of these. The next axiom schema implies that such a set exists. \begin{itemize} \item Replacement: \[ \Forall {x, \vec y} {(\Forall {z \in x} \ExistsUnique {w} {A(z, w, \vec y)) \Implies \Exists u {\Forall w {w \in u \Iff \Exists {z \in x} {A(z, w, \vec y)}}}}}. \] \end{itemize} Here, $A$ is any formula that does not contain $u$. The schema says that if $A$ describes a function on $x$, then the image of $x$ under that function is again a set. This constitutes the core axioms of Zermelo--Fraenkel set theory, sometimes abbreviated $\na{ZF}$. \emph{Zermelo--Fraenkel set theory with choice}, abbreviated $\na{ZFC}$, adds the following principle: \begin{itemize} \item Choice:\enskip $\Forall x {\emptyset \notin x \Implies \Exists {f \in (x \to \bigcup x)} {\Forall {y \in x} f(y) \in y}}$. \end{itemize} In this statement $x \to \bigcup x$ denotes the set of functions from $x$ to $\bigcup x$, relying on the representation of a function as a set of ordered pairs, as described in the next subsection. In words, it says that if $x$ is a collection of nonempty sets, there is a function $f$ which selects an element $f(y) \in y$ from each element $y$ of $x$. The use of the notation $\mathcal P(x)$ for power sets and $\bigcup x$ for unions can be be viewed as definitional extensions, as described in Section~\ref{subsection:lf:definitional:extensions}. But now we have to contend with the slightly confusing situation that there are function symbols and relation symbols in the metatheory, which correspond to functions and relations on the universe of any model, as well as functions and relations as set-theoretic objects \emph{within} the theory, which are elements of the universe of any such model. It might help to think of the former as \emph{global} functions and relations associated with their defining formulas. In particular, if $f$ is a function within the theory and $x$ is a set, the notation $f(x)$ refers to the unique element $y$ such that $(x, y)$ is in $f$. It should therefore be viewed as shorthand for a term of the form $\fn{app}(f, x)$, where $\fn{app}$ is a metatheoretic function symbol introduced to describe that value. The concerns about partial functions raised in Section~\ref{subsection:lf:partial:functions:and:undefined:terms} come into play; to introduce $\fn{app}(f, x)$, we must ensure that its defining formula describes a total function on the entire universe. We therefore have to choose a default value, such as the empty set, for elements $x$ that are not in the domain of $f$. \subsection{Working in set theory} \label{subsection:lf:working:in:set:theory} The axioms of set theory provide recipes for constructing sets. Following Kazimierz Kuratowski we can define the \emph{ordered pair} $(x, y)$ to be the set $\{ \{ x \}, \{ x, y \} \}$, and then we can prove that $(x, y) = (x', y')$ if and only if $x = x'$ and $y = y'$. The set $A \times B$ is the set of all ordered pairs consisting of an element of $A$ and an element of $B$. Triples, quadruples, and so on can be defined by iterating these. A \emph{binary relation} $R$ on $A$ and $B$ is a subset of $A \times B$, and similarly for ternary relations and so on. A \emph{function} $f$ from~$A$ to~$B$ is a binary relation $R_f$ on $A$ and $B$ such that for every $x$ in $A$ there is a unique $y$ in $B$ such that $R(x, y)$ holds, and for any such $x$, $f(x)$ denotes that unique $y$. The set of all functions from $A$ to $B$ is denoted $A \to B$. A $k$-place function $f$ from $A_0, \ldots, A_{k-1}$ to $B$ can be interpreted as an element of $A_0 \times \ldots \times A_{k-1} \to B$. If $f$ is a function from $A$ to $B$, the set $A$ is known as the \emph{domain} of $f$ and $B$ is known as the \emph{codomain}. The domain is a bona fide property of the function: it is the set of values $x$ such that for some $y$, $(x, y) \in f$. But the intended codomain has to be specified independently, since, for example, the function $f(x) = x^2$ defined on the real numbers, $\mathbb{R}$, can be viewed as a function from $\mathbb{R}$ to $\mathbb{R}$ or as a function from $\mathbb{R}$ to $\mathbb{R}^{\ge 0}$, the nonnegative reals. The set of values $y$ such that $(x, y) \in f$ for some $x$ is called the \emph{image} of $f$. The term \emph{range} is sometimes used to refer to the image, and sometimes the codomain. Dropping the existence requirement in the definition of a function gives rise to the notion of a \emph{partial function} from $A$ to $B$; in other words, a partial function $f$ from $A$ to $B$ is a relation $R_f$ such that for every $x$ in $A$ there is at most one $y$ in $B$ such that $(x, y)$ in $f$. Equivalently, a partial function from $A$ to $B$ is a function from some subset of $A$ to $B$. The \emph{quotient construction} is central to modern mathematics, and an important tool in the use of mathematical abstraction. Let $A$ be any set, and let $\equiv$ be an \emph{equivalence relation} on $A$, that is, a reflexive, symmetric, transitive relation on $A$. Think of an equivalence relation in $A$ as a notion of what it means for two objects in $A$ to be the same, up to representational details that are irrelevant to a problem at hand. For any object $a \in A$, its \emph{equivalence class} $[a]$ is the set $\{ b \mid b \equiv a \}$, and the set $A / \equiv$ is the set of equivalence classes of elements of $A$. A function $f$ from $A$ to another set~$B$ is said to \emph{respect} the equivalence relation if whenever $x \equiv x'$, $f(x) = f(x')$. Such a function gives rise to another function $\bar f : {A / \equiv} \to B$ defined by $\bar f([a]) = f (a)$. In Section~\ref{subsection:lf:inductively:defined:sets}, we will explain how to define the natural numbers. The integers, $\mathbb{Z}$, the rationals, $\mathbb{Q}$, and the real numbers, $\mathbb{R}$, can then all be defined as suitable quotients. For example, the real numbers can be constructed as a quotient of the set of Cauchy sequences of rationals. Finally, algebraic structures can be constructed as tuples. For example, a group is a tuple $(G, \circ, e, \cdot^{-1})$ satisfying the group axioms, a metric space $(M, d)$ consists of a set $M$ and a function $d : M \times M \to \mathbb{R}$ satisfying the axioms for a metric space, and a topological space $(X, \mathcal{O})$ consists of a set $X$ together with its \emph{topology}, that is, a collection $\mathcal{O}$ of \emph{open} subsets of $X$ closed under finite intersections and arbitrary unions. \subsection{Inductively defined sets} \label{subsection:lf:inductively:defined:sets} The natural numbers can be characterized abstractly as a set, $\mathbb{N}$, with a constant, $0$, and a function $\fn{succ} : \mathbb{N} \to \mathbb{N}$ satisfying the following: \begin{itemize} \item $0$ is not equal to $\fn{succ}(x)$ for any $x$ in $\mathbb{N}$. \item The function $\fn{succ}(x)$ is injective. \item If $y \subseteq \mathbb{N}$ contains $0$ and is closed under $\fn{succ}(x)$, then $y = \mathbb{N}$. \end{itemize} The third principle is the principle of induction. It is not hard to show that these properties characterize the natural numbers in the sense that if $\mathbb{N}'$, $0'$, and $\fn{succ}'(x)$ satisfy the same description, there is a bijection $F : \mathbb{N} \to \mathbb{N}'$ such that $F(0) = 0'$ and for every $x$, $F(\fn{succ}(x)) = \fn{succ}'(F(x))$. So we only need to show that the axioms of set theory imply the existence of one such set. The von Neumann set-theoretic construction of the natural numbers runs as follows. Take $0$ to be the empty set, $\emptyset$, and take $\fn{succ}(x)$ to be $x \cup \{ x \}$. Notice now that the axiom of infinity says that there exists a set $y$ that contains $0$ and is closed under $\fn{succ}$. Call such a set \emph{inductive}. To satisfy the axiom of induction, roughly, we want to define $\mathbb{N}$ to be the \emph{smallest} inductive subset of $y$. We can achieve that by defining it to be the intersection of all of them: \[ \mathbb{N} = \bigcap \{ z \subseteq y \mid \mbox{$z$ is inductive} \} \] It is now an exercise in unraveling definitions to show that $\mathbb{N}$ is inductive. To see that it satisfies the axiom of induction, let $z \subseteq \mathbb{N}$ be inductive. Since $\mathbb{N}$ is the intersection of all inductive subsets, it is a subset of $z$, and hence $\mathbb{N} = z$. It is clear from these definitions that $0$ is not equal to $\fn{succ}(x)$ for any $x$, since the empty set does not have any elements and $\fn{succ}(x)$ has at least one. It takes a bit more effort to show that $\fn{succ}(x)$ is injective on $\mathbb{N}$, but it can be done. We therefore have a suitable definition of the natural numbers. This is a classic example of an \emph{impredicative} construction: the set of natural numbers is defined with respect to a collection of sets---the collection of inductive subsets of $y$---that includes the very set, $\mathbb{N}$, that is being defined. In the wake of the set-theoretic paradoxes around the turn of the twentieth century, this circularity raised concerns. The definition is problematic if you think of sets as somehow being created by their definitions. The problem goes away if you think of the definition as merely picking out a particular set from among a well-defined totality, namely, the collection of all subsets of $y$. The principle of induction can be used to justify the principle of recursive definition: given any set $B$, any element $b \in B$, and any function $g : \mathbb{N} \times B \to B$, there is a unique function $f$ satisfying \begin{align*} f(0) &= b \\ f(x+1) &= g(x, f(x)) \quad \mbox{for every $x$ in $\mathbb{N}$}. \end{align*} The structure $(\mathbb{N}, \fn{succ}, 0)$ is an instance of an \emph{freely generated inductively defined structure}. The fact that it is inductively defined means that that the elements are generated from the bottom up by the constructors, in this case, $\fn{succ}(x)$ and $0$. This is sometimes thought of as saying that the structure contains \emph{no junk}, in the sense that there is nothing there except what \emph{has} be there to be closed under $0$ and $\fn{succ}$. The fact that $\fn{succ}$ is injective and $0$ is not in its range says that the structure contains \emph{no noise}, in the sense that no unexpected equations hold between elements. This property is essential to justifying the principle of recursive definition. We will see in Chapter~4 that inductively defined structures are fundamental to interactive theorem proving. In some foundational frameworks, such as the systems of dependent type theory discussed in Section~\ref{section:lf:dependently:typed:foundations}, they are given as axiomatic primitives. In others, including most implementations of simple type theory, they are constructed. In that case, the methods generally follows the pattern described here: one finds a set or domain of objects big enough to support the construction, and then carves out the inductive structure with an impredicative definition. \subsection{Variations} \label{subsection:lf:set:theory:variations} An axiom of first-order logic like $A \And B \Implies A$ is schematic, in that $A$ and $B$ can be replaced by arbitrary formulas. The separation and replacement axioms of $\na{ZFC}$ are schemas as well. They are best formulated, therefore, in a system that allows schematic presentations of axioms, with variables that can be replaced by suitable formulas. Some implementations of set theory, like those of Metamath and Isabelle/ZF, allow one to prove schematic theorems as well. Other presentations of set theory avoid the need for schemata by positing two types of objects, sets and \emph{classes}. One can think of a class as a collection of sets that is potentially too large to be a set itself; in particular, the collection of all sets satisfying a first-order formula of $\na{ZFC}$ should form a class. There are two types of extensions of this sort. The theory $\na{NBG}$, or \emph{von Neumann--Bernays--G\"odel set theory}, is a conservative extension of $\na{ZFC}$, which means that it proves the same statements in the smaller language. In contrast, a theory like \emph{Morse--Kelley} set theory is properly stronger than $\na{ZFC}$, which is to say, the use of classes provides new consequences in the original language. Another way to increase the strength of set theory is to postulate the existence of \emph{universes} of sets. A set $U$ is a universe if the following hold: \begin{itemize} \item For every $x$ in $U$, $\mathcal{P}(x)$ is in $U$. \item For every $x$ in $U$ and $y \subseteq x$, $y$ is in $U$. \item If $x \subseteq U$ has cardinality less than that of $U$, then $x$ is in $U$. \end{itemize} In other words, a universe is closed under adding the power set of any element, adding all the subsets of an element, and adding all the subsets of the universe of smaller cardinality. \emph{Tarski--Grothendieck set theory} is $\na{ZFC}$ together with an axiom that says that every set $x$ is an element of some universe $U$. The axiomatizations of set theory in both \relax{Mizar} and \relax{Metamath} include such universes, and this provides a way of working around the fact that some classes of objects are too large to be sets. For example, if we define a category to consist of a set of objects and a set of morphisms between them, we cannot talk about the category of groups, because the class of groups is too big to be a set. But we \emph{can} talk about the category of groups in any particular universe, and the closure properties on universes make that just as useful in practice. Constructive theories based on the notion of set have also been studied \cite{MR519801,MR786465}. If we replace the axiom of infinity by its negation, the result is a theory of the \emph{hereditarily finite sets}, which is equi-interpretable with classical first-order arithmetic. \section{Simple Type Theory} \label{section:lf:simple:type:theory} There are at least three ways to think of simple type theory. One way is to think of it as a variant of set theory that assigns a type to every object and separates the construction of objects from the construction of types. Mathematicians generally distinguish between domains of objects, like the set of natural numbers, function spaces, and algebraic structures, and elements of those domains, like the number 7, the exponential function on the reals, and the identity element of a group. Just as set theory provides fundamental recipes for constructing sets, type theory provides recipes for constructing such domains and their elements. A second way to think of simple type theory is as an extension of first-order logic that allows us to quantify over relations and functions. \emph{Second-order logic} allows for quantifying over relations and functions on the first-order universe, and \emph{higher-order logic} allows for quantifying over relations and functions defined on these second-order domains, functions and relations on those third-order domains, and so on. Yet a third way to think of simple type theory is as an extension of the simply typed lambda calculus with a new type, $\ty{Prop}$, intended to denote a type of propositions. Since a relation can be viewed as a function that returns a proposition, this provides a flexible language for describing functions and relations and making assertions about them. All three perspectives come together in the formal systems we present in Section~\ref{subsection:lf:formulations:of:simple:type:theory}. We will start by exploring the second perspective with a discussion of second- and higher-order logic. \subsection{Second-order logic} \label{subsection:lf:second:order:logic} Second-order logic can be viewed as a many-sorted logic in which we introduce, for each $n$, a sort ranging over $n$-place relations on a first-order universe and a function $\fn{app}_n(R, \vec x)$ to denote the result $R(\vec x)$ of applying the relation $R$ to elements $\vec x$ in that universe. We can then quantify over predicates and relations. For example, suppose we adopt a language for talking about undirected graphs, with a relation $E(x, y)$ that is intended to say that there is an edge from $x$ to $y$. Then the following second-order formula says that the graph is disconnected: \[ \Exists {x, y, P} {P(x) \And \neg P(y) \And \Forall {u, v} {E(u, v) \Implies (P(u) \Iff P(v))}} \] \emph{Second-order logic} is many-sorted first-order logic in such a language, together with a \emph{comprehension} schema that says that every formula defines a relation: \[ \Exists {R} {\Forall {\vec x} {R(\vec x) \Iff A(\vec x)}} \] In this chapter, when we present an axiom schema like this, it is to be understood that a formula like $A$ may have free variables other than the ones shown, in which case these variables are implicitly universally quantified. We require that $R$ is not a free variable of $A$. Without that stipulation, we would have the existence of a relation satisfying $R(\vec x) \Iff \neg R(\vec x)$, a contradiction. Given any formula $A$ that contains an $n$-ary relation variable $R$ and given any formula $B(\vec x)$, we can imagine replacing every atomic formula $R(t_0, \ldots, t_{n-1})$ occurring in $A$ by the formula $B(t_0, \ldots, t_{n-1})$. It is convenient to use $A[\Lam {\vec x} {B} / R]$ to denote this replacement, even though the syntax of second-order logic, as we have just described it, does not include such lambda expressions. In a natural deduction formulation, the following rules can be derived from the comprehension axiom for the formula $B$:\strut \begin{center} \AXN{\strut\Gamma \fCenter A[\Lam {\vec x} {B} / R]} \UIN{\strut\Gamma \fCenter \Exists R A} \DP \quad \AXN{\strut\Gamma \fCenter \Forall R A} \UIN{\strut\Gamma \fCenter A[\Lam {\vec x} {B} / R]} \DP \end{center} Conversely, one can derive the comprehension schema from the first of these rules. If we include an equality symbol for each of the new sorts, we may want to add the corresponding axioms of \emph{extensionality}: \[ \Forall {R, R'} {(\Forall {\vec x} {R(\vec x) \Iff R'(\vec x)}) \Implies R = R'} \] With the substitution axiom for equality, this means that whenever two relations agree on all possible arguments, each can be substituted for the other. In the context of second-order logic, we can instead \emph{define} $R = R'$ by the formula $\Forall {\vec x} {R(\vec x) \Iff R'(\vec x)}$. With this definition, the usual equality axioms are derivable. In second-order logic, we can prove $\Forall {x, y} x = y \Iff \Forall P {P(x) \Iff P(y)}$. This says that two elements of the first-order universe are equal if and only if they have all the same properties, a characterization known as \emph{Leibniz equality} or \emph{identity of indiscernibles}. Alternatively, we can take the right-hand side of the equivalence as the definition of equality on the first-order universe, in which case the usual laws of equality are derivable. Other simplifications are possible. We can think of $0$-ary relations as propositions, and comprehension gives us $\Forall {\vec z} {\Exists P {P \Iff A(\vec z)}}$, where $\vec z$ denotes the free variables of $A$. In other words, every formula corresponds to a proposition. We can then define all the logical connectives in terms of universal quantification and implication as follows: \begin{align*} A \And B & \; \equiv \; \Forall P {(A \Implies (B \Implies P)) \Implies P} \\ A \Or B & \; \equiv \; \Forall P {(A \Implies P) \Implies ((B \Implies P) \Implies P)} \\ \bot & \; \equiv \; \Forall P P \\ (\Exists x A) & \; \equiv \; \Forall P {(\Forall x {A \Implies P}) \Implies P} \end{align*} As a result, one can formulate second-order logic with only the universal quantifier and implication. Moreover, given the correspondence between formulas and propositions, there is no good reason to distinguish between the two. In other words, we can conflate the propositional variable $P$ and the formula $\fn{app}_0(P)$ that says that $P$ holds. As a result, we can take formulas to be terms of the sort of propositions, which we now call $\ty{Prop}$. Implication is then a binary operation that takes two elements of $\ty{Prop}$ and returns an element of $\ty{Prop}$, and universal quantification is a variable-binding construction that applies to terms of sort $\ty{Prop}$. It is reasonable to want to quantify over functions in addition to relations. This can be reduced to quantification over relations by interpreting an $n$-ary function variable~$f$ as an $(n+1)$-ary relation symbol $R_f$ and relativizing to \emph{functional} relations, that is, relations satisfying $\Forall {\vec x} {\ExistsUnique y {R(\vec x, y)}}$. We can then use the method of definite descriptions, presented in Section~\ref{subsection:lf:definitional:extensions}, to interpret uses of the function symbol $f$. Under this interpretation, both classical and intuitionistic versions of second-order logic can prove the following comprehension schema for functions: \[ (\Forall {\vec x} {\ExistsUnique y {A(\vec x, y)}}) \Implies \\ \Exists {f} {\Forall {\vec x} {A(\vec x, f(\vec x))}} \] The stronger schema obtained by dropping the uniqueness requirements in the hypothesis is known as the axiom of choice. In classical second-order logic, it is possible to go the other way and interpret relations as functions. Suppose that, in addition to the first-order universe, we introduce another first-order sort $\ty{Bool}$ of truth values, with constants $\top$ and $\bot$ and an axiom $\top \ne \bot$. Then, for any formula $A(\vec x)$, classical logic proves $\Forall {\vec x} {\ExistsUnique y {y = \top \Iff A(\vec x)}}$. If $f(\vec x)$ meets this specification of a map to $\ty{Bool}$, then $A(\vec x)$ is equivalent to $f(\vec x) = \top$. As a result, we can interpret any relation $R(t_0, \ldots, t_{n-1})$ as an equation $\chi_R(t_0, \ldots, t_{n-1}) = \top$, where $\chi_R$ is the characteristic function of $R$. In intuitionistic logic, however, a two-valued sort is not sufficient to represent truth values. We have already noted that comprehension gives us $\Forall {\vec z} {\Exists P {P \Iff A(\vec z)}}$, where $P$ is of the second-order sort $\ty{Prop}$, so $\ty{Prop}$ can be viewed as a sort of truth values. But any map $\vec z \mapsto P$ is a function from the sort of individuals to the sort of propositions, which takes us beyond second-order logic. It is, however, within the scope of \emph{higher-order logic}, which we turn to next. \subsection{Higher-order logic} \label{subsection:lf:higher:order:logic} Having opened the door to quantifying over predicates and relations on a first-order universe, there is no reason to stop there. One way to describe higher-order logic is to start with a collection $\mathcal B$ of basic sorts and define a set of higher-order sorts inductively as follows: \begin{itemize} \item Every basic sort is a sort. \item If $\alpha_0, \ldots, \alpha_{n-1}$ are sorts, so is $[\alpha_0, \ldots, \alpha_{n-1}]$. \end{itemize} Here, $[\alpha_0, \ldots, \alpha_{n-1}]$ is intended to denote the sort of relations $R(x_0, \ldots, x_{n-1})$ where each $x_i$ is of the sort $\alpha_i$. If $A$ is any formula and the variables $\vec x$ range over the sorts $\vec \alpha$, we have the comprehension axiom $\Exists {R} {\Forall {\vec x} {R(\vec x) \Iff A(\vec x)}}$, where $R$ has sort $[\vec \alpha]$. As in the case of second-order logic, the comprehension axioms can be formulated instead in terms of the $\exists$-introduction rule. A convenient alternative, favored by proof assistants, is to formulate higher-order logic as an extension of the simply typed lambda calculus. To interpret relations as functions, we just need to add a basic type $\ty{Prop}$ of propositions. In a natural deduction formulation, in addition to reflexivity, symmetry, and transitivity of equality, we add rules to express that equality is preserved by lambda abstraction and application, as described in Section~\ref{subsection:lf:simply:typed:lambda:calculus:equational:theories}. If we take formulas to be terms of type $\ty{Prop}$, we no longer need to add comprehension axioms, since we now have a term $\Lam {\vec x} {A(\vec x)}$ to denote the relation $R(\vec x)$ defined by $A(\vec x)$. The axiom for $\beta$-reduction gives $(\Lam {\vec x} {A(\vec x)}) \, \vec t = A(\vec t)$. To avoid a multiplicity of term-binding operations, we can introduce constants $\fn{Forall}_\alpha : (\alpha \to \ty{Prop}) \to \ty{Prop}$ and $\fn{Exists}_\alpha : (\alpha \to \ty{Prop}) \to \ty{Prop}$ for each type $\alpha$, define $\Forall x A$ to be $\fn{Forall}_\alpha \; \Lam x A$, and define $\Exists x A$ to be $\fn{Exists}_\alpha \; \Lam x A$. In contrast to the second-order case, here we cannot easily eliminate the need for extensionality axioms. For example, combining the axiom of extensionality for unary second-order predicates with the substitution rule for equality yields the following for any \emph{third-order} relation $\mathcal{R}$: \[ (\Forall x {P(x) \Iff Q(x)}) \Implies (\mathcal{R}(P) \Iff \mathcal{R}(Q)) \] In the second-order setting, we could define $P = Q$ to be $\Forall x {P(x) \Iff Q(x)}$, in which case the extensionality axiom holds by definition. But when we take equality as a primitive in the higher-order setting, we have $P = Q \Implies \mathcal{R}(P) = \mathcal{R}(Q)$ as an instance of the usual substitution axiom for equality; so if instead we define $P = Q$ to be $\Forall x {P(x) \Iff Q(x)}$, we have to add implications like the one above as additional axioms. In other words, there are two interpretations of an equation $P = Q$ to contend with: Leibniz equality, which says that $P$ and $Q$ can be exchanged in any formula, and extensional equality, which says that $P$ and $Q$ hold of the same elements. The first always implies the second, and extensionality is equivalent to saying that the second implies the first. When we formulate higher-order logic in terms of the simply typed lambda calculus, there are two types of extensionality axioms to consider: \begin{itemize} \item Propositional extensionality:\enskip $\Forall {P, Q : \ty{Prop}} {(P \Iff Q) \Implies P = Q}$. \item Function extensionality:\enskip $\Forall {f, g : \alpha \to \beta} {(\Forall x {f \, x = g \, x}) \Implies f = g}$. \end{itemize} As noted in Section~\ref{section:lf:simply:typed:lambda:calculus}, in the presence of the other equality axioms, function extensionality is equivalent to having an axiom $\Forall f (\Lam x {f \, x}) = f$ for each function type. It turns out that whether we formulate higher-order logic with relations or functions, it is possible to interpret higher-order logic with extensionality in higher-order logic without it, by relativizing quantifiers and variables to the \emph{hereditarily extensional} objects. This shows that, in a theoretical sense, the principle of extensionality does not add logical strength. But the extensional view of functions is fundamental to classical mathematics, and most implementations of classical higher-order logic include some formulation of extensionality. In constructive dependent type theory, the issues are more subtle, since extensionality bears on a system's computational interpretation. We will return to this issue in Section~\ref{section:lf:dependently:typed:foundations}. Regarding semantics, if we formulate second- and higher-order logic as systems of many-sorted first-order logic with relations, having a first-order model is equivalent to having interpretations of each relation sort with enough relations to satisfy the comprehension axioms. Such a model is known as a \emph{Henkin model}, and soundness and completeness for Henkin semantics carries over from first-order logic. Similar considerations hold for the formulation of higher-order logic in the simply typed lambda calculus with extensionality. (As in indicated in Section~\ref{subsection:lf:simply:typed:lambda:calculus:semantics}, since lambda abstraction takes us outside the realm of first-order logic, it takes more work to describe a semantics in which extensionality can fail but equality is nonetheless preserved by lambda abstraction.). In the \emph{standard} interpretation of second-order logic, second-order quantifiers range over \emph{all} relations on the first-order universe, and similarly for higher-order functions and relations in higher-order logic. Because this semantics admits a definition of the natural numbers (modulo an assumption that the first-order universe is infinite), validity in this semantics is far from decidable. As a result, there is no computable notion of proof that gives rise to a system that is sound and complete for the semantics. Intuitionistic higher-order logic has interesting algebraic and category-theoretic interpretations. It can be seen as the \emph{internal logic} of a \emph{topos}, and versions of intuitionistic logic are sound and complete with respect to semantics in an elementary topos. The latter is a generalization of the notion of a topos of sheaves on a Grothendieck site, and that, in turn, is a far-reaching generalization of the notion of a topos of sheaves on a topological space, first developed by Grothendieck for its applications to algebraic geometry. \subsection{Formulations of simple type theory} \label{subsection:lf:formulations:of:simple:type:theory} To sum up the conclusions from the previous subsection, we can build a system of higher-order logic using terms in the simply typed lambda calculus with a basic type of propositions, $\ty{Prop}$, and another basic type of individuals, $\ty{Ind}$, with constants $\fn{Imp} : \ty{Prop} \to \ty{Prop} \to \ty{Prop}$ and $\fn{Forall}_\alpha : (\alpha \to \fn{Prop}) \to \fn{Prop}$ for each type $\alpha$. We write $\Forall x A$ for $\fn{Forall} \, \Lam x A$, define the other propositional connectives as described in Section~\ref{subsection:lf:higher:order:logic}, and define $x =_\alpha y$ at each type $\alpha$ by $\forall P : \alpha \to \ty{Prop}, P \, x \Iff P \, y$. We can take the proof system to establish sequents of the form $\Gamma \fCenter A$, where the elements of $\Gamma$ as well as a $A$ are terms of type $\ty{Prop}$. The axioms and rules of the proof system are as follows: \begin{itemize} \item the natural deduction rules for assumption, implication, and the universal quantifier; \item the equational rules for the simply typed lambda calculus: reflexivity, transitivity, a rule expressing that lambda abstraction respects equality, and axioms for $\beta$-reduction and $\eta$-reduction; \item propositional extensionality: $(P \Iff Q) \to P = Q$. \end{itemize} Church used $\omicron$ instead of $\ty{Prop}$ and $\iota$ instead of $\ty{Ind}$, and this notation is still common in the literature. In classical systems it is possible to show that $\ty{Prop}$ has only two values, and so, in such systems, it can be called $\ty{Bool}$ instead. An alternative approach, adopted by John Harrison in the HOL Light proof assistant \cite{DBLP:conf/tphol/Harrison09a}, is to start with the simply typed lambda calculus with basic types $\ty{Prop}$ and $\ty{Ind}$ as before, but now take equality as basic and define the logical connectives in terms of that. Specifically, we define the following: \begin{align*} \top & \; \equiv \; (\Lam {P : \ty{Prop}} P) = (\Lam {P : \ty{Prop}} P) \\ (\Forall x P) & \; \equiv \; (\Lam x P) = (\Lam x \top) \\ P \And Q & \; \equiv \; (\Forall {\mathcal R} {\mathcal R \, P \, Q = \mathcal R \, \top \, \top}) \\ P \Implies Q & \; \equiv \; P \And Q = Q \end{align*} In the definition of $P \And Q$, the variable $\mathcal R$ has type $\ty{Prop} \to \ty{Prop} \to \ty{Prop}$. Equality on $\ty{Prop}$ serves as bi-implication, and the other logical connectives can be defined as described in Section~\ref{subsection:lf:second:order:logic}. The axioms and rules of the proof system are then as follows: \begin{itemize} \item Equality axioms and rules: reflexivity, transitivity, rules expressing that application and lambda abstraction respect equality, and, finally, $\beta$-reduction and $\eta$-reduction. \item The following logical rules, where $P$ and $Q$ are assumed to have type $\ty{Prop}$:\strut \begin{center} \AXN{\strut P \fCenter P} \DP \quad \AXN{\strut\Gamma \fCenter P = Q} \AXN{\strut\Delta \fCenter P} \BIN{\strut\Gamma{,}\; \Delta \fCenter Q} \DP \quad \AXN{\strut\Gamma{,}\; P \fCenter Q} \AXN{\strut\Delta, Q \fCenter P} \BIN{\strut\Gamma{,}\; \Delta \fCenter P = Q} \DP \end{center} \end{itemize} The two formulations of higher-order logic just described are equivalent and give rise to an intuitionistic logic. The axioms and rules presented so far have a (classical) model in which $\ty{Ind}$ consists of a single element. To obtain a stronger system, we add an \emph{axiom of infinity}, asserting that $\ty{Ind}$ is Dedekind-infinite: \[ \Exists {f : \ty{Ind} \to \ty{Ind}} {(\Forall {x, x'} {f \, x = f \, x' \Implies x = x'}) \And \Exists y {\Forall x {f \, x \ne y}}}. \] This says that there exists a function from $\ty{Ind}$ to $\ty{Ind}$ that is injective but not surjective. Finally, we add a choice operator $\varepsilon_\alpha : (\alpha \to \ty{Prop}) \to \alpha$ with the following axiom, in which $P$ has type $\alpha \to \ty{Prop}$ and $x$ has type $\alpha$: \[ \Forall {P, x} {P \, x \Implies P \, (\varepsilon \, P)}. \] This axiom says that if there is anything that satisfies the predicate $P$, $\varepsilon \, P$ chooses one such value. This operation is often called the \emph{Hilbert epsilon function}, since it was used in the context of first-order arithmetic by David Hilbert and his students in the early 1920s. A trick due to Radu Diaconescu \cite{MR373893} can be used to derive the law of the excluded middle, $\Forall P {P \Or \neg P}$, from extensionality and choice. For a sketch of the argument, let $P$ be an arbitrary element of $\ty{Prop}$, and define the following two predicates: \begin{align*} & U \; \equiv \; \Lam x {(x = \top) \Or P} && V \; \equiv \; \Lam x {(x = \bot) \Or P} \end{align*} From extensionality for propositions and functions, we have $P \Implies U = V$, and hence $P \Implies \varepsilon \, U =\varepsilon \, V$. From the choice axiom, we have $(\varepsilon \, U = \top) \Or P$ and $(\varepsilon \, V = \bot) \Or P$. These two disjunctions give rise to four cases. In three of them, $P$ holds, and in the fourth we have $\varepsilon \, U \ne \varepsilon \, V$, and hence $\neg P$. Those who prefer to avoid using the choice operator can replace it with a definite description operator. To define the natural numbers, one should then add constants to name the objects asserted to exist by the axiom of infinity, and for classical logic one has to add the law of the excluded middle as a separate axiom. \subsection{Extensions} \label{subsection:lf:simple:type:theory:extensions} The previous subsections provide a clean theoretical presentation of simple type theory. We now consider some extensions that are commonly adopted by proof assistants for practical purposes. Even though they extend the theoretical core conservatively, they are so fundamental to the operation of the system that it makes sense to view them as part of the foundation rather than incidental features of the implementation. First, proof assistants invariably allow users to introduce \emph{definitions}. In the context of simple type theory, this amounts to allowing the user to introduce, corresponding to any term $t$ of type $\alpha$, a new constant symbol $\fn{D}$ of the same type, with the axiom $\fn{D} = t$. With lambda abstraction, this allows for explicit definitions of functions and relations. Together with either a definite or an indefinite description operator, this allows for implicit definitions as well. Most proof assistants also provide mechanisms to support things like infix notation, but, in contrast, we view that as syntactic sugar on top of the core logic. Second, given a set of hypotheses, $\Gamma$, a formula, $A$, some variables $x_0, \ldots, x_{n-1}$, and terms $t_0, \ldots, t_{n-1}$ of the same type, most systems include a substitution rule:\strut \begin{center} \AXN{\strut\Gamma \fCenter A} \UIN{\strut\Gamma[\vec t / \vec x] \fCenter A[\vec t / \vec x]} \DP \end{center} This makes it convenient to store theorems schematically and instantiate them. This is a conservative extension because all the axioms and rules of the calculus, as we have presented them, are already closed under substitution. Third, most systems also allow variables $\alpha, \beta, \gamma, \ldots$ ranging over types and a substitution principle for them:\strut \begin{center} \AXN{\strut\Gamma \fCenter A} \UIN{\strut\Gamma[\vec \tau / \vec \alpha] \fCenter A[\vec \tau / \vec \alpha]} \DP \end{center} Here, $\vec \tau$ are arbitrary type expressions, possibly involving other variables. One has to spell what it means to substitute a type expression for a type variable, but that is straightforward. As an example, from the theorem $(\Lam {x : \alpha} x) \, y = y$ for any variable $y$ of type $\alpha$, we can conclude $(\Lam {x : \ty{Ind} \to \beta} x) \, y = y$ for any variable $y$ of type $\ty{Ind} \to \beta$. Fourth, we have included $(\Lam x t) \, s = t [s / x]$ among the axioms of simple type theory, but some systems, like Isabelle, identify a $\beta$-redex with its contraction when comparing and matching expressions. This makes the axioms for $\beta$-reduction unnecessary, since they are just instances of the reflexivity of equality. Such an identification is one way of incorporating a broader notion of \emph{definitional equality} into the logical foundation, something which is discussed in greater detail in Section~\ref{subsection:lf:dependent:type:theory:syntax}. Finally, proof assistants based on simple type theory generally provide a mechanism for defining new types by abstracting a nonempty subset of a type. This makes it possible to define types for the natural numbers, booleans, integers, rationals, reals, and so on. Type constructions can also be parameterized by type variables, so that $\alpha \times \beta$ is an operation that returns the cartesian product, and $\ty{List} \; \alpha$ is the type of lists of elements of objects of type $\alpha$. To understand the principle for defining new types, you should keep in mind that the axioms and rules of higher-order logic, as we have presented them, presuppose that every type is nonempty. Indeed, for every type $\alpha$, $\varepsilon_\alpha \, (\Lam x \top)$ is a closed term of type $\alpha$ and $\Exists {x : \alpha} {x = x}$ is a theorem for every type $\alpha$. (There are variations of higher-order logic that allow for the possibility of empty types by maintaining a context of variables that have been assumed to be elements of each type. We will see that this idea is implemented organically in the context of dependent type theory, where, in contrast, it is hard to avoid the possibility of empty types.) The principle for defining new types is as follows. Suppose $\tau$ is a type expression, possibly involving some type variables $\vec \alpha$. Let $P$ be a closed term of type $\tau \to \ty{Prop}$. (By \emph{closed} we mean that there are no ordinary variables free in $P$, although \emph{types} of $P$ and its subexpressions may depend on the type variables $\vec \alpha$.) Suppose moreover we have have proof that $P$ is nonempty, that is, a proof of $\Exists x {P \, x}$. Then we can introduce a new type constructor, $\ty{D} \, \vec \alpha$, abstractly representing the elements of $\tau$ satisfying $P$. We express this by providing a function $\fn{abs} : \tau \to \ty{D}$ which maps any element $x$ of $\tau$ satisfying $P$ to its abstraction in $\fn{D}$, a function $\fn{repr}$, which maps any element of $\ty{D}$ to its representative in $P$, and axioms saying that these provide a bijective correspondence. Operations on $D$ can be defined from operations on $\tau$ via these functions. Seeing that such definitions yield a conservative extension is not entirely straightforward, but it should seem plausible that one can translate proofs in the expanded system to proofs in the original by relativizing quantifiers to the defining predicates. Alternatively, one can use a model-theoretic argument and show that one can expand any (Henkin) model for the system without definitions to the system with them, by iteratively adding new sorts to accommodate these definitions. \subsection{Working in simple type theory} \label{subsection:lf:working:in:simple:type:theory} Given a type $\alpha$, subsets of $\alpha$ can be represented as predicates $P : \alpha \to \ty{Prop}$. In other words, we can define new types $\ty{Set} \, \alpha$ as abstractions of $\alpha \to \ty{Prop}$, or simply take $x \in P$ to be notation for $P \, x$. We then obtain expected properties of sets, with the caveat that when we talk about a set, it is always, implicitly, a subset of some underlying type. With this identification of predicates with sets, our principle for defining new types allows us to declare a new type in bijective correspondence with any nonempty subset of an existing type. Up to a point, the development of mathematics in simple type theory looks much like the development of mathematics in set theory. Fixing the injective function $f$ asserted to exist by the axiom of infinity and an element $c$ that is not in its range, we can define the type of natural numbers as an abstraction of the intersection of all subsets of $\fn{Ind}$ containing $c$ and closed under $f$. Cartesian products $\alpha \times \beta$ can be represented by the set of relations $R : \alpha \to \beta \to \ty{Prop}$ with the property that for some $a : \alpha$ and $b : \beta$, we have $\Forall {x, y} R \, x \, y \Iff x = a \And y = b$. In other words, we represent pairs as binary relations on $\alpha$ and $\beta$ that hold of exactly one pair of elements. Iterating cartesian products, we get arbitrary tuples of data, sometimes called \emph{records}. Quotients can also be defined as in set theory: if $\alpha$ is a type and $R$ is an equivalence relation on $\alpha$, we can define a new type $\alpha / R$ represented by the set of all nonempty equivalence classes modulo $R$. The integers, rationals, real numbers, and so on can be defined in this way. Inductively defined types like $\fn{List} \, \alpha$ can also be defined as in set theory. Structures are generally parameterized by types. For example, a group structure on a type $\alpha$ is an element of $(\alpha \to \alpha \to \alpha) \times \alpha \times (\alpha \to \alpha)$ consisting of the group operation, the identity, and the inverse function. An element of this type is a group if it satisfies a predicate that says that the multiplication is associative and the identity and inverse have the required properties. Proving a theorem about arbitrary groups then amounts to proving theorems about group structures satisfying the predicate, where $\alpha$ is left as a variable ranging over types. This allows us to prove theorems about arbitrary groups, rings, and fields, and then instantiate them to particular instances, like the integers, rationals, and reals. \subsection{Sets versus types} \label{subsection:lf:sets:versus:types} In comparison to set theory, typed frameworks offer both advantages and disadvantages. An important advantage is that functions and predicates that have been defined in a library come with a specification of the expected types of their arguments, so the system can provide users with an informative error messages when these expectations are not met. Type disciplines also support overloading and more concise manners of expression; when stating a theorem like $\Forall {x y : \mathbb{Z}} {(x + y)^2 = x^2 + 2 \cdot x \cdot y + y^2}$, a user does not have to specify that the addition symbol denotes addition on $\mathbb{Z}$, since that can be inferred from the types of the variables. In a set-theoretic framework, one has to use different notation for the different interpretations of $+$ or devise conventions and mechanisms to disambiguate the meaning. Another advantage is that a proof assistant can use typing information to draw conclusions that generally have to be justified explicitly in set theory. For example, using facts from the library to justify the theorem above may require knowing that a large number of auxiliary expressions, like $(x + y) \cdot x$ and $x^2$, are integers. In a typed framework, this can be inferred automatically when checking that the expression is well formed. In a set-theoretic framework, either users have to do more work or system designers have to provide ad hoc automation to fill in the necessary steps. Some of the disadvantages of using a type discipline have already been mentioned in Section~\ref{section:lf:overview}. A typed foundation is generally more complicated than an untyped one, making it harder to implement the framework and harder to ensure correctness. And from a mathematical perspective, the distinction between objects and types is unnatural. In ordinary mathematics, the symbol $\mathbb{Z}$ for the integers is sometimes used as a type, to delimit the range of significance of a quantifier or a variable, and sometimes used an an object, something that can be manipulated and passed as an argument to a function. As a result, a typing discipline sometimes feels like more of a hindrance than a help, since it often distinguishes between objects that we would like to consider the same. It is disappointing that we have to worry about the differences between the natural number $2$, the integer $2$, and the real number $2$ when formalizing a theorem in type theory. In an implementation of set theory such as that of Mizar, they are the all same object, since the natural numbers and integers are defined as subsets of the real numbers. There are a few things that can be said in defense of types. The first is that one does not \emph{have} to use them. One can certainly implement the natural numbers and integers using predicates $\fn{is\text{-}nat}$ and $\fn{is\text{-}int}$ on the type of real numbers, in which case formal statements about natural numbers and integers look much like they do in a set-theoretic setting. One can even axiomatically introduce a type of sets closed under the usual set-theoretic constructions \cite{DBLP:conf/itp/HanD19,DBLP:conf/cade/Harrison06,DBLP:conf/ictac/Obua06,DBLP:journals/access/SunY20} and develop most of one's mathematics on that type. The reason that this is not generally done is that types are often useful. So the real issue is deciding when it is advantageous to use them and when it is not. A second consideration is that many of the challenges that have to do with identifying mathematical objects in different domains come up in set-theoretic frameworks as well. It might be possible to set up definitions so that the integer 2 and the real number 2 coincide, but there are also 2s in the quaternions, the octonians, every field extension of the rationals, and the $p$-adic numbers for any prime $p$. Mathematicians generally identify the integers with their images in any ring of characteristic zero. They are more generally notorious for identifying structures that are \emph{canonically isomorphic}, where canonical isomorphism is like pornography: it is hard to define, but they know it when they see it. One often refers to ``the two-element group'' even though, of course, there are many of them; in measure theory and probability one conflates the difference between functions and equivalence classes of functions up to almost-everywhere equivalence; and so on. Making these practices formal causes headaches for the set theorist and type theorist alike. Moreover, in situations like these, type theory offers means to help. Given an expression $e$ of type $\mathbb{Z}$ where an expression of type $\mathbb{R}$ is expected, an implementation of type theory can silently or overtly insert a \emph{coercion} or \emph{cast} that embeds $\mathbb{Z}$ into $\mathbb{R}$, as is done in many programming languages. Types also support a mechanism known as \emph{type class inference} that can be used to infer algebraic structure that is implicitly associated with a type, as well as to overload notation in a principled way. Coercions and class inference can be used in conjunction with dependent type theory as well as simple type theory, and they are discussed in detail in Chapter~7. \subsection{Limitations of simple type theory} \label{subsection:lf:limitations:of:simple:type:theory} Once we decide that types are useful, the question is then how elaborate we want our type system to be. Many-sorted first-order logic is a first step toward dividing expressions into syntactic categories, and simple type theory is the next. We should not look to extend a type system without good reason, so this subsection is dedicated to considering some of the limitations of simple types. In simple type theory, there is a sharp distinction between objects and types, and types themselves are not objects. A theorem with polymorphic type variables $\alpha, \beta, \gamma, \ldots$ is implicitly universally quantified over those variables, but one cannot quantify over them explicitly. There is no way to even state the fact that there exists a type with two elements, let alone prove it. Since quantifying over algebraic structures requires, in particular, quantifying over their carrier types, simple type theory has limited capacities for reasoning about them as well. Similarly, in simple type theory, functions between types are modeled as polymorphic type constructors like $\ty{List} \; \alpha$, which are not objects either. So it is impossible to reason about higher-order operations on types and algebraic structures. One can define the abstract notion of a \emph{category} in simple type theory using types to represent the objects and morphisms, but then one cannot use them to reason about concrete categories, like the category of groups. Simple type theory poses similar difficulties for reasoning about abstractions in computer science. Functional programming languages like Haskell rely on \emph{monads}, which are functors on types equipped with operations satisfying certain laws. In simple type theory, we cannot even define the notion of a functor, let alone prove things about them. Another drawback of giving types and type constructors second-class status is that it is becomes impossible to define type constructions that depend on \emph{parameters} that are objects. Although we can define the type of lists, $\ty{List} \; \alpha$, we cannot define the type $\ty{Vector} \, \alpha \, n$ of tuples of elements of $\alpha$ of length $n$, where $n$ is a parameter of type~$\mathbb{N}$. In mathematics, algebraic structures are often constructed from data: \begin{itemize} \item For every $n > 0$, the structure $\mathbb{Z} / n \mathbb{Z}$ of integers modulo $n$ is a ring, and a field if $n$ is prime. \item Multivariate analysis deals with space $\mathbb{R}^n$ of vectors of real numbers of length $n$. \item Linear algebra deals with $m \times n$ matrices, and, for any $n > 0$, the $n \times n$ matrices with elements in a given ring again form a ring. \item For every ring, $R$, we have the ring $R[X]$ of polynomials with coefficients in $R$. \item For every group, $G$, we can consider its group of automorphisms, $\fn{Aut}(G)$. \item A \emph{sheaf} over a topological space $T$ assigns an algebraic structure to each open set of $T$ and a restriction map to every inclusion. \end{itemize} Such constructions cannot be modeled straightforwardly as type constructors in simple type theory. These limitations also bear on applications to computer science, since we cannot define a type of $n$-bit words with $n$ as a parameter, or a type of search trees depending on an order function. In short, the problem is that simple type theory prevents us from thinking about types as full-fledged mathematical objects, and sometimes that is what we want to do. This reflects a fundamental tension between two ways of thinking about types. On the one hand, types are useful syntactic categorizations, enabling a system to determine quickly whether an expression is well formed, fill in information that is left implicit, and provide useful error messages. From that point of view, a type system should be straightforward, deterministic, and efficient. On the other hand, we want flexibility when it comes to specifying systems and spaces of objects. This pushes toward a more elaborate type system. Simple type theory offers a compromise, with a simple but expressive typing discipline. If we are unhappy with this compromise, we have to make a choice. One option is to abandon the use of types and stick with set theory. Dependent type theory, which we will turn to next, goes to the opposite extreme: it brings the expressivity of the language of objects to the language of types, with all the advantages and disadvantages that come with it. \section{Dependent Type Theory} \label{section:lf:dependently:typed:foundations} As with simple type theory, there are various ways to think about dependent type theory. We can view it as a system for constructing mathematical objects and domains of objects, one that overcomes the limitations of simple type theory described in Section~\ref{subsection:lf:limitations:of:simple:type:theory}. But there is another way of thinking of dependent type theory that highlights its computational nature. We have seen that simple type theory can be viewed as an extension of the simply typed lambda calculus, and that, thanks to strong normalization and confluence, the latter can be viewed as a programming language. It is a rather restricted programming language, and the construction of the natural numbers that was described in Section~\ref{section:lf:simple:type:theory} does not directly extend the computational interpretation. But, as described in Section~\ref{subsection:lf:simply:typed:lambda:calculus:extensions}, we can augment the simple types with the types for the natural numbers and other inductively defined structures, together with suitable principles of definition by recursion. If we do that, the simply typed lambda calculus starts to look more like a real programming language, and we can think of simple type theory of a way of extending it with support for writing formal specifications and verifying that they are met. Dependent type theory goes further along this path, augmenting the programming language with a more expressive type system and integrating it more closely with the specification language. In short, a type theory can be viewed either as a proof system in which we can define computable functions if we want to, or as a programming language that allows us to state and prove theorems as well. It is mainly a historical artifact that implementations of simple type theory are usually based on classical logic and favor the first viewpoint, while implementations of dependent type theory are usually based on a constructive logic and favor the second. In this section we will emphasize the constructive viewpoint, in order to balance the classical viewpoint we have developed so far. But it is important to recognize that dependent type theory provides an expressive framework for carrying out classical mathematics as well, and we will describe the axioms and constructions that support that in Section~\ref{subsection:lf:dependent:type:theory:additional:axioms}. Dependent type theory goes by many names, including \emph{constructive type theory} and \emph{intuitionistic type theory}. The next two subsections present the core syntax and basic type constructions, and the subsections that follow present a number of extensions and variations. To avoid introducing names for theories and relating them to existing provers in a piecemeal fashion, we summarize the state of affairs here. Most systems today implement versions of dependent type theory with Pi types, type universes, and inductive types, from which other type constructions can be defined. A key distinguishing feature is whether the system in question implements an impredicative type of propositions, as described in Section~\ref{subsection:lf:the:type:of:propositions}. Systems that do not are generally classified as versions of \emph{predicative type theory} or \emph{Martin-L\"of type theory}, and systems that do are generally classified as versions of \emph{impredicative type theory} or the \emph{calculus of constructions}. Among contemporary proof assistants, Nuprl and Agda implement predicative type theories, and Coq, PVS, Matita, and Lean implement impredicative ones. As will be explained in the next subsection, another distinguishing feature is whether the logical foundation treats equality of types \emph{intensionally} or \emph{extensionally}. Of the systems just mentioned, only Nuprl and PVS are based on type theories that are extensional in this sense. \subsection{Syntax} \label{subsection:lf:dependent:type:theory:syntax} The syntax of dependent type theory is more subtle than that of set theory and simple type theory. In set theory, the sets of terms, formulas, and proofs are defined by successive inductive definitions, each independent of the next. In simple type theory, there are, similarly, three kinds of syntactic objects: types, terms, and proofs. In contrast, dependent type theory can be presented in such a way that there is only one syntactic category, that of \emph{expressions}. Every expression has a type. Some expressions \emph{are} types, some expressions are propositions, and some expressions are proofs, and it is the type of the expression that determines which is the case. The tradeoff is that the definition of the set of well-formed expressions and the relation $t : \alpha$ that expresses that $t$ has type $\alpha$ are more complicated than the syntactic definitions of first-order logic and simple type theory. In dependent type theory, a term $t$ with variables $\vec x$ is judged to be well formed with respect to a \emph{context} $\Gamma$ of the form $x_0 : \alpha_0{,}\; \ldots{,}\; x_{n-1} : \alpha_{n-1}$ that specifies the types of the variables. As with natural deduction and simple type theory, we can use the notation $\Gamma{,}\; x : \alpha$ to denote the extension of $\Gamma$ with the additional hypothesis $x : \alpha$, and we can use $\Gamma{,}\; \Delta$ for the union of two contexts. But now there is an important difference in that the order of the hypotheses matters. In the context $x_0 : \alpha_0{,}\; \ldots{,}\; x_{n-1} : \alpha_{n-1}$, a type expression $\alpha_j$ may depend on a variable $x_i$ for some $i < j$, and so exchanging $x_i$ and $x_j$ does not result in a well-formed context. The expression $\Gamma{,}\; \Delta$ should therefore be interpreted as describing a combination of the two contexts that preserves the dependency structure. Theoretical presentations of dependent type theory generally take a context to be a sequence, and they generally include explicit \emph{structural rules} that allow for weakening a context, contracting duplicate elements, and reordering elements subject to the dependency rules. In contrast, implementations of dependent type theory generally use efficient data structures and algorithms to manage and merge contexts. The following three judgments are usually defined simultaneously with a mutual inductive definition: \begin{itemize} \item the judgment that $\Gamma$ is a valid context; \item the judgment $\Gamma \fCenter t : \alpha$, which says that expression $t$ has type $\alpha$ in context $\Gamma$; \item the judgment $s \equiv t$, which says that expressions $s$ and $t$ are \emph{definitionally equal}. \end{itemize} In dependent type theory, propositions are represented as types, and if $\alpha$ is a proposition, the judgment $t : \alpha$ represents the assertion that $t$ is proof of $\alpha$. The most important task a proof assistant's kernel has to perform is therefore validating judgments of the form $\Gamma \fCenter t : \alpha$. For that purpose, a backward-style presentation of the rules is appropriate (Section~\ref{subsection:lf:first:order:logic:syntax}). To perform the task, type-checking algorithms also need to \emph{infer} the type of an expression; that is, given a well-formed expression $t$ in context $\Gamma$, they need to determine a type $\alpha$ such that $\Gamma \vdash t : \alpha$. See Chapter~7 for details. Let us start with an expression, $\ty{Type}$. For the moment we relinquish the requirement that every expression has a type, so we will not worry about assigning a type to $\ty{Type}$. (We will return to that issue in Section~\ref{subsection:lf:dependent:type:theory:universes}.) We will read judgments of the form $\Gamma \fCenter \alpha : \ty{Type}$ as ``$\alpha$ is a type in context $\Gamma$.'' We add the following two rules for generating contexts: \begin{itemize} \item The empty context is a context. \item If $\Gamma$ is a context, $\alpha$ is a type in context $\Gamma$, and $x$ is a fresh variable, then $\Gamma{,}\; x : \alpha$ is a context. \end{itemize} In analogy to the assumption rule in natural deduction, we have: \begin{itemize} \item If $x : \alpha$ is in $\Gamma$, then $\Gamma \fCenter x : \alpha$. \end{itemize} We also specify that definitional equality is reflexive, symmetric, and transitive, and that it respects the typing judgments: if $\Gamma \vdash t : \alpha$ and we have $t \equiv t'$ and $\alpha \equiv \alpha'$, then $\Gamma \vdash t' : \alpha'$. In the next subsection, we will see why such a rule is necessary. Definitional equality is also called \emph{judgmental equality}, and sometimes \emph{computational equality}, because it can usually be determined in principle by reducing terms to a normal form. The notion of $\beta$-equivalence for terms in the simply typed lambda calculus is a prototypical example of a notion of definitional equality. Saying that two expressions $t$ and $t'$ are definitionally equal says that the logical foundation treats them as being essentially the same. This stands in contrast to \emph{propositional equality}, namely, judgments of the form $\Gamma \vdash p : s =_\alpha t$, where the type $s =_\alpha t$ represents the \emph{proposition} that the terms $s$ and $t$ of type $\alpha$ are equal. Expressions that are definitionally equal are propositionally equal, by the reflexivity of propositional equality. But the converse does not hold in general: since all the resources of mathematics can be brought to bear to prove that two expressions are equal, one cannot identify propositional equality with definitional equality without making type checking undecidable. \emph{Extensional} versions of type theory do add a rule saying that if two expressions are propositionally equal, they are definitionally equal. As a result, type checking in such systems sometimes raises proof obligations for users to meet. Although this section focuses on \emph{intensional} type theory (that is, type theory without that additional rule), almost everything said below applies to both kinds of systems. \subsection{Basic type constructions} \label{subsection:lf:basic:type:constructions} Most rules in dependent type theory are associated with a single type construction and fall into one of the following categories: \begin{itemize} \item \emph{type formation rules}, resulting in a judgment of the form $\Gamma \fCenter \alpha : \ty{Type}$, where $\alpha$ is an instance of the new type construction; \item \emph{introduction rules}, which show how to derive a judgment $\Gamma \fCenter t : \alpha$; \item \emph{elimination rules}, which show how to make use of a hypothesis $x : \alpha$ in the context; \item \emph{conversion rules}, which declare definitional identities, for example asserting that an introduction followed by an elimination can be simplified. \end{itemize} We will follow this organizational scheme where possible. In dependent type theory, the function types $\alpha \to \beta$ are generalized by the \emph{Pi types}, $\PiT {x : \alpha} \beta$, in which the variable $x$ is bound. An element of this type should be viewed as a function $f$ that maps any element $x : \alpha$ to an element of type $\beta$, where $\beta$ can depend on $x$. Such a function is therefore called a \emph{dependent function}. The formation, introduction, and elimination rules are as follows:\strut \begin{center} \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}} \AXN{\strut\Gamma{,}\; x : \alpha \fCenter \beta : \ty{Type}} \BIN{\strut\Gamma \fCenter (\PiT {x :\alpha} \beta) : \ty{Type}} \DP \\ \medskip \AXM{\strut\Gamma{,}\; x : \alpha \fCenter t : \beta} \UIM{\strut\Gamma \fCenter (\Lam {x : \alpha} t) : (\PiT {x : \alpha} \beta)} \DP \quad\quad \AXN{\strut\Gamma \fCenter t : (\PiT {x : \alpha} \beta)} \AXN{\strut\Gamma \fCenter a : \alpha} \BIN{\strut\Gamma \fCenter t \, a : \beta[a/x]} \DP \end{center} The conversion rule is $(\Lam x t) \, s \equiv t[s/x]$. The usual construction $\alpha \to \beta$ represents the special case in which $\beta$ does not depend on $x$. \emph{Sigma types} are another fundamental construction. An element $p$ of $\SigmaT {x : \alpha} \beta$ should be viewed as a pair $(a, b)$ where $a : \alpha$ and $b : \beta[a/x]$. In other words, the Sigma type is a generalization of the cartesian product $\alpha \times \beta$ with elements $(a, b)$ that are \emph{dependent pairs}, in the sense that type of the second component can depend on the first. The formation, introduction, and elimination rules are as follows:\strut \begin{center} \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}} \AXN{\strut\Gamma{,}\; x : \alpha \fCenter \beta : \ty{Type}} \BIN{\strut\Gamma \fCenter (\SigmaT {x :\alpha} \beta) : \ty{Type}} \DP \quad\quad \AXN{\strut\Gamma \fCenter a : \alpha} \AXN{\strut\Gamma \fCenter b : \beta[a/x]} \BIN{\strut\Gamma \fCenter (a, b) : (\SigmaT {x : \alpha} \beta)} \DP \\ \medskip \AXN{\strut\Gamma{,}\; z : (\SigmaT {x : \alpha} \beta) \fCenter \gamma : \ty{Type}} \AXN{\strut\Gamma{,}\; x : \alpha{,}\; y : \beta \fCenter t : \gamma[(x, y) / z]} \AXN{\strut\Gamma \fCenter p : (\SigmaT {x : \alpha} \beta)} \TIN{\strut\Gamma \fCenter \fn{cases}_{\alpha, \Lam x \beta, \Lam z \gamma} \, (\Lam {x, y} t) \, p : \gamma[p / z]} \DP \end{center} The elimination rule, which is analogous to the elimination rule for the existential quantifier in natural deduction, should be understood as follows. Suppose $\gamma$ is a type depending on a value $z$ of type $\SigmaT {x : \alpha} \beta$. Suppose also that $t$ is an expression that, given $x : \alpha$ and $y : \beta$, returns a value of type $\gamma[(x, y)/z]$. Then for any $p$ of type $\SigmaT {x : \alpha} \beta$, assuming $p$ represents the term $(a, b)$, the expression $\fn{cases} \, (\Lam {x, y} t) \, p$ is supposed to be represent $t [a /x, b / y] : \gamma[a/x, b/y]$. The conversion rule says exactly that: \[ \fn{cases} \, (\Lam {x, y} t) \, (a, b) \; \equiv \; t [a /x, b / y] \] We will see in Section~\ref{subsection:lf:dependent:type:theory:inductive:types} that a Sigma type is an instance of an inductively defined type. If we think of the introduction rule as describing the canonical way to build an element of type $\SigmaT {x : \alpha} \beta$, the elimination rule says that every element of $\SigmaT {x : \alpha} \beta$ arises in such a way. A Pi type $\PiT {x : \alpha} \beta$ is analogous to a set-theoretic product $\prod_{x \in A} B_x$, and a Sigma type $\SigmaT {x : \alpha} \beta$ is analogous to set set-theoretic disjoint sum $\sum_{x \in A} B_x$. This explains the use of $\Pi$ and $\Sigma$ in the notation, as well as the fact that Pi types and Sigma types are sometimes called \emph{dependent products} and \emph{dependent sums}, respectively. But be careful: some authors use the phrase \emph{dependent product} to refer to Sigma types instead of Pi types, because the Sigma types can also be viewed as generalizations of the binary cartesian product. Using $\fn{cases}$, we can define the projections: \begin{align*} & \fn{fst} : (\SigmaT {x : \alpha} \beta) \to \alpha && \fn{snd} : (\PiT {z : (\SigmaT {x : \alpha} \beta)} {\beta[\fn{fst} \, z / x])} \end{align*} Given $a : \alpha$ and $b : \beta[a / x]$, these satisfy $\fn{fst} \, (a, b) \equiv a$ and $\fn{snd} \, (a, b) \equiv b$. The second of these identities illustrates the necessity of allowing definitional equality in type checking, since the left-hand side has type $\beta[\fn{fst} \, (a, b) / x]$ and the right-hand side has type $\beta[a / x]$. A type checker has to reduce $\fn{fst} \, (a, b)$ to $a$ in order to recognize that these types are the same. In the elimination rule, the lambdas in the expression $\fn{cases}_{\alpha, \Lam x \beta, \Lam z \gamma} \, (\Lam {x, y} t) \, p$ are meant to indicate that the associated variables are bound by the construction. With the availability of Pi types, we could instead introduce $\fn{cases}_{\alpha, \Lam x \beta, \Lam z \gamma}$ as an expression on its own, with the following type: \[ (\PiT {x : \alpha, y : \beta} {\gamma[(x, y) / z]}) \to \PiT {z : (\SigmaT {x : \alpha} \beta)} \gamma \] In Section~\ref{subsection:lf:dependent:type:theory:universes}, we will explain how $\ty{Type}$ itself can be treated as a type, at which point $\fn{cases}$ itself can be viewed as a constant of the following type: \begin{align*} & \PiT {\alpha : \ty{Type}{,}\; \beta : \alpha \to \ty{Type}{,}\; \gamma : (\SigmaT {x : \alpha} \beta) \to \ty{Type}} {} \\[-\jot] & \quad (\PiT {x : \alpha, y : \beta \, x} {\gamma \, (x, y)}) \to \PiT {z : (\SigmaT {x : \alpha} \beta)} {\gamma \, z} \end{align*} Using constants instead of constructions in this way is analogous to using axioms instead of rules in a presentation of first-order logic. Such approaches are generally favored in implementations, since it is easy to add new constants once the system can handle Pi types appropriately. We will continue to favor a rule-based presentation, however, since that usually clarifies the main ideas. In a similar manner, we can go on to introduce the following types: \begin{itemize} \item sum types, $\alpha + \beta$; \item the natural numbers, $\mathbb{N}$; \item the type $\ty{Empty}$ with no elements; \item the type $\ty{Unit}$ with a single element; \item the type $\ty{Bool}$ with two elements. \end{itemize} Sum types, $\mathbb{N}$, and $\ty{Bool}$ were described in Section~\ref{subsection:lf:simply:typed:lambda:calculus:extensions}. For the type $\ty{Empty}$, there is no introduction rule, and the elimination rule says that we can map an element of empty to any type (which should be vacuously true because there are no elements of that type). The types $\ty{Empty}$, $\ty{Unit}$, and $\ty{Bool}$ are sometimes written $\mathbf 0$, $\mathbf 1$, and $\mathbf 2$, respectively, with the happy consequence that $\mathbf 2$ is isomorphic to $\mathbf 1 + \mathbf 1$. The rules follow the same patterns as the rules for Pi types and Sigma types; the key difference from the simply typed lambda calculus is that the types in the elimination rules can depend on the variable being eliminated. For example, the formation and introduction rules for $\mathbb{N}$ are as follows:\strut \begin{center} \AXN{\strut\Gamma \fCenter \mathbb{N} : \ty{Type}} \DP \quad\quad \AXN{\strut\Gamma \fCenter 0 : \mathbb{N}} \DP \quad \quad \AXN{\strut\Gamma{,}\; x : \mathbb{N} \fCenter \fn{succ} \, x : \mathbb{N}} \DP \end{center} Here is the elimination rule: \begin{center} \AXN{\strut\Gamma{,}\; z : \mathbb{N} \fCenter \gamma : \ty{Type}} \AXN{\strut\Gamma \fCenter s : \gamma(0)} \AXN{\strut\Gamma{,}\; x : \mathbb{N}{,}\; y : \gamma(x) \fCenter t : \gamma(\fn{succ} \, x)} \AXN{\strut\Gamma \fCenter z : \mathbb{N}} \QIN{\strut\Gamma \fCenter \fn{rec}_{\Lam z \gamma} \, s \, (\Lam {x, y} t) \, z : \gamma} \DP \end{center} For brevity, we have written $\gamma(u)$ for $\gamma[u/z]$. There are two conversion rules: \begin{align*} & \fn{rec} \, s \, (\Lam {x, y} t) \, 0 \; \equiv \; s && \fn{rec} \, s \, (\Lam {x, y} t) \, (\fn{succ} \, u) \; \equiv \; t[u/x, \fn{rec} \, s \, (\Lam {x, y} t) \, u / y] \end{align*} With the mechanism introduced in Section~\ref{subsection:lf:dependent:type:theory:universes} to abstract over types, we can express $\fn{rec}$ as a constant with the following type: \[ \PiT {\gamma : (\mathbb{N} \to \ty{Type})} {\gamma \, 0 \to (\PiT {x : \mathbb{N}} {\gamma \, x \to \gamma \, (\fn{succ} \, x)}) \to \PiT {x : \mathbb{N}} {\gamma \, x} } \] Notice that this is essentially the second-order formulation of the induction axiom, with $\ty{Prop}$ replaced by $\ty{Type}$. \subsection{Using propositions as types} \label{subsection:lf:using:propositions:as:types} The rules formulated in the previous section allow for the fact that a type $\alpha$ can depend on a variable $x$, but we have not yet provided any way of introducing such a dependency. To do so, we will invoke the propositions-as-types interpretation, introduced in Section~\ref{subsection:lf:simply:typed:lambda:calculus:semantics}. Remember that, according to the interpretation, we view propositions as data types and proofs of those propositions as terms of those types. Pi and Sigma types can be interpreted in that light. If $\alpha$ is a type that depends on $x$ and we view $\alpha$ as a proposition about $x$, then instead of interpreting a term $p$ of type $\PiT x \alpha$ as a function, we should interpret it as a proof of $\Forall x \alpha$, namely, a recipe that, for every $x$, constructs a proof of $\alpha(x)$. Similarly, a term $p$ of type $\SigmaT x \alpha$ should be viewed as a constructive proof of $\Exists x \alpha$, providing a witness $x$ and a proof of $\alpha(x)$. Thus $\Pi$ and $\Sigma$ are simply the constructive interpretations of $\forall$ and $\exists$. The function type construction $\alpha \Implies \beta$ is identified with implication: constructively, a proof of $\alpha \Implies \beta$ is a recipe that transforms a proof of $\alpha$ into a proof of $\beta$, or a recipe that transforms evidence for $\alpha$ into evidence for $\beta$. In first-order logic, given any terms $a$ and $b$, we can express the proposition that $a$ is equal to $b$. To do this in type theory, we simply add a new construction, the \emph{identity types}. Given $a : \alpha$ and $b : \alpha$, we introduce a type $\ty{Id}_\alpha \, a \, b$, which we will write $a =_\alpha b$. Drawing on propositions as types, we should think of an element $p : a =_\alpha b$ as a proof, or some sort of evidence, that $a$ and $b$ are equal. The formation and introduction rules are as follows:\strut \begin{center} \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}} \AXN{\strut\Gamma \fCenter a : \alpha} \AXN{\strut\Gamma \fCenter b : \alpha} \TIN{\strut\Gamma \fCenter a =_\alpha b : \ty{Type}} \DP \quad\quad \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}} \AXN{\strut\Gamma \fCenter a : \alpha} \BIN{\strut\Gamma \fCenter \fn{refl}_\alpha \, a : a =_\alpha a} \DP \end{center} The elimination rule is as follows: given \begin{itemize} \item $\Gamma{,}\; x : \alpha{,}\; y : \alpha{,}\; p : x =_\alpha y \fCenter \gamma : \ty{Type}$, \item $\Gamma{,}\; z : \alpha \fCenter t : \gamma[z/x, z/y, \fn{refl}_\alpha \, z/ p]$, \item $\Gamma \fCenter a : \alpha$, \item $\Gamma \fCenter b : \alpha$, \item $\Gamma \fCenter u : a =_\alpha b$, \end{itemize} we have $\fn{cases}_{\alpha, \Lam {x, y, p} {\gamma}} \, (\Lam z t) \, a \, b \, u : \Gamma[a/x, b/y, u/p]$. (We should really write $\fn{cases}^=$ instead of $\fn{cases}$ to distinguish it from the $\fn{cases}$ functions for Sigma types and sum types, but we will leave such distinctions implicit.) The rule says that if we have $u : a =_\alpha b$, we can, in a sense, assume that $u$ is really $\fn{refl} \, a : a =_\alpha a$. For brevity we will omit the conversion rule which says, roughly, that casing on reflexivity is the identity operation. The elimination rule is a generalization of the substitution rule for equality, which asserts that given $e : a =_\alpha b$ and $h : \gamma \, a$ we can conclude $\fn{subst} \, e \, h : \gamma \, b$. If we think of $\gamma$ as a parameterized data type instead of a proposition, the substitution rule has a novel interpretation. Given an object $h$ of type $\gamma \, a$ and the fact $e : a =_\alpha b$, the types $\gamma \, a$ and $\gamma \, b$ should be equal, and so $h$ should have type $\gamma \, b$ as well. But unless $\gamma \, a$ and $\gamma \, b$ are definitionally equal, the type checker cannot tell that they are the same type. The additional information $e$ is needed to help the type checker see that they are, and the expression $\fn{subst} \, e \, h$ therefore serves to \emph{cast} or \emph{transport} $h$ along the equality to an object of type $\gamma \, b$. With identity types in hand, we are off and running: we now have expressive means to define complex data types as well as state complex mathematical propositions. The propositions-as-types interpretation takes some getting used to, because types can be viewed as both data types and propositions, often at the same time. Viewed as a data type, the recursor for the natural numbers expresses the principle of recursive definition. Viewed as a proposition, it expresses the principle of induction. We can therefore use the recursor to define addition and multiplication, and then use the same recursor to prove things about them. For example, the type $\PiT {x, y : \mathbb{N}} {x + y = y + x}$ expresses that addition is commutative, and a term of that type is interpreted as a proof of that fact. Given $x$ and $y$ of type $\mathbb{N}$, we can define $x \le y$ to be the type $\SigmaT {z : \mathbb{N}} {x + z = y}$. In a similar way, we can define types $\ty{Divides} \, x \, y$, $\ty{Even} \, x$, and $\ty{Prime} \, x$. We can view an element of the type \[ \PiT {x : \mathbb{N}} {\SigmaT {y : \mathbb{N}} {(x \le y) \, \times \, \ty{Prime} \, y}} \] as a proof that for every $x$ there is a $y \ge x$ such that $y$ is prime. But we can also view it as a function which, given any $x$, returns such a prime, together with evidence that it meets this specification. For another example, we can express the Goldbach conjecture with the following type: \[ \PiT {x : \mathbb{N}} {\ty{Even} \, x \; \times \; (x > 2) \Implies \SigmaT {y, z : \mathbb{N}} {\ty{Prime} \, y \; \times \; \ty{Prime} \, z \; \times \; (x = y + z)}} \] A proof then includes a function that, given $x$ and evidence that $x$ is even, computes the relevant decomposition. We can now see how dependent type theory allows us to do some of the things that were described in Section~\ref{subsection:lf:limitations:of:simple:type:theory} as falling outside the range of simple type theory. For example, given $n : \mathbb{N}$, we can define the type $\ty{Fin} \; n$ to be $\SigmaT {x : \mathbb{N}} {x < n}$, so that $\ty{Fin} \; n$ represents a type with $n$ elements. We can then define $\ty{Vec}_\alpha \; n$ to be $\ty{Fin} \; n \to \alpha$ and $\fn{Matrix}_\alpha \; m \, n$ to be $\ty{Fin} \; m \to \ty{Fin} \; n \to \alpha$. \subsection{Inductive types} \label{subsection:lf:dependent:type:theory:inductive:types} We were able to define the natural numbers in set theory and simple type theory from axioms asserting the existence of an infinite set or type, respectively. We could try to do something similar in dependent type theory, but the rules we have introduced so far are not strong enough to carry out an impredicative construction. We could define the natural numbers using an axiom of infinity and the impredicative type of propositions described in Section~\ref{subsection:lf:the:type:of:propositions}, but the resulting type would not have nice computational properties. In dependent type theory, it is more natural to add such inductive constructions axiomatically, with new type constructors and rules. This encourages the inductive constructions to be thought of abstractly, in terms of their constructors and recursion principles. For example, the type $\ty{List} \; \alpha$ has constructors $\fn{nil}_\alpha : \ty{List} \; \alpha$ and $\fn{cons}_\alpha : \alpha \to \ty{List} \; \alpha \to \alpha$. The recursor expresses a principle of recursion on lists, and the conversion rule says that the recursor satisfies the expected defining equations. In the next subsection we will see that once we have variables ranging over types, we can promote the subscripted $\alpha$ in $\fn{cons}_\alpha$ to a bona fide argument to $\fn{cons}$, resulting in a single $\fn{cons}$ function that is \emph{polymorphic} over types. The \emph{W Types}, introduced by Martin-L\"of, are a canonical family of inductively defined types. The formation and introduction rules are as follows:\strut \begin{center} \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}} \AXN{\strut\Gamma{,}\; x : \alpha \fCenter \beta : \ty{Type}} \BIN{\strut\Gamma \fCenter (\GenericBinder W {x : \alpha} \beta) : \ty{Type}} \DP \\ \medskip \AXN{\strut\Gamma \fCenter a : \alpha} \AXN{\strut\Gamma{,}\; y : \beta[a/x] \fCenter f : (\GenericBinder W {x : \alpha} \beta)} \BIN{\strut\Gamma \fCenter \fn{sup}_{\alpha, \Lam x \beta} \, a \, f : (\GenericBinder W {x : \alpha} \beta)} \DP \end{center} An element of $\GenericBinder W {x : \alpha} \beta$ is intended to denote a well-founded tree whose nodes are labeled by elements of $\alpha$, with the property that the subtrees of a node labeled $a$ are indexed by the elements of $\beta[a/x]$. The tree $\fn{sup} \, a \, f$ is the tree whose top node is labeled $a$ and whose children are given by $f$. (In order for us to construct an element of this type, there has to be at least one $a$ in $\alpha$ such that $\beta[a/x]$ is empty, so that the single node labeled $a$ is a tree.) The elimination principle provides a recursion for such well-founded trees, as follows. Given a family of types $\gamma$ indexed by trees, \begin{center} \AXN{\strut\Gamma{,}\; z : (\GenericBinder W {x : \alpha} \beta) \fCenter \gamma : \ty{Type},} \DP \end{center} and given a term $t$ that assigns a value to any tree of the form $\fn{sup} \, a \, f$ from an assignment $g$ of values to its subtrees, \begin{center} \AXN{\strut\Gamma{,}\; a : \alpha{,}\; f : (\beta[a/x] \to \GenericBinder W {x : \alpha} \beta), g : (\PiT {y : \beta[a/x]} \gamma[f \, y / z]) \fCenter t : \gamma [\fn{sup} \, a \, f / z],} \DP \end{center} we have a value for every tree $u$, \begin{center} \AXN{\Gamma{,}\; u : (\GenericBinder W {x : \alpha} \beta) \fCenter \fn{rec}_{\Lam z \gamma} \, (\Lam {a, f, g} t) \, u : \gamma[u/z].} \DP \end{center} The conversion rule, not shown, says that the recursor satisfies the expected defining equations. Sigma types, cartesian products, and sum types can all be viewed as instances of inductive types. In fact, with the notion of \emph{indexed families of types}, even the identity types introduced in the last subsection become an instance of the general schema. For details, see Chapters~3 and 4. \subsection{Universes} \label{subsection:lf:dependent:type:theory:universes} At this point, we can construct concrete types like $\mathbb{N} \to \mathbb{N}$, $\fn{List} \; \mathbb{N}$, and $\ty{Fin} \; n$, but we do not have variables ranging over types. Recall that the rule for introducing a new variable into the context is as follows: \begin{itemize} \item If $\Gamma$ is a context and $\Gamma \fCenter \alpha : \ty{Type}$, then $\Gamma, \, x : \alpha$ is a context. \end{itemize} So, as things stand, we need a judgment $\ty{Type} : \ty{Type}$ in order to have a variable range over types. Unfortunately, this makes the system inconsistent \cite{girard:72}. A solution is to replace $\ty{Type}$ by a sequence of type universes, $\ty{Type}_0, \ty{Type}_1, \ty{Type}_2, \ldots$ with $\ty{Type}_i : \ty{Type}_{i+1}$. Now any judgment of the form $\alpha : \ty{Type}_i$ is interpreted as saying that $\alpha$ is a type, but every type belongs to a particular type universe. Sometimes the letter $\ty{U}$ is used to denote type universes instead, as in $\ty U_0, \ty U_1, \ty U_2, \dotsc$. Once we have variables ranging over types, we can construct Pi types and lambda abstractions that bind those variables. Type formation rules need to specify which universe the constructions end up in. For Pi types, the formation rules becomes the following:\strut \begin{center} \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}_i} \AXN{\strut\Gamma{,}\; x : \alpha \fCenter \beta : \ty{Type}_j} \BIN{\strut\Gamma \fCenter (\PiT {x :\alpha} \beta) : \ty{Type}_{\fn{max} \, i \, j}} \DP \end{center} In other words, a Pi type lands in the larger of the two universes. An an example, the expression $\Lam {\tau : \ty{Type}_i} {\Lam {x : \tau} x}$, which represents the polymorphic identity function for types in the universe $\ty{Type}_i$, has type $\PiT {\tau : \ty{Type}_i} {\tau \to \tau}$. That expression, in turn, has type $\ty{Type}_{i + 1}$. The formation rules for inductive types also have to be adjusted accordingly. Implementations of type theory with universes tend to use variables $i, j, \ldots$ ranging over the levels of a type universe so that definitions and theorems can be expressed generically and work when instantiated to any particular universe. This is known as \emph{universe polymorphism}, and it allows us to write $\ty{Type}$ instead of $\ty{Type}_i$ and leave it to the system to work out the constraints on the choice of $i$. This is often quite effective in providing the illusion that there is just one big universe of types. Some formulations of type theory add the following rule, for any $j > i$:\strut \begin{center} \AXN{\strut\Gamma \fCenter \alpha : \ty{Type}_i} \UIN{\strut\Gamma \fCenter \alpha : \ty{Type}_j} \DP \end{center} This effectively makes the type universes \emph{cumulative}. The ability to quantify over types means that we can make structures into first-class objects. For example, we can define the type $\ty{Group}_i$ of groups with carrier in the universe $\ty{Type}_i$ as a big Sigma type: \begin{align*} & \SigmaT {\, \ty{Carrier} : \ty{Type}_i} {} \\[-\jot] & \quad \SigmaT {\, \fn{op} : \ty{Carrier} \to \ty{Carrier} \to \ty{Carrier}{,}\; \fn{id} : \ty{Carrier}{,}\; \fn{inv} : \ty{Carrier} \to \ty{Carrier}} {} \\[-\jot] & \quad (\PiT {x, y, z : \ty{Carrier}} {\fn{op} \, (\fn{op} \, x \, y) \, z = \fn{op} \, x \, (\fn{op} \, y \, z)}) \times (\PiT {x : \ty{Carrier}} {\fn{op} \, x \, \fn{id} = x}) \times \cdots \end{align*} In words, a group consists of a type, $\ty{Carrier}$, a binary operation $\fn{op}$ on $\ty{Carrier}$, an identity element $\fn{id}$, and an inverse function $\fn{inv}$, satisfying the group axioms. It can take time to get used to the fact that the data associated with a group and its axiomatic properties are treated uniformly as elements of the structure, but this is a hallmark of dependent type theory, and it can be very useful. We have now realized most of the design requirements enumerated in Section~\ref{subsection:lf:limitations:of:simple:type:theory}. Types are expressions, every expression has a type, and we have all the means of dependent type theory at our disposal to define new types as expressions of type $\ty{Type}_i$ for some $i$. Expressions in type theory can be verbose. The polymorphic $\fn{cons}$ function on lists has type $\PiT {\tau : \ty{Type}} {\tau \to \ty{List} \; \tau \to \ty{List} \; \tau}$, so that given $n : \mathbb{N}$ and $\ell : \ty{List} \; \mathbb{N}$, we have to write $\fn{cons} \, \mathbb{N} \, n \, \ell$ for the result of adding $n$ to the beginning of $\ell$. Implementations of type theory usually allow the first argument to $\fn{cons}$ to be marked \emph{implicit}. This allows users write $\fn{cons} \, n \, \ell$ and leave it to the system to infer that the first argument is $\mathbb{N}$ from the types of $n$ and $\ell$. This process is described in detail in Chapter~7. In dependent type theory, most concrete type constructions, like the number systems, land in the smallest universe, $\ty{Type}_0$. It is only generic constructions involving types that require larger universes. A type whose elements are structures with carrier in $\ty{Type}_i$ is itself an element of $\ty{Type}_{i+1}$. In category theory, one sometimes wants to consider a type of \emph{small} categories, where the objects are elements of a type in $\ty{Type}_{i+1}$, while the morphisms between any two objects are represented by a type in $\ty{Type}_i$. (For example, the type of groups with carrier in $\ty{Type}_i$ itself has type $\ty{Type}_{i+1}$, but the type of morphisms between any two such groups has type $\ty{Type}_i$.) The type of such small categories itself has type $\ty{Type}_{i+2}$. \subsection{The type of propositions} \label{subsection:lf:the:type:of:propositions} The propositions-as-types interpretation, as we have developed it so far, highlights the parallels between data type constructions and logical operations. It reminds us that every mathematical statement has potential computational significance, whether or not we choose to think of it in those terms. But the conflation of propositions and types is sometimes unnatural. Elements of the types $\ty{Fin} \; x$, which were defined as $\SigmaT {y : \mathbb{N}} {y < x}$ in Section~\ref{subsection:lf:using:propositions:as:types}, are best viewed as a piece of data meeting a specification. Describing them as constructive proofs that there exists something less than $x$ or as the combination of two pieces of data is awkward. There are other reasons to resist conflating proofs and data. Suppose $(y, h)$ and $(y', h')$ are both elements of $\ty{Fin} \; x$. Under what conditions should we say that they are equal? Under a strict propositions-as-types interpretation, it is not enough to know $y = y'$; we also have to worry about the equality of $h$ and $h'$ under the cast that identifies their types. From a mathematical perspective, these proofs are irrelevant. Another problem is that under the strict propositions-as-types interpretation, propositions are stratified by the type universes. A theorem about groups in type universe $i$, $\PiT {G : \ty{Group}_i} \dotsc$, is at best an element of $\ty{Type_{i+1}}$. We can no longer take a subset of a type $\alpha$ to be a function of type $\alpha \to \ty{Prop}$; rather, for each $i$, we can talk about the subsets of type $\alpha \to \ty{Type}_i$. So we cannot define the subgroup of a group $G$ generated by a set of elements $S$ to be the intersection of all the subgroups of $G$ containing $S$. Instead, given $\ty{Carrier} \; G : \ty{Type}_i$ and $S : \ty{Carrier} \; G \to \ty{Type}_j$, for any $k$ we can consider the sets of type $\ty{Carrier} \; G \to \ty{Type}_k$ containing $S$ and closed under the group operations. A universe calculation shows that the intersection of these subgroups has type $\ty{Carrier} \; G \to \ty{Type}_\ell$, where $\ell = \max (i, j, k+1)$. In particular, $\ell > k$, so the subgroup just defined is not among the subgroups in the intersection. In other words, propositions as types, as we have understood it so far, serves to stratify sets into a hierarchy whereby any definition of a set that quantifies over a fixed totality of sets produces a new set that is not part of that totality. Such a treatment of sets and types is said to be \emph{predicative}, a term introduced early in the twentieth century in the wake of the set-theoretic paradoxes. Russell and Whitehead's original \emph{ramified type theory} had this character, but it was deemed unworkable for ordinary mathematics without an additional axiom, the \emph{axiom of reducibility}, which provided an ad hoc workaround. A better solution is to introduce a type $\ty{Prop}$ like the one in simple type theory, with the property that a Pi type $\PiT {x : \alpha} \beta$ is in $\ty{Prop}$ whenever $\beta$ is in $\ty{Prop}$, no matter what type universe $\alpha$ is in. It is common to use the notation $\Forall {x : \alpha} \beta$ for such a Pi type, and putting it in $\ty{Prop}$ means that we can form a proposition by quantifying over the elements of any type. Such a type $\ty{Prop}$ is said to be \emph{impredicative}. One can think of a type $\alpha : \ty{Prop}$ is being inhabited if and only if $\alpha$ is true, in which case, a judgment $h : \alpha$ shows that it is true. The type $\ty{Prop}$ can be placed at the bottom of the hierarchy of universes by declaring $\ty{Prop} : \ty{Type}_0$, or alongside the smallest universe of data by declaring $\ty{Prop} : \ty{Type}_1$. With such a type of propositions, one can use a general framework for inductive definitions to define logical operations. The connectives $\exists$, $\wedge$, $\vee$, and $\bot$ are defined just like $\Sigma$, $\times$, $+$, and $\ty{Empty}$, except that the results land in $\ty{Prop}$ rather than $\ty{Type}$. Identity types are also generally assumed to take values in $\ty{Prop}$. To balance the strength of impredicativity, restrictions are placed on the elimination rules. Saying that a type $\alpha$ is a proposition is meant to distinguish it from a data type; the existence of an element $h : \alpha$ is supposed to show that $\alpha$ is true but the object that $h$ denotes need not bear any additional information. The distinction means that, given $\alpha : \ty{Type}_i$ for some $i$, and given $\beta : \ty{Prop}$, there are two versions of the Sigma type construction $\SigmaT {x : \alpha} \beta$, depending on whether we view it as a data type or a proposition: \begin{itemize} \item The \emph{subtype} $\{ x : \alpha \mid \beta \} : \ty{Type}_i$ consists of pairs $(a, h)$, where $a : \alpha$ and $h : \beta[a / x]$. The first component is data, and can be used in functions with any return type. The second component is a proposition. \item The proposition $(\Exists {x : \alpha} \beta) : \ty{Prop}$ says that there exists an $x$ satisfying $\beta$. An element $h$ of this type only guarantees the existence of such an $x$, but it does not make one available as data. \end{itemize} Classically, we can think of every element of $\ty{Prop}$ as being either a type with no elements, $\False$, or a type, $\True$, with a single element, $\fn{trivial} : \True$. In other words, classically, we can identify $\ty{Prop}$ with $\ty{Bool}$. We can formalize the statement that $\ty{Prop}$ is two-valued with the following strong form of the law of the excluded middle, known as \emph{propositional decidability}: \[ \Forall {\alpha : \ty{Prop}} {\alpha + \neg \alpha} \] This suffices to define an isomorphism between $\ty{Prop}$ and $\ty{Bool}$. The following principle, known as \emph{proof irrelevance}, says that any two proofs of a proposition are equal. \[ \Forall {\alpha : \ty{Prop}{,}\; h_1 : \alpha{,}\; h_2 : \alpha} {h_1 = h_2} \] Given any predicate $P : \alpha \to \ty{Prop}$, proof irrelevance implies that any two elements of the subtype $\{ x : \alpha \mid P \, x \}$ are equal if their first components are equal; in other words, only the value matters, not the justification. Proof irrelevance is consistent with the classical view of $\ty{Prop}$ described in the last paragraph, but it is also reasonable from a constructive viewpoint in which the operations that land in $\ty{Prop}$ are viewed as erasing computational information. The principle can even be implemented as a conversion rule, in which case it is called \emph{definitional proof irrelevance}. The notion of proof irrelevance is not limited to the presence of $\ty{Prop}$: even in predicative type theory, one can add an axiom that says that any two elements of an identity type $a =_\alpha b$ are equal. This principle is known as \emph{axiom K}. To sum up, the introduction of an impredicative type universe $\ty{Prop}$ offers the following benefits: \begin{itemize} \item It provides a means to separate propositions from data. \item It allows for impredicative definitions. \item It provides a means of incorporating proof irrelevance. \end{itemize} In ordinary mathematics, the distinction between propositions and data is more natural. \subsection{Additional axioms} \label{subsection:lf:dependent:type:theory:additional:axioms} The axiom of function extensionality, discussed in Section~\ref{subsection:lf:higher:order:logic}, can be extended to dependent functions: \[ \Forall {\alpha : \ty{Type}{,}\; \beta : \alpha \to \ty{Type}} \Forall {f, g : (\PiT {x : \alpha} \beta \, x)} {(\Forall {x : \alpha} {f \, x = g \, x}) \Implies f = g} \] The axiom of propositional extensionality is essentially unchanged: \[ \Forall {\alpha, \beta : \ty{Prop}} {(\alpha \Iff \beta) \Implies \alpha = \beta}. \] Neither of these is derivable from the axioms we have seen so far, but both can be consistently added. In the context of dependent type theory with an impredicative type of propositions, there is an elegant formulation of the axiom of choice. Define $\ty{Nonempty} \; \alpha$ to be the proposition $\Exists {x : \alpha} \top$, which asserts that there exists an element of type $\alpha$. We can then assert the existence of a function that chooses an element from any nonempty type: \[ \fn{choice} : \PiT {\alpha : \ty{Type}} {\ty{Nonempty} \; \alpha \to \alpha} \] A version of the $\varepsilon$ function, discussed in Section~\ref{subsection:lf:formulations:of:simple:type:theory}, can be defined from that. The sketch of Diaconescu's theorem presented there can be modified to derive propositional decidability from choice and extensionality. The addition of propositional extensionality and function extensionality can have negative effects on computational reduction. Ideally, in a constructive type theory, every closed term of type $\mathbb{N}$ should reduce to a numeral. The extensionality axioms, however, can block such reductions; for example, there is generally no way to reduce an expression $\fn{subst} \, e \, h$ when $e$ is an instance of the extensionality axiom, even though the substitution operator $\fn{subst}$ can be interpreted as a computationally inert operation that only serves to modify the type of $h$. But propositional and function extensionality are generally consistent with computational interpretations that ignore type information and replace $\fn{subst} \, e \, h$ by $h$. As a result, a constructive proof assistant that incorporates extensionality can still support code extraction. In contrast, the use of the choice axiom breaks the computational interpretation entirely. With functional extensionality, propositional extensionality, and choice, dependent type theory has a fully classical flavor. Many other additions to type theory have been considered in the literature. For example, \emph{quotient types} \cite{DBLP:conf/tlca/Hofmann95,DBLP:conf/tphol/Nogin02} provide an axiomatic way of constructing quotients, and \emph{induction-induction} and \emph{induction-recursion} provide more general forms of inductively defined types. Many systems also implement \emph{coinductive types}, as described in Chapter~5. \subsection{Homotopy type theory} \label{subsection:lf:homotopy:type:theory} \emph{Homotopy type theory} draws on the fact that predicative type theory has a homotopy-theoretic interpretation, first discovered by Steve Awodey and Michael Warren on the one hand, and Vladimir Voevodsky, independently, on the other. Rather than thinking of types as data types, we can think of them as topological spaces, and rather than think of terms as expressions that depend on the values of their variables, we can think of them as terms that depend \emph{continuously} on those variables. Even better, we can think of types as abstract representations of spaces up to the topological notion of \emph{homotopy equivalence}. Awodey and Warren made this precise by showing that dependent type theory can be interpreted in any \emph{model category} with some additional structure. Voevodsky interpreted it in the category of \emph{simplicial sets}, a structure that is fundamental to algebraic topology. In the homotopy-theoretic interpretation, elements of an identity type $a =_\alpha b$ represent \emph{paths} from $a$ to $b$, that is, continuous maps of the unit interval into $\alpha$ that map one endpoint to $a$ and the other to $b$. The elimination rule for identity types then corresponds to a method of proof in algebraic topology that involves contracting paths down to a constant path. In type theory, given $p, q : a =_\alpha b$, one can ask whether there is an element of $p =_{a =_\alpha b} q$. With proof irrelevance or axiom K, the answer is trivially yes, but in the homotopy-theoretic interpretation, it amounts to the interesting question as to whether there is a continuous deformation between the paths $p$ and $q$. Whereas proof irrelevance trivializes questions about elements of the identity types, homotopy type theory makes them a central focus. Given $\alpha, \beta : \ty{Type}$, one can formally define a type $\alpha \sim \beta$ of \emph{equivalences} between types, corresponding to the notion of \emph{homotopy equivalence} in the interpretation just described. From the axioms for equality, it is easy to construct an expression of type $\alpha = \beta \to \alpha \sim \beta$. Voevodsky's \emph{univalence axiom} asserts that this map is an equivalence, so, in particular, there is a map of type $\alpha \sim \beta \to \alpha = \beta$ going in the opposite direction. Voevodsky showed that it is consistent to add this principle to predicative type theory. Informally, this can be read as the statement that isomorphic types are equal, allowing us to use the laws of the equality to substitute one structure for another freely once we have constructed a bijection between them. The univalence axiom supports the informal mathematical practice of treating isomorphic structures as being the same; its consistency hinges on the fact that the things we can say about structures in the language of dependent type theory respect isomorphism. Read computationally, the univalence axiom says that once we have a translation between two data types, we may exchange them freely in a program. When it was initially presented, the univalence axiom did not have a computational interpretation. A good deal of work in recent years has done toward developing foundations for homotopy type theory with better computational properties. In particular, versions of \emph{cubical type theory} incorporate the dependence of terms and types on special \emph{interval variables}. In such systems, the elimination rule for identity types and the univalence principle are derivable from more fundamental syntactic rules. At present, there are a number of prototype systems based on cubical type theory, including the Arend proof assistant \cite{arend} and a cubical version of Agda \cite{DBLP:journals/pacmpl/VezzosiM019}. Such systems are not sufficiently well settled to give a definitive presentation now, but the underlying ideas offer promising new directions for interactive theorem proving. \section{Bibliographical Notes} Most of the information in this chapter can be found in numerous textbooks and other expository sources. The suggestions that follow are only meant to offer starting points for further reading. For a broad history of logic, see Kneale and Kneale \cite{MR0144812}. For a history of logic from around the turn of the twentieth century, see Van Heijenoort \cite{MR0209111} or Mancosu, Zach, and Badesa \cite{MR2895611}. For important source documents in the foundations of mathematics, see Ewald \cite{ewald:96}. For the history of constructive mathematics, see Troelstra and Van Dalen \cite{MR966421:modified} or Beeson \cite{MR786465}. For a history of interactive theorem proving, see Harrison, Urban, and Wiedijk \cite{DBLP:series/hhl/HarrisonUW14}. Most of the general background in logic discussed here is presented in greater detail in Avigad \cite{avigad:nd}. Countless textbooks cover the basics of first-order logic. The \emph{Handbook of Mathematical Logic} \cite{MR457132:modified} is a general reference, and the \emph{Handbook of Proof Theory} \cite{MR1640324} and Troelstra and Schwichtenberg \cite{MR1776976} offer proof-theoretic perspectives. For classical, model-theoretic semantics, see Chang and Keisler \cite{MR1059055}, Hodges \cite{MR1221741}, or Marker \cite{MR1924282}. For algebraic and category-theoretic approaches to semantics, including the semantics of higher-order logic, see Troelstra and Van Dalen \cite{MR966421:modified}, Lambek and Scott \cite{MR856915}, or Mac Lane and Moerdijk \cite{MR1300636}. Harrison \cite{DBLP:books/daglib/0022394} provides decision procedures for all the decidable theories enumerated in Section~\ref{subsection:lf:decidability:and:incompleteness}. Smith \cite{MR3059012} is an introduction to theories of arithmetic and the incompleteness theorems. For more information on the simply typed lambda calculus and related topics, see Hindley and Seldin \cite{MR2435558}, Barendregt, Dekkers, and Statman \cite{MR3114769}, Girard \cite{MR1003608}, or S{\o}rensen and Urzyczyn \cite{sorensen:urzyczyn:06}. The last two offer introductions to the propositions-as-types interpretation, the history of which is surveyed by Wadler \cite{DBLP:journals/cacm/Wadler15}. Good introductions to set theory include Devlin \cite{MR1237397}, Enderton \cite{MR0439636}, and Kunen \cite{MR2905394}. Grabowski, Kornilowicz, and Naumowicz \cite{DBLP:journals/jfrea/GrabowskiKN10} describe its implementation in Mizar. Higher-order logic is treated in Andrews \cite{MR1932484}, Takeuti \cite{MR882549}, or Lambek and Scott \cite{MR856915}, and it is informative to see how it is implemented in Isabelle \cite{DBLP:books/sp/NipkowPW02}, HOL4 \cite{HOL4}, and HOL Light \cite{hol:light:tutorial}. For introductions to dependent type theory, see Martin-L\"{o}f \cite{MR769301}, Nordstr\"{o}m, Petersson, and Smith \cite{MR1243882}, or Nederpelt and Geuvers \cite{MR3445957}. Once again, it is informative to see how the theory is put into practice in Coq \cite{DBLP:series/txtcs/BertotC04}, Agda \cite{DBLP:conf/afp/Norell08}, Nuprl \cite{DBLP:books/daglib/0068834}, PVS \cite{pvs}, and Lean \cite{theorem:proving:in:lean}. The \emph{Homotopy Type Theory} book \cite{DBLP:books/daglib/0046165} describes early systems of homotopy type theory, and its appendices provide a clear presentation of the rules of predicative type theory. \newcommand{\acks}[1]{\bigskip \noindent \emph{Acknowledgements.} #1} \acks{I am grateful to Guillaume Dubach, Randy Pollack, and Pedro S\'anchez Terraf for comments and corrections.} \bibliographystyle{plain}
{'timestamp': '2021-09-01T02:05:50', 'yymm': '2009', 'arxiv_id': '2009.09541', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09541'}
arxiv
\section{Introduction} With the rapid development of earth observation technology, earth remote sensing has entered the era of multi-platform, multi-sensor, and multi-angle observation. The demand of acquiring remote sensing data with high spatial resolution and high spectral resolution has further boomed. However, because the optical remote sensing system is limited by the optical diffraction limit, modulation transfer function, signal-to-noise ratio and so on, it is quite arduous to obtain satellite remote sensing images with both high spatial and high spectral properties. In order to alleviate this problem, many optical earth observation satellites carry two kinds of optical sensors to obtain panchromatic (PAN) images and multispectral (MS) images, through which relevant experts can fuse the different but complementary characteristics. The Pan-sharpening method is a significant branch of remote sensing image fusion. Its essence is to fuse multispectral images (MS) with low spatial information and high spectral quality and panchromatic images (PAN) with high spatial quality and low spectral information ,so as to achieve multi-spectral images with both high spatial resolution and high spectral resolution. So far, researchers have proposed many methods for fusion of panchromatic and multispectral images. Traditional panchromatic and multispectral algorithms can be roughly classified into two categories: component substitution (CS) methods and am\'elioration de la r\'esolution spatiale par injection de structures(ARSIS) concept methods. When the component substitution method is used for image fusion, the multi-spectral image is projected into a new feature space. Then, the intensity component is obtained and the panchromatic image is used to replace the intensity component, which improves the spatial resolution of the multi-spectral image. Component substitution method generally consists of up-sampling, forward transformation, intensity matching, component substitution and inverse transformation \citep{p01}. Generally, the component substitution method is easy to implement with high algorithm efficiency and the fusion result can reach a higher spatial resolution. However, for the low-frequency information of the image keeping changing during the fusion process, it will inevitably cause spectral distortion \citep{p02}. Representative algorithms of CS methods include PCA (principal component analysis) method \citep{p03,p04} and IHS (intensity, hue, saturation)methods \citep{p05,p06}. ARSIS can overcome the problem of spectral distortion, but it causes some spatial degradation. ARSIS method mainly extracts the spatial information of the panchromatic image through muti-scale methods or filters, and injects the extracted spatial information into the original muti-spectral image to improve the spatial resolution of the multi-spectral image. Comparing with the component substitution method, the performance of the muti-resolution analysis method is easily affected by the image registration result, and is prone to aliasing effects and edge artifacts. Representative algorithms of ARSIS methods include wavelet transform-based methods \citep{p07}, Laplacian Pyramidal decomposition methods \cite{p08}, and filtering-based methods \citep{p09,p10}. In recent years, the application of deep learning, especially the depth model based on convolutional neural network, to process panchromatic and multi-spectral image fusion has become a research hotspot.Masi et al.\citep{p11} proposed a pan-sharpening method based on the three-layer CNN architecture originally designed for image super resolution \citep{p12}.Zhong et al. \citep{p13} proposed a novel two-stage RSIF algorithm. In the first stage, the algorithm also uses similar methods \citep{p12} to improve the spatial resolution of LMS images. Liu et al. \citep{p14} proposed a dual-stream fusion network (TFNet) to solve the problem of generic sharpening. With the successful application of traditional deep learning models in fields such as image segmentation, classification and fusion, many scholars are gradually introducing the concept of Bayesian learning into deep learning. On the other hand, Bayesian deep learning can be used to explore the uncertainty of the model and assist the model to make decisions. Inspired by this, we propose a Bayesian Generative Adversarial Network based on Preconditioned Stochastic Gradient Langevin Dynamics (PGSLD-BGAN) to improve the pan-sharpening performance of remote sensing images. Similar to most pan-sharpening using an encoder structure, the generative network of PGSLD-BGAN serves as a fusion network that encodes the features of PAN and MS and then decodes the fused features to implement image fusion. The image results generated by the generative network are input to the discriminator network as fake data, while the corresponding reference images (high-resolutin MS images) are co-trained as real data. To sum up, our contribution can be concluded as the following three aspects: 1. We propose a Generative Network Adversarial structure to perform the pan-sharpening task. The proposed model can conduct the image reconstruction better by discriminating the network as compared to the common encoder structure. 2. We propose a PSGLD approach for Bayesian learning on GAN, which leverages a RMSPROP optimizer and train the model more stably than SGHMC methods to avoid the vanishing gradient problem. 3. To our knowledge, our work is the first to employ the Bayesian deep learning methodology to select better generator parameters for pan-sharpening by sampling the model parameter posterior. The proposed model has an excellent description of latent variable space of the model than traditional deep generative models. \section{Related works} This section briefly introduces some related works, including remote sensing image fusion technology based on deep learning and the development of Bayesian neural network. \subsection{Deep learning methods for image fusion} In recent years, deep learning has been successfully applied to remote sensing image fusion due to its strong ability to extract image features. Masi et al. \citep{p11} first tried to apply the SRCNN framework \citep{p12} to the pan-sharpening problem. In order to adapt to the input of the SRCNN framework, Masi et al. superimposed the up-sampled MS and PAN to form a five-band image. Zhong et al. \citep{p13} also used SRCNN for remote sensing image fusion. The difference is that they divide pan-sharping into two steps. The first step uses SRCNN to enhance the resolution of MS, and the second step applies GS transformation to complete pan-sharping. In order to avoid network degradation caused by the increase in the number of network layers, researchers have also explored the use of residual network to improve the performance of remote sensing image fusion. For example, Rao et al. \citep{p15} proposed a residual CNN model to conduct pan-sharpening. Comparing with the traditional CNN model, this method achieves fast convergence and high pan-sharpening quality. Yang et al. \citep{p16} proposed a deep network structure called PanNet, which can incorporate knowledge of a specific field. In particular, this approach can learn in the high-pass filter domain instead of the image domain to preserve spatial information. Liu et al. \citep{p14} proposed a two-stream fusion network (TFNet) to solve the pan-sharpening problem. This method employs two networks to extract features from PAN images and MS images respectively, and then integrates them together. Finally, the desired high spatial resolution MS image is achieved from the fused features through the image reconstruction network. \subsection{Bayesian neural networks} From the perspective of probability theory, the existing neural network can be interpreted as point estimation, and the use of point estimation to determine the network weight of the classification learning task cannot measure uncertainty. Hinton et al.\citep{p17} are the first to propose combining the scalability, flexibility and predictive performance of neural networks with Bayesian uncertainty modeling. Neal \citep{p18} showed that under certain assumptions, as the width of the shallow BNN increases, its limit distribution can be regarded as a Gaussian process. In recent years, as the popularity of deep learning has risen, a variety of mathematical methods have emerged to implement Bayesian deep learning. For example, Chen et al. \citep{p19} proposed a Hamiltonian Monte Carlo method based on stochastic gradient to implement Bayesian sampling algorithm. In order to improve the natural implementation of stochastic approximation, they introduced the second-order Langevin dynamics. Blundell \citep{p20} introduced a new network propagation method Bayes By Backprop to realize Bayesian neural network. Gal \citep{p21} et al. proposed a new theoretical framework, using drop-out in deep neural networks as a Bayesian inference method, providing a simple and easy to implement uncertainty modeling technique. Maddox et al. \citep{p22} proposed a simple and scalable approach called SWA-Gaussian based on stochastic weight averaging to explore the uncertain representation and calibration in Bayesian deep learning. \section{PSGLD-BGAN} Before introducing PSGLD-BGAN, we briefly review the related content of Generative Adversarial Network (GAN) and a general framework of Bayesian GAN. \subsection{Generative Adversarial Network} GAN \citep{p23} is a generative model, which can generate real data by implicitly modeling the distribution of high-dimensional data. Inspired by the idea of game theory, GAN trains a pair of competing networks at the same time through a mini-max game process. To further illustrate, A generator G and a discriminator D compete with each other to achieve Nash equilibrium. The goal of the generator is to capture the potential distribution in the actual data and generate artificial data samples. The purpose of the discriminator D is to distinguish the generated fake samples and real data samples. In the training process, the quality of the generated samples and the discriminative ability of the discriminator have been interactively improved. GAN conducts sampling from the real data distribution $p_{data}\left( x \right) $, and samples $z$ from the prior distribution $p_z\left( z \right) $. The input of $G$ is a random vector $z$, the generated data is recorded as $G\left( z \right)$, and its distribution is $p_g\left( z \right) $. The purpose of GAN is to make the distribution of $p_g\left( z \right) $ and the real data sample $p_{data}\left( x \right)$ similar. The input of $D$ can be real data $x$ or generated data $G\left( z \right)$. The output result of $D$ is scaled to [0,1]. When the input is real data $x$, the output value $D\left( x \right)$ will approach 1, and when the input is generated data $G\left( z \right)$, the output probability value $D\left( G\left( z \right) \right) $ will approach 0. Eq. (\ref{e1}) describes the objective function of GAN. \begin{equation} \label{e1} \underset{G}{\min}\underset{D}{\max}L\left( G,D \right) =E_{x\sim p_{data}\left( x \right)}\left[ \log D\left( x \right) \right] +E_{z\sim p_z\left( x \right)}\left[ \log \left( 1-D\left( G\left( z \right) \right) \right) \right] \end{equation} \subsection{Bayesian GAN} Saatci et al.(23) introduced the concept of Bayesian GAN for the first time, and utilized Stochastic Gradient HMC (SGLD) to perform posterior sampling to obtain the marginal distribution of GAN parameters. The given hyperparameters $\alpha _d$ and $\alpha _g$ are used to control the discriminator parameter $\theta _d$ and the generator parameter $\theta _g$ respectively. In other words, we set $p\left(\theta _d|\alpha _d \right)$ and $p\left(\theta _g|\alpha _g\right)$ as the prior probability of the discriminator parameter and the generator parameter. Bayesian GAN specially designs the likelihood to maximize the possibility of conditional distribution and equivalently optimize the corresponding goal of GAN . Instead of the traditional GAN based on the maximum likelihood estimation of point quality, it marginalizes the distribution of the generator (multimodal itself) to better explore the distribution of multimodal data. Eq. (\ref{e2}) and Eq. (\ref{e3}) show the joint distribution modeling process of discriminator and generator. \begin{equation} \label{e2} p\left( \theta _g|\theta _d \right) \propto \exp \left\{ -L_g\left( \theta _g;\theta _d \right) \right\} p\left( \theta _g|\alpha _g \right) \end{equation} \begin{equation} \label{e3} p\left( \theta _d|\theta _g \right) \propto \exp \left\{ -L_g\left( \theta _d;\theta _g \right) \right\} p\left( \theta _d|\alpha _d \right) \end{equation} Literature \citep{p24} also designed a general framework for Bayesian Gan to update parameters using Monte Carlo sampling. The specific steps are shown in Eq. (\ref{e4}). \begin{equation} \label{e4} \left\{ \theta _{g,k}^{\left( t+1 \right)} \right\} _{k=1}^{K}\sim p\left( \theta _d|\left\{ \theta _{d,k}^{\left( t \right)} \right\} _{k=1}^{K} \right) =\left( \prod_k{p\left( \theta _g|\theta _{d,k}^{\left( t \right)} \right)} \right) ^{\frac{1}{K}}=\exp \left\{ -\frac{1}{K}\sum_k{L_g\left( \theta _g;\theta _{d,k} \right)} \right\} p\left( \theta _g|\alpha _g \right) \end{equation} \begin{equation} \label{e5} \left\{ \theta _{d,k}^{\left( t+1 \right)} \right\} _{k=1}^{K}\sim p\left( \theta _g|\left\{ \theta _{d,k}^{\left( t \right)} \right\} _{k=1}^{K} \right) =\left( \prod_k{p\left( \theta _g|\theta _{g,k}^{\left( t \right)} \right)} \right) ^{\frac{1}{K}}=\exp \left\{ -\frac{1}{K}\sum_k{L_d\left( \theta _d;\theta _{g,k} \right)} \right\} p\left( \theta _d|\alpha _d \right) \end{equation} \subsection{Bayesian inference with PSGLD} Unlike the SGHMC approach adopted in comparison to the literature \citep{p24}, we propose a Bayesian GAN based on Preconditioned Stochastic Gradient Langevin Dynamics\citep{p25}. Stochastic Gradient Langevin Dynamics\citep{p26} naturally incorporates Stochastic gradient algorithms and Langevin dynamics. What's more, SGLD enables us to capture uncertainty in a Bayesian learning manner while applying it efficiently to large datasets. This approach implements Bayesian learning on neural networks by adding appropriate noise to random gradients in an annealing stepwise manner. \begin{equation} \label{e6} \Delta \theta _t=\frac{\epsilon _t}{2}\left( \nabla \log p\left( \theta _t \right) +\frac{N}{n}\sum_{i=1}^n{\nabla \log p\left( x_{ti}|\theta _t \right)} \right) +\eta _t \end{equation} where $\frac{\epsilon _t}{2}$ represents a sequence of steps and satisfies the properties $\sum_{t=1}^{\infty}{\epsilon_{t}=\infty}$ , $\sum_{t=1}^{\infty}{\epsilon _{t}^{2}}=\infty$, and $\eta_{t}<\infty$. $\left(0,\epsilon _{t} \right)$, $\mathbf{X}^t=\left\{ \boldsymbol{x}_{t1},...,\boldsymbol{x}_{tn} \right\} $ denotes the set of subsets divided from the full dataset, corresponding to the batches during the training of the neural network. In order to accommodate rapid changes in curvature, Li et al. \citep{p25} used a user-chosen preconditioning matrix $G_\theta$ based on the SGLD.Considering the family of probability distributions $p\left( X|\theta\right)$ from a Riemannian manifold perspective, they take the non-Euclidean geometry through this perspective to direct the sampling method. Then, Eq. (\ref{e6}) can then be rewritten as \label{e7}. \begin{equation} \label{e7} \Delta \theta _t=\frac{\epsilon _t}{2}\left[ G\left( \theta _t \right) \left( \nabla \log p\left( \theta _t \right) +\frac{N}{n}\sum_{i=1}^n{\nabla \log p\left( x_{ti}|\theta _t \right)} \right) +\Gamma \left( \theta _t \right) \right] +G^{\frac{1}{2}}\left( \theta _t \right) \eta _t \end{equation} where $\Gamma \left( \mathbf{\theta }_t \right) =\sum_j{\frac{\partial G_j\left( \boldsymbol{\theta } \right)}{\partial \theta _j}}$ describes the change pattern of the preconditioning matrix $G\left( \theta\right)$. The preconditioner strategy in equation d is implemented by the stochastic optimizer RMSprop. this preconditioner is sequentially updated by the current gradient information, which is expressed as follows. \begin{equation} \label{e8} G\left( \theta _{t+1} \right) =\text{diag} \left( 1 \oslash \left( \lambda +\sqrt{V\left( \theta _{t+1} \right)} \right) \right) \end{equation} \begin{equation} \label{e9} V\left( \theta _{t+1} \right) =\alpha V\left( \theta _t \right) +\left( 1-\alpha \right) \bar{g}\left( \theta _t;\mathbf{X} \right) \odot \bar{g}\left( \theta _t;\mathbf{X} \right) \end{equation} where $\bar{g}\left( \boldsymbol{\theta }_t;\mathbf{X}^t \right)$ represents the mean of the gradient of a mini-batch $D^t$, which can be used for simplification into $\frac{1}{n} \sum\limits_{i=1}^n{\nabla _{\theta}\log p\left( \boldsymbol{x}_{ti}|\boldsymbol{ \theta }_t \right)}$. The symbols $\odot$ and $\oslash$ represent elment-wise matrix multiplication and division, respectively. Therefore, we can give a general PSGLD-BGAN training framework, denoted as Algorithm 1. Algorithm 1 Preconditioned SGLD Bayesian GAN. \begin{algorithm} \caption{$ \textbf{:}$ SGLD Bayesian GAN} \label{alg1} \hspace*{0.02in}{\bf Input:} $\left\{ \epsilon _t \right\} _{t=1:T},\lambda ,\alpha$\\ \hspace*{0.02in}{\bf Output:} $\left\{ \theta _{d,t} \right\} _{t=1:T},\left\{\theta _{g,t} \right\} _{t=1:T}$\\ \hspace*{0.02in}{\bf Initialize:} $\mathbf{V}_0\gets 0,random\,\,\theta _{g,1},\theta _{d,1}$\\ \begin{algorithmic}[1] \For{$\,\text{epoch\,\,}t\gets 1:T$} \State $\text{Sample\,\,a\,\,}\min\text{ibatch\,\,of\,\,size\,\,n,\,\,}\mathbf{X}^t=\left\{ \boldsymbol{x}_{t1},...,\boldsymbol{x}_{tn} \right\} $. \State $\text{Sample\,\,a\,\,}\min\text{ibatch\,\,of\,\,}n\,\,\text{noise\,\,samples}\left\{ \boldsymbol{z}^{\left( 1 \right)},...,\boldsymbol{z}^{\left( n \right)} \right\} \,\,from\,\,noise\,\,prior\,\,p\left( z \right)$. \State $\text{Update\,\,}p\left( \theta _g|\theta _d \right) \,\,\text{through\,\,preconditioned\,\,SGLD\,\,RMSprop:}$ \State $Estimate\,\,gradient\,\,\bar{g}\left( \theta _{g,t};X^t \right) =\frac{1}{n}\sum\limits_n^1{\nabla \log p\left( x_{ti};\theta _{gt}|z^{\left( i \right)},\theta _{dt} \right)}$ \State $V\left( \theta _{g,t} \right) \gets \alpha V\left( \theta _{g,t-1} \right) +\left( 1-\alpha \right) \bar{g}\left( \theta _{g,t};\mathbf{X}^t \right) \odot \bar{g}\left( \theta _{g,t};\mathbf{X}^t \right) $ \State $G\left( \theta _{g,t} \right) \gets \text{diag}\left( 1\oslash\left( \lambda +\sqrt{V\left( \theta _t \right)} \right) \right) $ \State $ \theta _{g,t+1}\gets \theta _{g,t}+\frac{\epsilon _t}{2}\left[ G\left( \theta _{g,t} \right) \left( \nabla \log p\left( \theta _t \right) +N\bar{g}\left( \theta _{g,t} \right) \right) +\Gamma \left( \theta _{g,t} \right) \right] +G^{\frac{1}{2}}\left( \theta _{g,t} \right) \eta _t$ \State $\text{Sample\,\,a\,\,}\min\text{ibatch\,\,of\,\,}n\,\,\text{noise\,\,samples}\left\{ \boldsymbol{z}^{\left( 1 \right)},...,\boldsymbol{z}^{\left( n \right)} \right\} \,\,from\,\,noise\,\,prior\,\,p\left( z \right)$. \State $\text{Update\,\,}p\left( \theta _d|\theta _g \right) \,\,\text{through\,\,preconditioned\,\,SGLD\,\,RMSprop:}$ \State $Estimate\,\,gradient\,\,\bar{g}\left( \theta _{d,t};X^t \right) =\frac{1}{n}\sum\limits_n^1{\nabla \log p\left( x_{ti};\theta _{dt}|z^{\left( i \right)},\theta _{gt} \right)}$ \State $V\left( \theta _{d,t} \right) \gets \alpha V\left( \theta _{d,t-1} \right) +\left( 1-\alpha \right) \bar{g}\left( \theta _{d,t};\mathbf{X}^t \right) \odot \bar{g}\left( \theta _{d,t};\mathbf{X}^t \right) $ \State $G\left( \theta _{d,t} \right) \gets \text{diag}\left( 1\oslash\left( \lambda +\sqrt{V\left( \theta _{d,t} \right)} \right) \right)$ \State $\Delta \theta _{d,t+1}\gets \theta _{d,t}+\frac{\epsilon _t}{2}\left[ G\left( \theta _{d,t} \right) \left( \nabla \log p\left( \theta _t \right) +N\bar{g}\left( \theta _{d,t} \right) \right) +\Gamma \left( \theta _{d,t} \right) \right] +G^{\frac{1}{2}}\left( \theta _{d,t} \right) \eta _t$ \EndFor \end{algorithmic} \end{algorithm} \section{Image fusion task through proposed PSGLD-BGAN} In this section, we will describe how to perform remote sensing image fusion tasks using proposed PSGLD-BGAN. The network design and the loss function are described in detail. \subsection{Motivation and purpose} For multi-source remote sensing images, PAN images contain high-resolution spatial information, and MS images contain the multispectral features of the image. At present, deep learning models for remote sensing image fusion has become the mainstream method. Unlike traditional methods, which tend to cause problems such as spectral distortion and information loss, deep learning models can perform feature extraction while retaining more feature information, so high-quality fusion images can be obtained. However, traditional deep learning methods use point estimation methods to form a fusion image generator, which lacks exploration of the potential performance capabilities of the generator. For this reason, we employ PGSLD to perform Bayesian learning on GAN and apply PGSLD-BGAN to the field of pan-sharping. Figure. \ref{Fig1} describes the concept of the posterior distribution of Bayesian learning on pan-sharping. Each $\theta_g$ on the abscissa corresponds to the generator parameter hypothesis. We show there examples generated by three parameter settings, where $\theta_g$ corresponds to the image fusion result output by traditional deep learning using point estimation. In contrast, the generator that introduces Bayesian learning observes a more comprehensive distribution sampling of the parameters. This distribution sampling can help us choose better generator parameters for image fusion. To illustrate, compared to the other two results, the second image fusion result in Figure. 1 reduces the image noise in the marked area. \begin{figure} \centering \includegraphics[width=10cm] {Figure1.png} \caption{\label{1} Representation of posterior over the generator parameter space} \label{Fig1} \end{figure} \subsection{Network design} In this subsection, we describe the architectural design of the PSGLD-BGAN. Figure. \ref{Fig2} describes in detail the design of the two-stream generative network of the PSGLD-BGAN, including feature extraction, feature fusion, and image reconstruction. For the discriminator network, we use a Markovian discriminator \citep{p27}, which is commonly used in the field of image generation. When using the worldview dataset as an input, Table \ref{tab1} and Table \ref{tab2} show the network design parameters for the generative and adversary networks. \begin{figure} \centering \includegraphics[width=15cm] {Figure2.png} \caption{\label{2} Architecture of proposed generator network} \label{Fig2} \end{figure} \begin{table*}[!htbp] \caption{\label{tab1} Parameters of proposed generator network} \begin{tabular}{@{}ccccc@{}} \toprule Module & & Layer & Kernel/Stride & Output \\ \midrule Input & PAN & & & $400\times 400\times 4$ \\ & MS & & & $100\times 100\times 4$ \\ & Reference & & & $400\times 400\times 4$ \\ Feature Extraction & PAN & Conv1\_P & $3\times 3\times 32/1$ & $400\times 400\times 32$ \\ & & Conv2\_P & $3\times 3\times 32/1$ & $400\times 400\times 32$ \\ & & Conv3\_P & $3\times 3\times 32/1$ & $400\times 400\times 32$ \\ & & Down\_Conv1 & $2\times 2\times 64/2$ & $200\times 200\times 64$ \\ & MS & Conv1\_M & $3\times 3\times 32/1$ & $100\times 100\times 32$ \\ & & Conv2\_M & $3\times 3\times 32/1$ & $100\times 100\times 32$ \\ & & Conv3\_M & $3\times 3\times 32/1$ & $100\times 100\times 32$ \\ & & Up\_Conv1 & $2\times 2\times 64/2$ & $200\times 200\times 64$ \\ Feature Fusion & & Concat1 & & $200\times 200\times (64+64)$ \\ & & Conv4 & $3\times 3\times 128/1$ & $200\times 200\times 128$ \\ & & Conv5 & $3\times 3\times 128/1$ & \\ & & Conv6 & $3\times 3\times 128/1$ & \\ & & Down\_Conv2 & $2\times 2\times 256/2$ & $100\times 100\times 256$ \\ & & Concat2 & & $100\times 100\times (256+32)$ \\ & & Conv7 & $1\times 1\times 256/1$ & $100\times 100\times 256$ \\ & & Conv8 & $3\times 3\times 256/1$ & $100\times 100\times 256$ \\ & & Conv9 & $3\times 3\times 256/1$ & $100\times 100\times 256$ \\ Imgae Reconstruction & & Up\_Conv2 & $2\times 2\times 128/2$ & $200\times 200\times 128$ \\ & & Concat3 & & $200\times 200\times (128+128)$ \\ & & Conv10 & $1\times 1\times 256/1$ & $200\times 200\times 256$ \\ & & Conv11 & $3\times 3\times 256/1$ & $200\times 200\times 256$ \\ & & Conv12 & $3\times 3\times 256/1$ & $200\times 200\times 256$ \\ & & Up\_Conv3 & $2\times 2\times 128/2$ & $400\times 400\times 128$ \\ & & Concat4 & & $400\times 400\times (128+32)$ \\ & & Conv13 & $1\times 1\times 64/1$ & $400\times 400\times 64$ \\ & & Conv14 & $3\times 3\times 64/1$ & $400\times 400\times 64$ \\ & & Conv15 & $3\times 3\times 64/1$ & $400\times 400\times 64$ \\ & & Conv16 & $3\times 3\times 4/1$ & $400\times 400\times 4$ \\ & & & & $400\times 400\times 4$ \\ \bottomrule \end{tabular} \end{table*} \begin{table*}[!htbp] \caption{\label{tab2} Parameters of proposed generator network} \begin{tabular}{ccccc} \toprule Module & & layer & Kernel/Stride & Output \\ \midrule Input & Reference image (True data) & & & $400\times 400\times 4$ \\ & Fusion results (False data) & & & $400\times 400\times 4$ \\ & & Conv1 & $3\times 3\times 64/2$ & $200\times 200\times 64$ \\ & & Conv2 & $3\times 3\times 16/2$ & $100\times 100\times 16$ \\ & & Conv3 & $3\times 3\times 4/2$ & $50\times 50\times 4$ \\ & & Conv4 & $3\times 3\times 4/2$ & $25\times 25\times 4$ \\ & & Conv5 & $3\times 3\times 1/1$ & $25\times 25\times 1$ \\ & & Sigmoid & & $25\times 25\times 1$ \\ \bottomrule \end{tabular} \end{table*} \subsection{Loss function} In addition to the network architecture, the loss function is another important factor that affects the quality of the reconstructed image. Several works \citep{p28,p29} have shown that $l_11$ loss is a better choice when performing image recovery tasks. Hence in this work, we also leverage $l_11$ as part of the generator loss to train our network. Given a set of training samples $\left\{ X_P^i,X_M^i,Y^i \right\} $, where $X_P^i$ and $X_M^i$ are the PAN image and low resolution MS image, respectively, and $Y^i$ is the corresponding reference image. Then, $l_1$ loss is defined as: \begin{equation} \label{e10} l_1=\frac{1}{N}\sum_{i=1}^N{\left| F\left( X_{P}^{i},X_{M}^{i} \right) -Y^i \right|_1} \end{equation} Thus, the loss of PSGLD-BGAN generator and discriminator networks can be respectively described as follows: \begin{equation} \label{e11} l_g=E_{z\sim p_z\left( z \right)}\left[ \log \left( 1-D\left( G\left( z \right) \right) \right) \right] +l_1 \end{equation} \begin{equation} \label{e12} l_d=-E_{x\sim p_{data}\left( x \right)}\left[ \log D\left( x \right) \right] -E_{z\sim p_z\left( z \right)}\left[ \log \left( 1-D\left( G\left( z \right) \right) \right) \right] \end{equation} where N is the number of training samples in a mini-batch and $f$ represents the proposed image fusion model. \section{Experiments and analysis} \subsection{Data sets} We experiment on data sets from QuickBird and WorldView\footnote{http://www.digitalglobe.com/.} to validate the effectiveness of the proposed PSGLD-BGAN on the image-fusion (Pan-Sharping) mission. Table \ref{tab3} details the spatial resolution and wavelength range of the two remote sensing satellites. The data in this paper are part of the Roman city images of Italy taken by QuickBird and part of the Mexican city images taken by WorldView. The scale ratio of low spatial resolution MS image to high spatial resolution PAN image is 4:1. Therefore, Therefore, we downsampled the original single-band PAN and quad-band (Red, Green, Blue and Near infrared) MS images with one-quarter contraction and used the original MS images as reference images. To accommodate the training and testing of the network, for Worldview satellite data, we set the input PAN image (QuickBird data) size to $400\times 400\times 4$, the MS image size to $100\times 100\times 4$, and the reference image size $400\times 400\times 4$; for QucikBird satellite data input PAN image (WorldView data) size is $512\times 512\times 4$, MS image size is $128\times 4 \times 128 \times 4$ and reference image size $512 \times 512 \times 4$. \begin{table*}[!htbp] \caption{\label{tab3} Spectral and spatial characteristics of PAN and MS images from Qucikbird and WorldView} \begin{center} \begin{tabular}{lcccccc} \hline \multirow{2}{*}{Satellite} & \multicolumn{4}{c}{Spectral wavelength(nm)} & \multicolumn{2}{c}{Spatial resolution(m)} \\ \cline{2-7} & Red & Green & Blue & Nir & PAN & MS \\ \hline \multicolumn{1}{c}{Quickbird} & 630-690 & 520-600 & 450-520 & 760-890 & 0.6 & 2.4 \\ \hline \multicolumn{1}{c}{WordView-4} & 655-690 & 510-580 & 450-510 & 780-920 & 0.31 & 1.24 \\ \hline \end{tabular} \end{center} \end{table*} \subsection{Evaluation indexes} We employ five popular indexes to evaluate the performance of several classic methods and advanced ones. \textbf{CC} The Correlation Coeffient (CC) is the similarity between fusion image and reference image, which is mainly used to observe the spectral quality of fusion images through pan-sharping. The value range of CC is [0,1], and the spectral quality comes to be better with the value increasing. \begin{equation} \label{e13} CC=\frac{\sum_{i=1}^W{\sum_{j=1}^H{\left( X_{i,j}-m_X \right) \left( Y_{i,j}-m_Y \right)}}}{\sqrt{\sum_{i=1}^W{\sum_{j=1}^H{\left( X_{i,j}-m_X \right) ^2\sum_{i=1}^W{\sum_{j=1}^H{\left( Y_{i,j}-m_Y \right) ^2}}}}}} \end{equation} where X and Y represent the fusion image and the reference image respectively, m is the mean value of an image. \textbf{UIQI} \citep{p30}The universal image quality index (UIQI) is an index capturing the degree of structural distortion of the fusion image, which can be defined as: \begin{equation} \label{e14} UIQI=\frac{\sigma _{XY}}{\sigma _X\sigma _Y}\times \frac{2\mu _X\mu _Y}{\mu _X\mu _Y}\times \frac{2\sigma _X\sigma _Y}{\sigma _X+\sigma _Y} \end{equation} where $\sigma_ {XY}$ and $\mu_{XY}$ represent standard variance and mean of image X and image Y and the similar definition can be employed in $ \sigma_ {X}$ ,$ \sigma_ {Y}$, $ \mu_{X}$ and $ \mu_ {Y}$. \textbf{SAM} \citep{p31} The spectral angle mapper(SAM) can measure spectral distortions between fusion results through pan-sharpening and the corresponding reference images. It is defined as: \begin{equation} \label{e15} SAM\left( x_P,x_R \right) =\arccos \left( \frac{x_P\cdot x_R}{\lVert x_P \rVert \cdot \lVert x_R \rVert} \right) \end{equation} where $x_P$ and $x_R$ respectively represent the spectral vectors from fusion images and reference images. \textbf{ERGAS} \citep{p32} The erreur relative globale adimensionnelle de synth\`ese (ERGAS) measures the global dimensional synthesis error, which can be calculated as: \begin{equation} \label{e16} ERGAS=100\frac{h}{l}\sqrt{\frac{l}{K}\sum_{k=1}^K{\left( \frac{rmse_i}{m_i} \right)}} \end{equation} where $h$ and $l$ represent the spatial resolution of PAN and MS images, respectively; $rmse_i$ is the root mean square error between the $i$th band of the fusion image and reference image; $m_i$ is the mean value of the $i$th band of the MS image. $\boldsymbol{Q}_4$ \citep{p33} The quality-index $Q_4$ is the 4-band extension of Q index. $Q_4$ can be calculated as: \begin{equation} \label{e20} Q_4=\frac{4\left| \sigma _{z_1z_2} \right|\cdot \left| \mu _{z_1} \right|\cdot \left| \mu _{z_2} \right|}{\left( \sigma _{z_1}^{2}+\sigma _{z_2}^{2} \right) \left( \mu _{z_1}^{2}+\mu _{z_2}^{2} \right)} \end{equation} where $z_1$ and $z_2$ are two quaternions, which consist of spectral vectors of MS images, $\mu _{z_21}$ and $\mu _{z_2}$ are the mean value of $z_1$ and $z_2$, denotes the variances of z1 and z2, and $\sigma _{z_1z_2}$ represents the covariance between$z_1$ and $z_2$. \subsection{Implement environment} Through data augmentation, we obtain two final data sets, i.e., the QuickBird data set with 12,000 pairs (PAN, MS and reference image) and the WorldView data set with 10,000 pairs, respectively. To avoid random results, we randomly utilize 80\% of the data for training and the remainder for testing. The proposed model is implemented in PyTorch and run on a GTX 1080TI. The loss is minimized through the proposed optimizer based on PSGLD strategy with a learning rate 0.0001. The mini-batch is set to 16. During the training process, we acquire 50 posterior samples of the generator parameter. And the generator parameter with the highest CC index is taken as the final selected parameter. \subsection{Comparison with other models} In this subsection, we compare the proposed method with state of the art deep learning models such as MSDCNN \citep{p36}, PanNet \citep{p16} ,ResTFNet \citep{p14} and Pan-GAN \citep{p37}. Table \ref{tab4} and Table \ref{tab5} respectively show the quantitative evaluation of experiments on Quickbird and WorldView data sets. Figure \ref{Fig3} and Figure \ref{Fig4} illustrate examples of comparison methods from two data sets. PSGLD-BGAN* represents the proposed model without bayesian learning, sharing the same architecture and parameter. From Tables \ref{tab4} and \ref{tab5}, we can observe that the traditional deep learning version, PSGLD-BGAN*, is already capable of rivaling recent advanced models. Further, PSGLD-BGAN incorporates Bayesian learning for posteriori sampling, selects the final parameter in a simple way, and achieves the best performance on all evaluation metrics. \begin{figure} [!htbp] \centering \includegraphics[width=10cm] {Figure3.png} \caption{\label{3} Pansharpening results on the Quickbird images} \label{Fig3} \end{figure} \begin{table*}[!htbp] \caption{\label{tab4} Quantitative assessment on the Quickbird data sets} \begin{center} \begin{tabular}{cccccc} \toprule & CC$\uparrow $ & UIQI$\uparrow$ & SAM$\downarrow$ & ERGAS$\downarrow$ & Q4$\uparrow$ \\\midrule MSDCNN & 0.9352 & 0.9483 & 4.2387 & 5.5578 & 0.9403 \\ PanNet & 0.9472 & 0.9523 & 4.1345 & 5.2014 & 0.9499 \\ ResTFNet & 0.9828 & 0.9843 & 3.8775 & 4.1544 & 0.9822 \\ Pan-GAN & 0.9832 & 0.9827 & 3.9564 & 4.0313 & 0.9831 \\ PGSLD-BGAN* & 0.9821 & 0.9833 & 3.8211 & 4.0154 & 0.9817 \\ PSGLD-BGAN & 0.9899 & 0.9853 & 3.7078 & 3.7154 & 0.9895 \\\bottomrule \end{tabular} \end{center} \end{table*} \begin{figure} \centering \includegraphics[width=10cm] {Figure4.png} \caption{\label{4} Pansharpening results on the WordView images} \label{Fig4} \end{figure} \begin{table*}[!htbp] \caption{\label{tab5} Quantitative assessment on the WorldView data sets} \begin{center} \begin{tabular}{cccccc} \toprule & CC$\uparrow $ & UIQI$\uparrow$ & SAM$\downarrow$ & ERGAS$\downarrow$ & Q4$\uparrow$ \\\midrule MSDCNN & 0.9423 & 0.9311 & 4.4984 & 4.2457 & 0.9256 \\ PanNet & 0.9478 & 0.9422 & 4.0345 & 4.1476 & 0.9405 \\ ResTFNet & 0.9802 & 0.9821 & 3.6664 & 4.0954 & 0.9834 \\ Pan-GAN & 0.9811 & 0.9822 & 3.6743 & 3.8922 & 0.9846 \\ PGSLD-BGAN* & 0.9825 & 0.9817 & 3.7089 & 3.9841 & 0.9820 \\ PSGLD-BGAN & 0.9887 & 0.9836 & 3.6103 & 3.7548 & 0.9875 \\\bottomrule \end{tabular} \end{center} \end{table*} \section{Conclusion} In this paper, we propose a Bayesian Generative Adversarial Network based on Preconditioned Stochastic Gradient Langevin Dynamics for solving remote sensing pan-sharpening. Deep learning techniques, especially the GAN architecture, which severe as a powerful and flexible tool, have gradually became the dominant framework in the field of image generation. We design a generator network to extract the features of PAN and MS images and fuse them together naturally for pan-sharpening. Then, we distinguish the fusion images from the reference images through proposed discriminator network to enhance the image fusion performance. Different from traditional image fusion deep learning models, we use PSGLD strategy to sample the posterior parameter of the generator network, expand the parameter space to explore the generator network, and select the best generator parameter among them. In the future, we will develop a Bayesian deep generative framework that is more suitable for image fusion of people. \bibliographystyle{unsrt}
{'timestamp': '2020-09-22T02:18:17', 'yymm': '2009', 'arxiv_id': '2009.09465', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09465'}
arxiv
\section{Introduction} \IEEEPARstart{I}{n} a wireless communications system with a next-generation NodeB (gNB) and multiple user equipments (UEs), a pivotal issue to tackle is the scheduling of available time and frequency resources to the UEs in order to satisfy certain quality of service (QoS) requirements such as throughput, fairness, latency, and/or reliability. According to the specifications by the 3rd Generation Partnership Project (3GPP)~\cite{38214,38331}, there are two types of downlink frequency-domain resource allocation (FDRA): type 0 and type 1. In downlink FDRA of type 0, the resource block (RB) assignment information comprises a bitmap indicating the resource block groups (RBGs) that are allocated to the scheduled UE, where an RBG consists of a set of consecutive virtual RBs defined by higher layer parameters~\cite{38214}. In downlink FDRA of type 1, the RB assignment information signifies to a scheduled UE a set of contiguously allocated non-interleaved or interleaved virtual RBs within the active bandwidth part (BWP)~\cite{38214}. Two key discrepancies between type-0 and type-1 FDRA are (1) type 0 is on the RBG level while type 1 is on the RB level, and (2) the resources (RBGs or RBs) assigned to each UE can be non-contiguous for type 0, while they must be contiguous for type 1. A variety of scheduling methods for contiguous FDRA have been proposed previously~\cite{Wong11,Zhang13,Cicalo14,Maciel18,Arafat19,Tsiropoulou16}, predominantly for single-carrier frequency division multiple access in the Long-Term-Evolution-Advanced system. An optimal algorithm was presented in~\cite{Wong11}, which yielded the best performance but was quite intricate. To reduce the complexity, a greedy heuristic allocation was then proposed in~\cite{Wong11} which performed adjacent RB allocation expansion around a localized optimal RB for each UE. At each iteration, the UE and feasible RB combination arousing the largest increase in weighted capacity was selected. In~\cite{Zhang13}, a two-step FDRA scheme was proposed prioritizing the most demanding UEs in terms of their QoS requirements. The authors of~\cite{Cicalo14} proposed a sub-optimal algorithmic solution to address the problem of ergodic sum-rate maximization with the constraint of consecutive RB allocation, where the performance gap to optimal solution was limited to 10\%. The invention in~\cite{Maciel18} also contained two steps where the allocation leading to maximum throughput was first found without considering the contiguity constraint, which was then iteratively refined to reach an allocation satisfying contiguity. The algorithm presented in~\cite{Arafat19} was based on channel gain matrix and iterative RB cluster selection with highest channel gain. More prior art can be found in~\cite{Tsiropoulou16}. The existing strategies, however, mainly concentrate on throughput and do not take into account other QoS criteria such as delay and packet drop rate~\cite{Wong11,Zhang13,Cicalo14,Maciel18,Arafat19}, and/or involve high computational complexity when the number of UEs is large~\cite{Zhang13,Maciel18}. In this article, we put forth three scheduling algorithms with type-1 (i.e., contiguous) FDRA which are aligned with 3GPP standards for fifth-generation (5G) and beyond-5G (B5G) communications~\cite{38214,38331} and have relatively low computational complexity thus viable to deploy in practice. In the first proposed algorithm, FDRA and UE scheduling are jointly conducted to achieve near-optimal performance, whereas in the second and third proposed algorithms, UE selection is executed first, followed by RB allocation, whose major advantage is low complexity. Moreover, all of the proposed algorithms are flexible in terms of scheduling metric such as sum-rate, proportional fairness (PF)~\cite{Tse99} and modified largest weighted delay first (M-LWDF)~\cite{Andrews01}. System-level simulations are carried out to validate and compare the performance of the proposed algorithms, using several traffic types with diverse packet sizes, arrival rates, and QoS requirements. \vspace{-8pt} \section{System Model and Problem Formulation} In this work, we investigate a downlink cellular system comprising of one gNB and $K$ UEs indexed by the set $\mathcal{K}=\{0,...,K-1\}$, where the UEs' traffic types can be heterogenous with dissimilar QoS requirements. The transmission BWP $W$ is orthogonally divided into $B$ RBs indexed by the set $\mathcal{B}=\{0,...,B-1\}$. The payload for UE $k$ is denoted by $L_k$. There are two constraints in type-1 FDRA in 3GPP 5G and B5G specifications~\cite{38214,38331}: (1) exclusivity, meaning an RB can only be allocated to at most one UE; (2) contiguity, i.e., the RBs assigned to each UE must be contiguous. Fig.~\ref{fig:inputOutput} illustrates the input and output relation per slot in the UE and resource scheduling process with type-1 FDRA~\cite{38214,38331}. The input incorporates the UE set $\mathcal{K}$, RB set $\mathcal{B}$, payload and channel state information (CSI) per UE, where the CSI usually embodies rank indicator (RI), precoding matrix indicator (PMI), and channel quality indicator (CQI)~\cite{38214}. The output includes the selected UE set $\mathcal{K}^\star$, selected RB set $\mathcal{B}^\star$ implied by resource indication value (RIV) per selected UE, and RI, PMI, and modulation and coding scheme (MCS) per selected UE, where an RIV corresponds to a starting virtual RB and a length pertaining to contiguously allocated RBs~\cite{38214}. \begin{figure} \centering \includegraphics[width=\columnwidth]{Fig1.pdf} \caption{Input and output relation per slot in the UE and resource scheduling process for a multi-UE scenario with type-1 FDRA.} \label{fig:inputOutput} \end{figure} \vspace{- 12pt} In some of the proposed algorithms to be elaborated in Section III, the calculation of transport block size (TBS) [1] over a certain number of RBs is needed. If wideband (WB) CSI [1] is available, where WB denotes the entire active BWP, the TBS is directly computed using the WB CSI. If subband (SB) CSI is available (while RI is still WB) [1], where an SB is equivalent to an RBG herein, the TBS over all the selected RBs (or RBGs) is calculated via the procedure below: (1) Convert each SB CQI to SB MCS, (2) compute the effective MCS over all the selected RBs (or RBGs), and (3) calculate the TBS over all the selected RBs (or RBGs) using the effective MCS and WB RI. In this article, the effective MCS equals the median of the MCSs over all the selected RBs (or RBGs), but it can also be the average, maximum, or other quantities related to SB MCS. Further, to obtain WB CQI to be utilized in some of the proposed algorithms, the effective MCS is computed over the entire active BWP, which is then converted back to CQI. For UE $k$ on RB $b$, given the estimated channel $\mathbf{H}_{k,b}$ and precoding matrix codebook~\cite{38214}, the RI, PMI, and MCS can be obtained via Algorithms 1 and 2 in~\cite{Sun20}, after which $\mathrm{TBS}_{k,b}$ is calculated via the method mentioned above. The achievable rate of UE $k$ on RB $b$ in each slot is $r_{k,b}=\mathrm{TBS}_{k,b}$. Let $\mathcal{B}_k$ denote the set of RBs allocated to UE $k$, the achievable rate of UE $k$ is $r_k=\sum_{b \in\mathcal{B}_k}r_{k,b}$. The scheduling metric (e.g., sum-rate, PF, M-LWDF) can be flexible depending on the system requirement. Considering QoS requirement, we select M-LWDF as the scheduling metric as an example, which is expressed as~\cite{Andrews01} $\mu_{k,b}=-(\log\delta_k/\tau_k)d_kr_{k,b}/R_k$, where $\delta_k$, $\tau_k$, $d_k$, and $R_k$ denote the acceptable packet drop probability, delay threshold (the maximum allowable delay from packet generation to packet scheduling), head-of-line (HOL) delay, and historical average rate of UE $k$, respectively. The optimization problem is formulated as \begin{equation}\label{eq1} \begin{alignedat}{2} \text{(P1):}~ &\max_{\{\mathcal{B}_0,...,\mathcal{B}_{K-1}\}\subseteq\mathcal{A}}&&\sum_{k \in\mathcal{K}}\sum_{b \in\mathcal{B}_k}\mu_{k,b} \\ &\text{subject~to} & & \mathcal{B}_k\cap\mathcal{B}_{k^\prime}=\emptyset,\forall k\ne k^\prime, k,k^\prime\in\mathcal{K}, \\ & & &d_k\leq\tau_k, \forall k\in\mathcal{K} \end{alignedat} \end{equation} \noindent where $\mathcal{A}$ is the set of all possible RB allocations satisfying the contiguity constraint. (P1) is non-convex whose optimal solution requires exhaustive search with prohibitively high computational complexity. Therefore, in the next section, we propose three practical sub-optimal algorithms to tackle (P1). \vspace{- 9.9pt} \section{Scheduling Algorithms} \subsection{Proposed Three Scheduling Algorithms} \vspace{- 3pt} Since it is almost impossible to obtain the optimal solution to (P1) with reasonable computational complexity, we propose three sub-optimal algorithms to solve (P1). Inspired by the observation that $\sum_{k \in\mathcal{K}}\sum_{b \in\mathcal{B}_k}\mu_{k,b}$ in (\ref{eq1}) is likely to be maximized if the UEs who yield the largest $\sum_{b \in\mathcal{B}_k}\mu_{k,b}$ while consuming the minimum resources are scheduled first, we propose an algorithm named Joint Allocation with Dual Ends (JADE), whose procedures are detailed in Algorithm 1. Essentially, JADE jointly prioritizes the UE and RB(s) in each allocation step that produces the largest scheduling metric with the minimum number of RBs, where the RB selection is performed and compared between both ends of the active BWP to take advantage of frequency diversity. It is worth noting that a variant of JADE, where the RBs are allocated from only one end, rather than both ends, of the BWP, can be applied as well. As the variant is likely to yield inferior performance to JADE due to less frequency diversity, its performance is not shown herein. \begin{algorithm} \caption{Joint Allocation with Dual Ends (JADE)} \begin{algorithmic}[1 \Require {Initialize $\mathcal{K}^\star=\emptyset$, $\mathcal{B}^\star=\emptyset$.} \While{$\mathcal{K}\neq\emptyset$ and $\mathcal{B}\neq\emptyset$} \For{$\forall k\in\mathcal{K}$} \State \multiline{% Calculate the number of RBs needed, $n_{k,\text{start}}$, to transmit $L_k$ starting from the first remaining RB in $\mathcal{B}$ and going forward, until $r_{k,\text{start}}\geq L_k$ or $\mathcal{B}=\emptyset$. Denote the selected RB set as $\mathcal{B}_{k,\text{start}}$.} \State \multiline{% Calculate the number of RBs needed, $n_{k,\text{end}}$, to transmit $L_k$ starting from the last remaining RB in $\mathcal{B}$ and going backward, until $r_{k,\text{end}}\geq L_k$ or $\mathcal{B}=\emptyset$. Denote the selected RB set as $\mathcal{B}_{k,\text{end}}$.} \State \multiline{% If $n_{k,\text{start}}\leq n_{k,\text{end}}$, store $\mathcal{B}_{k,\text{start}}$ and $r_{k,\text{start}}$ as $\mathcal{B}_k$ and $r_k$, respectively; otherwise store $\mathcal{B}_{k,\text{end}}$ and $r_{k,\text{end}}$ as $\mathcal{B}_k$ and $r_k$, respectively.} \State \multiline{% Calculate $\sum_{b \in\mathcal{B}_k}\mu_{k,b} $.} \EndFor \State \multiline{% $k^\star=\underset{k}{\mathrm{argmax}}\sum_{b \in\mathcal{B}_k}\mu_{k,b}$.} \State \multiline{% Calculate $\text{MCS}_{k^\star}$, the final MCS for UE $k^\star$ over $\mathcal{B}_{k^\star}$.} \State \multiline{% $\mathcal{K}^\star\gets\mathcal{K}^\star\cup\{k^\star\}$, $\mathcal{B}^\star\gets\mathcal{B}^\star\cup\mathcal{B}_{k^\star}$.} \State \multiline{% $\mathcal{K}\gets\mathcal{K}\setminus\{k^\star\}$, $\mathcal{B}\gets\mathcal{B}\setminus\mathcal{B}_{k^\star}$.} \EndWhile \State \textbf{return} $\mathcal{K}^\star$, $\mathcal{B}^\star$, and $\text{MCS}_k,\forall k\in\mathcal{K}^\star$. \end{algorithmic} \end{algorithm} Note that in JADE, the number of TBS and scheduling metric calculation is proportional to $K^2$ due to the iteration for each remaining UE and RB. To further reduce the computational complexity, two lower-complexity algorithms are designed, i.e., Disjoint Allocation with Single End (DASE) and Disjoint Allocation with Two Ends (DATE). The main design principle of DASE and DATE is to guarantee the QoS for UEs with the most stringent delay and acceptable packet drop probability requirements. In both DASE and DATE, UE selection is done first based on their delay and acceptable packet drop probability requirements as well as the number of RBs needed, followed by RB selection. The only difference between DASE and DATE lies in that RB selection is conducted from only one end of the BWP in DASE, while both ends of the BWP are considered and compared for RB selection in DATE. Detailed steps for DASE and DATE are provided in Algorithm 2 and Algorithm 3, respectively. \vspace{- 5pt} \begin{algorithm} \caption{Disjoint Allocation with Single End (DASE)} \begin{algorithmic}[1 \Require {Initialize $\mathcal{K}^\star=\emptyset$, $\mathcal{B}^\star=\emptyset$.} \While{$\mathcal{K}\neq\emptyset$ and $\mathcal{B}\neq\emptyset$} \For{$\forall k\in\mathcal{K}$} \Comment{UE selection begins} \State \multiline{% $\Delta d_k=\tau_k-d_k$.} \State \multiline{% Calculate the number of RBs needed, $n_k$, to transmit $L_k$ based on WB CQI of UE $k$.} \EndFor \State \multiline{% $\mathcal{K}^\star_{\text{temp}}=\underset{k}{\mathrm{argmin}}\Delta d_k$.} \If{$|\mathcal{K}^\star_{\text{temp}}|=1$} \State \multiline{% $k^\star=\underset{k}{\mathrm{argmin}}~\Delta d_k$.} \Else \State \multiline{% $\mathcal{K}^\star_{\text{temp}}=\underset{k}{\mathrm{argmin}}~\delta_k$.} \If{$|\mathcal{K}^\star_{\text{temp}}|=1$} \State \multiline{% $k^\star=\underset{k}{\mathrm{argmin}}~\delta_k$.} \Else \State \multiline{% $\mathcal{K}^\star_{\text{temp}}=\underset{k}{\mathrm{argmin}}~n_k$.} \If{$|\mathcal{K}^\star_{\text{temp}}|=1$} \State \multiline{% $k^\star=\underset{k}{\mathrm{argmin}}~n_k$.} \Else \State \multiline{% Randomly select a UE $k^\star$.} \EndIf \EndIf \EndIf \Comment{UE selection ends and RB selection begins} \State \multiline{% Calculate the number of RBs needed, $n_{k^\star,\text{start}}$, to transmit $L_{k^\star}$ starting from the first remaining RB in $\mathcal{B}$ and going forward, until $r_{k^\star,\text{start}}\geq L_{k^\star}$ or $\mathcal{B}=\emptyset$. Denote the selected RB set as $\mathcal{B}_{k^\star}$, and allocate $\mathcal{B}_{k^\star}$ to UE $k^\star$.} \Comment{RB selection ends} \State \multiline{% Calculate $\text{MCS}_{k^\star}$, the final MCS for UE $k^\star$ over $\mathcal{B}_{k^\star}$.} \State \multiline{% $\mathcal{K}^\star\gets\mathcal{K}^\star\cup\{k^\star\}$, $\mathcal{B}^\star\gets\mathcal{B}^\star\cup\mathcal{B}_{k^\star}$.} \State \multiline{% $\mathcal{K}\gets\mathcal{K}\setminus\{k^\star\}$, $\mathcal{B}\gets\mathcal{B}\setminus\mathcal{B}_{k^\star}$.} \EndWhile \State \textbf{return} $\mathcal{K}^\star$, $\mathcal{B}^\star$, and $\text{MCS}_k,\forall k\in\mathcal{K}^\star$. \end{algorithmic} \end{algorithm} \begin{algorithm} \caption{Disjoint Allocation with Two Ends (DATE)} \begin{algorithmic}[1 \Require {Initialize $\mathcal{K}^\star=\emptyset$, $\mathcal{B}^\star=\emptyset$.} \While{$\mathcal{K}\neq\emptyset$ and $\mathcal{B}\neq\emptyset$} \State \multiline{% UE selection: Identical to Steps 2-21 in DASE.} \Comment{RB selection begins} \State \multiline{% Calculate the number of RBs needed, $n_{k^\star,\text{start}}$, to transmit $L_{k^\star}$ starting from the first remaining RB in $\mathcal{B}$ and going forward, until $r_{k^\star,\text{start}}\geq L_{k^\star}$ or $\mathcal{B}=\emptyset$. Denote the selected RB set as $\mathcal{B}_{k^\star,\text{start}}$.} \State \multiline{% Calculate the number of RBs needed, $n_{k^\star,\text{end}}$, to transmit $L_{k^\star}$ starting from the last remaining RB in $\mathcal{B}$ and going backward, until $r_{k^\star,\text{end}}\geq L_{k^\star}$ or $\mathcal{B}=\emptyset$. Denote the selected RB set as $\mathcal{B}_{k^\star,\text{end}}$.} \State \multiline{% If $n_{k^\star,\text{start}}\leq n_{k^\star,\text{end}}$, denote $\mathcal{B}_{k^\star,\text{start}}$ as $\mathcal{B}_{k^\star}$, otherwise denote $\mathcal{B}_{k^\star,\text{end}}$ as $\mathcal{B}_{k^\star}$. Allocate $\mathcal{B}_{k^\star}$ to UE $k^\star$.} \Comment{RB selection ends} \State \multiline{% Calculate $\text{MCS}_{k^\star}$, the final MCS for UE $k^\star$ over $\mathcal{B}_{k^\star}$.} \State \multiline{% $\mathcal{K}^\star\gets\mathcal{K}^\star\cup\{k^\star\}$, $\mathcal{B}^\star\gets\mathcal{B}^\star\cup\mathcal{B}_{k^\star}$.} \State \multiline{% $\mathcal{K}\gets\mathcal{K}\setminus\{k^\star\}$, $\mathcal{B}\gets\mathcal{B}\setminus\mathcal{B}_{k^\star}$.} \EndWhile \State \textbf{return} $\mathcal{K}^\star$, $\mathcal{B}^\star$, and $\text{MCS}_k,\forall k\in\mathcal{K}^\star$. \end{algorithmic} \end{algorithm} \subsection{Scheduling Algorithm with Type-0 FDRA} Ideally, the performance of the proposed algorithms should be compared with that of the optimal type-1 FDRA which, however, requires exhaustive search over UEs, the starting position of RBs per UE, and the number of RBs per UE, whose complexity is prohibitively high and hence almost impossible to realize. On the other hand, although also requiring exhaustive search, the optimal type-0 FDRA is possible to realize capitalizing on a different and smaller search space. Additionally, if the same frequency granularity is assumed for both type-0 and type-1 FDRA, the optimal type-0 allocation is expected to be superior to the optimal type 1, since discontinuous FDRA enjoys higher flexibility in terms of best UE and resource combination selection. To this end, we compare the performance of the proposed scheduling algorithms with one using the optimal type-0 FDRA which serves as a benchmark. In type-0 FDRA, the scheduling metric is first calculated per UE per RBG, then the UE and RBG combination corresponding to the largest scheduling metric is selected for scheduling and excluded from further selection afterwards in the current slot. Subsequently, the scheduling metric is recalculated per UE per RBG, followed by best UE and RBG combination selection and exclusion, so on and so forth, until there is no remaining UE or RBG. \vspace{- 10pt} \subsection{Complexity Analysis} Besides the RBG-level type-0 FDRA, we also compare the proposed algorithms with a representative sub-optimal contiguous FDRA algorithm in the industry published in~\cite{Wong11}, which is named Localized Expansion of Adjacent Positions (LEAP) herein, to evaluate the performance enhancement by the proposed algorithms over LEAP. The weighted capacity metric in LEAP is replaced by the scheduling metric for fair comparison. Assuming each UE needs $M$ RBs on average, and the number of RBs in an RBG is $M_\text{RB}$, the computational complexity of all the considered algorithms is provided in Table~\ref{tbl:complexity}. As expected, type-0 FDRA possesses the highest complexity due to exhaustive search over all UE and RBG combinations. In a typical example where $K=30, B=270,M=10$, and $M_\text{RB}=4$, the complexity of JADE is slightly lower than that of LEAP, both of which are approximately an order of magnitude lower than type-0 FDRA. DASE has the lowest complexity which is slightly lower than that of DATE, since these two algorithms exploit disjoint UE and RB selection. \begin{table}[!t] \renewcommand{\arraystretch}{1.1} \caption{Complexity Comparison} \label{tbl:complexity} \centering \begin{tabular}{|m{1.7cm}||m{0.75cm}|m{0.75cm}|m{0.75cm}|m{0.75cm}|m{1.1cm}|} \hline \multirow{2}{*}{Algorithm} & \multicolumn{4}{c|}{Type-1} & \multirow{2}{*}{Type-0}\\ \cline{2-5} & JADE & DASE & DATE & LEAP &\\ \hline \makecell{Number of \\TBS calculation} & $MK^2$ & $MK$ & $2MK$ & $MK$ & 0\\ \hline \makecell{Number of\\ scheduling \\metric\\calculation} & $\frac{MK^2}{2}$ & 0 & 0 & $\frac{BK^2}{3}$ & $\frac{[\frac{M}{M_\text{RB}}]^2K^3}{3}$\\ \hline \makecell{Number \\of RB amount \\calculation} & 0 & $K$ & $K$ & 0 & 0\\ \hline \makecell{Sum\\complexity} & $\frac{3MK^2}{2}$ & $MK$ & $2MK$ & $\frac{BK^2}{3}$ & $\frac{[\frac{M}{M_\text{RB}}]^2K^3}{3}$\\ \hline \makecell{Sum\\complexity for\\$K=30$, \\$B=270$,\\$M=10$, \\$M_\text{RB}=4$} & \makecell{$1e4$\\$\Downarrow$\\$\mathcal{O}(1e4)$} & \makecell{$3e2$\\$\Downarrow$\\$\mathcal{O}(1e2)$} & \makecell{$6e2$\\$\Downarrow$\\$\mathcal{O}(1e2)$} & \makecell{$8e4$\\$\Downarrow$\\$\mathcal{O}(1e4)$} & \makecell{$2e5$\\$\Downarrow$\\$\mathcal{O}(1e5)$} \\ \hline \end{tabular} \end{table} \vspace{- 9pt} \section{Simulation Results} System-level simulations are conducted to assess and compare the performance of the proposed three type-1 FDRA algorithms. Table~\ref{tbl:simSet} lists the simulation settings, where the traffic models comprise both eMBB (enhanced Mobile Broadband) and URLLC (Ultra-Reliable Low-Latency Communications)~\cite{Bennis18} (including arVr2, powerDist2, and ITS~\cite{38824}, where arVr2 denotes the second type of augmented reality/virtual reality, powerDist2 represents the second type of power distribution grid fault and outage management, and ITS stands for intelligent transportation system~\cite{38824}). The total number of UEs in our simulations vary from 10 to 50, and the ratios of eMBB, arVr2, powerDist2, and ITS UEs are about 1:1:1:1. Table~\ref{tbl:traffic} details the parameters for the traffic models studied in our simulations. We note that URLLC traffic can also be scheduled by puncturing the ongoing eMBB transmission, but that scheme has its own drawbacks as well and is out of the scope of this paper whose overarching focus is the scheduling of different traffic types using the same time resource. \begin{table}[!t] \renewcommand{\arraystretch}{1.0} \caption{Simulation Settings} \label{tbl:simSet} \centering \begin{tabular}{|c||c|} \hline Configuration & Value \\ \hline Transmit power & 23 dBm \\ \hline Number of gNB antennas & 4 \\ \hline Cell radius & 250 m \\ \hline UE distribution & Uniform \\ \hline Number of antennas per UE & 4 \\ \hline Number of UEs per gNB & 10-50 \\ \hline Channel& \makecell{EPA20 (6.0 km/h) (Extended \\Pedestrian A model with 20 Hz \\Doppler frequency)} \\ \hline Numerology& \makecell{30kHz sub-carrier spacing, \\100MHz bandwidth} \\ \hline CSI feedback delay & 1 slot \\ \hline Traffic model& \makecell{eMBB, arVr2, ITS, powerDist2} \\ \hline Traffic ratio& \makecell{1:1:1:1} \\ \hline Number of slots& \makecell{1200 per seed} \\ \hline \makecell{Number of seeds \\per simulation run}& \makecell{10} \\ \hline \makecell{Number of RBs per RBG}& \makecell{4} \\ \hline \end{tabular} \end{table} \begin{table}[!t] \renewcommand{\arraystretch}{1.1} \caption{Parameters for Traffic Models used in Simulations~\cite{38824}} \label{tbl:traffic} \centering \begin{tabular}{|c||c|c|c|c|} \hline & eMBB & arVr2 & ITS & powerDist2 \\ \hline \makecell{Delay threshold (ms)}& 100 & 7 & 7 & 6\\ \hline \makecell{Acceptable packet \\drop probability}& 10\% &0.1\% &0.001\% &0.001\%\\ \hline \makecell{Packet size (bits)}& 12000 &32768 &10960 &2000\\ \hline \makecell{Packet arrival rate \\(packets/second)}& 1000 &60 &100 &1200\\ \hline \end{tabular} \end{table} \setlength{\belowcaptionskip}{-10pt} The overall and two close-up views of packet throughput for various traffic types are illustrated in Fig.~\ref{fig:tputAll} and Fig.~\ref{fig:tput}, respectively. The maximum throughput degradation of the proposed algorithms against the type-0 algorithm and maximum throughput gain over LEAP are summarized in Table~\ref{tbl:tput}. Fig.~\ref{fig:pkLoss} shows the packet loss rate, where a packet is considered lost if it is not entirely scheduled before reaching its delay threshold. For LEAP, the swift increase in packet loss at 30 UEs in Fig.~\ref{fig:pkLoss} for ITS and arVr2 unveils its instability and sensitivity to the UE amount and/or locations. The following key observations can be drawn from these results: \noindent 1) In general, JADE outperforms DASE, DATE as well as LEAP. The superiority of JADE over DASE and DATE is especially evident when the number of UEs is large (e.g., 50), as shown by the throughput and packet loss rate for 50 UEs in Fig.~\ref{fig:tputAll} to Fig.~\ref{fig:pkLoss}. Comparing JADE and LEAP, as shown in Fig.~\ref{fig:tput} and Fig.~\ref{fig:pkLoss}, JADE yields higher throughput and lower packet loss rate in most cases, with a maximum throughput gain of 9.9\% (see Table~\ref{tbl:tput}). The reason is that LEAP allocates RBs locally around the first best RB for each UE, but if the channel quality happens to change abruptly around the first RB, the overall channel quality may degrade hence incurring performance loss. \noindent 2) JADE has comparable and sometimes even better performance in contrast with the type-0 algorithm, as shown by the throughput for arVr2 UEs in Fig.~\ref{fig:tput}, since type-0 FDRA is based on the RBG level (4 RBs per RBG in the simulation) while type 1 is of RB-level which has a finer frequency granularity hence higher flexibility. The maximum throughput degradation of JADE against type-0 FDRA is only 0.9\%. \noindent 3) Dual-end FDRA surpasses its single-end counterpart, as validated by DATE and DASE, due to its higher frequency diversity. \noindent 4) As demonstrated by the left plot of Fig.~\ref{fig:tput}, Table IV, and Fig.~\ref{fig:pkLoss}, DASE and DATE perform well and even exceed LEAP when the number of UEs is not very large, i.e., up to 40 UEs in this case. Since these two algorithms enjoy the least complexity, they can be used when traffic load is not too high. \begin{table \renewcommand{\arraystretch}{1.1} \caption{Throughput Comparison} \label{tbl:tput} \centering \begin{tabular}{|c||c|c|c|} \hline Algorithm & JADE & DASE & DATE \\ \hline \makecell{Maximum throughput \\degradation against Type 0} & 0.9\% &2.8\% &2.5\% \\ \hline \makecell{Maximum throughput gain over LEAP} & 9.9\% &8.9\% &11.0\% \\ \hline \end{tabular} \end{table} \begin{figure} \centering \includegraphics[width=\columnwidth]{Fig3_v1.pdf} \caption{Packet throughput of the proposed three scheduling algorithms with type-1 FDRA, as well as LEAP in~\cite{Wong11} and an RBG-level type-0 FDRA.} \label{fig:tputAll} \end{figure} \begin{figure} \centering \includegraphics[width=\columnwidth]{Fig4_v1.pdf} \caption{Close-up views of packet throughput for arVr2 UEs in the case of 30 total UEs and for all UEs in the case of 50 total UEs.} \label{fig:tput} \end{figure} \begin{figure} \centering \includegraphics[width=0.81\columnwidth]{500mISD_LOS_10seeds_1200slots_v1.pdf} \caption{Packet loss rate of the proposed three scheduling algorithms with type-1 FDRA, as well as LEAP in~\cite{Wong11} and an RBG-level type-0 FDRA. } \label{fig:pkLoss} \end{figure} \vspace{- 15pt} \section{Conclusion} We have proposed three practical multi-UE scheduling algorithms with type-1 FDRA, i.e., JADE, DASE, and DATE, and compared their performance with each other and with an optimal non-contiguous RBG-level FDRA method and a typical contiguous FDRA algorithm LEAP in the industry. Numerical results demonstrate that JADE can achieve near-optimal performance and outperform LEAP in terms of QoS requirements while having low computational complexity. Additionally, DASE and DATE perform similarly to JADE for small to moderate numbers of UEs, but with substantially lower computational complexity, thus can be adopted in practice under low traffic load conditions. The proposed algorithms are applicable to both downlink and uplink. This work can be extended by considering coarser frequency granularities in contiguous FDRA to mitigate RIV overhead~\cite{Kittichokechai20}. \ifCLASSOPTIONcaptionsoff \newpage \fi \vspace{- 6pt} \bibliographystyle{IEEEtran}
{'timestamp': '2020-10-07T02:10:05', 'yymm': '2009', 'arxiv_id': '2009.09520', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09520'}
arxiv
\section{Introduction} Estimation of gaze in current non-invasive, video-based eye trackers allows research involving visual perception, eye movement studies, virtual reality, and augmented reality in natural conditions ~\citep{li2008model,Kassner:2014:POS:2638728.2641695, san2010evaluation,holmdahl2015build,pupil2019invisible}. Current feature-based eye-trackers mainly estimate gaze by fitting a mathematical model (model-based or regression-based in 2D or 3D) to localized eye features such as the pupil, iris border, and corneal reflection (CR)~\citep{tsukada2011illumination,kassner2014pupil,dierkes2018novel,li2005starburst,hansen2009eye}. The spatial quality of the estimated gaze is characterized mainly by two widely used metrics; accuracy and precision. The degree to which an eye tracker can estimate the correct gaze position for a known target is referred to as its \textit{accuracy}, whereas the degree of spatial and temporal dispersion of gaze during fixations is referred to as its \textit{precision}~\citep[p.~182]{edlund2019advanced}. Various factors such as the inability of the participant to fixate at the desired target, the video quality of an eye tracker (resolution and compression artifacts), the experimental setup (on-axis or off-axis), calibration decay and the gaze-estimation algorithms limit the precision and accuracy of these systems~\citep{blignaut2019cost,ehinger2019new}. Among those factors, the selection of a gaze-estimation algorithm can influence the reported gaze significantly~\citep{hansen2010eye, villanueva2008evaluation}. Current video-based eye trackers are limited by signal noise due to reliance on localizing the edges of the pupil/iris boundary. Low-level image features such as edges are intolerant to illumination changes, occlusion caused by eyelashes/eyelids, CR at the pupil boundaries, etc. They are also highly dependent on parameters such as threshold values. Further, when eye-cameras are off-axis, the objective function of fitting an ellipse on the projected 2D image of iris or pupil might produce an error as these features are not perfect ellipses~\citep{swirski2015gaze,villanueva2008evaluation,wang2019center}.Recently, convolutional neural network-based approaches (appearance-based models) have been developed~\citep{park2018deep,park2018learning,kim2019nvgaze}, which focus on taking advantage of extensive training sets, learning-based optimization and generalization, preparation of synthetic data with natural features using generative adversarial networks~\citep{kim2019nvgaze,wood2016learning}, etc. However, the gaze estimation results are biased towards the training set and have only reached an accuracy of 2.06 ($\pm0.44$) degrees~\citep{kim2019nvgaze} for real subjects. There is still room for improvement in these approaches before its extensive use in research, especially in tasks requiring high precision. In another approach,~\cite{pelzwitzner} tracked a large number of \textit{motion vectors} made up of iris features across adjacent frames in order to extract the velocity of the eye over time, integrating the velocity to obtain eye position. They emphasized improving the temporal precision and accuracy of the eye-tracking system by considering a large number of iris features where the noise was addressed in the spatial domain rather than the temporal domain.~\cite{Chaudhary_Pelz_2019} extended~\cite{pelzwitzner}'s approach to demonstrate a method to achieve a high precision system capable of detecting small eye movements as small as 0.2 degrees with high confidence. While~\cite{pelzwitzner} and~\cite{Chaudhary_Pelz_2019} both show significant gains in precision due to the emphasis on a large number of motion vectors, neither addresses the issue of the drift inherent in a system that determines position purely by the integration of velocity over time. Small errors in approximations of the velocity induced by the use of central tendency metrics like geometric median~\citep{pelzwitzner,Chaudhary_Pelz_2019} accumulate over time, resulting in temporal drift which degrades accuracy in gaze estimations~\citep{chaudhary2019motion}. Additionally,~\cite{pelzwitzner} and~\cite{Chaudhary_Pelz_2019} only used trials without blinks because the method relies solely on the integration of iris motion vectors, which are absent during blinks. If gaze position changes while the eyelid covers the iris features, gaze position based on integrated motion values are inaccurate. Motion blur can also degrade performance as relatively few matches are available. This raises a concern regarding the overall concept of relying completely on the integration of velocity for the position signal, especially during rapid motion and pupil occlusion. One alternative approach might be to use the velocity integration method to provide only relative position information and use it in parallel with a traditional eye-position signal (e.g., P-CR or 3D gaze vector). In essence, such a system would provide high precision data during fixations and smooth pursuit, but rely on traditional methods at all other times. The goal of this paper is to address these issues, namely erroneous drifts, handling of blinks, and motion blur. Our approach is to use traditional approaches such as (P-CR) based system with an iris-based velocity system as proposed in~\citep{pelzwitzner,Chaudhary_Pelz_2019}. P-CR based gaze estimation has been used extensively since the 1960s and is still used today in some commercial eye-trackers. However, precision is constrained because of reliance on pupil edges and the bright corneal reflection~\citep{li2008model}. By optimally combining the \textbf{\textit{P}}-CR \textit{position} with the \textbf{\textit{i}}ris \textit{velocity} (computed from \textbf{\textit{t}}extures) [``$Pi_t$'' (or ``$\pi_t$'')] we demonstrate a hybrid method with high precision without the issues caused by drift, blinks, or motion blur. Observations made from multiple sources (e.g., pupil and iris estimates from different measurement techniques) can be fused with various state estimation techniques. Maximum likelihood and maximum posterior, the Kalman filter~\citep{kalman1960new}, and the particle filter~\citep{del1996non} are some of the common state estimation techniques used based on linear/non-linear dynamic measurements systems~\citep{castanedo2013review}. The disadvantages of maximum likelihood and maximum posterior are that in order to reduce the bias of the solution, they require an empirical model of the sensor with a possibly large number of samples~\citep{castanedo2013review}. As our data can be assumed to be from linear sources with Gaussian distributed noise (random variable derived by a large number of identically independent iris feature matches/pupil edges), modeling with the Kalman filter is a good fit as it assures the optimal estimation on this type of data~\citep{alofi2017review}. The use of the particle filters is sophisticated and well-practiced for non-linear data, but to obtain small variance in the estimations requires a relatively large data sample~\citep{alofi2017review}. The Kalman filter is designed to combine uncertain information from multiple independent sources to estimate a more confident (certain) approximation~\citep{pei2017elementary}. Our goal is to combine the information derived from the iris (\textit{I}: high precision but possibly contaminated with drift, motion blur, or blinks) with the information from the pupil (\textit{P}: no drift but noisy) by considering a convex combination of the two estimates with a general form $\beta \times I + (1-\beta) \times P $, where $(0 \leq \beta \leq 1)$~\citep{pei2017elementary}. $I$ and $P$ are derived in Section ~\ref{sec:model_formulate} and represent iris and pupil information, respectively, and $\beta$ is scaled with confidence in the information from the iris. Note that position information (P) is computed independently for each frame. As a result there is no accumulated drift, but the signal is noisy because of reliance on edge/boundary calculations based on a small number of features (edges) on each video frame. A position signal can also be computed by integrating the velocity signal derived from the iris features in consecutive frames. That position signal, however, suffers from drift over time because even small errors are compound over large numbers of frames. Here, combining the information from the two signals generated from two independent methods is not straightforward. We are only interested in the position information from the pupil center, and only the velocity information from the iris features so that the noise (from the pupil signal) and the drift (from iris signal) are not considered. Our work incorporates the two signals in the different domains that are related by first-order derivative/integration, which can further be applied to any application which has a spatial drift over time. We demonstrate this strategy in the field of eye-tracking to devise a post-hoc evaluation pipeline on a chin-rest system with both high accuracy and high precision for stimuli displayed in an automated teleprompter setup. The major contributions of this paper are as follows: \begin{enumerate} \item We demonstrate a new methodology to improve precision of any pupil detection technique by incorporating information from multiple features of the iris. This is one of the earliest attempts to combine regression-based approaches (P-CR) with computer-vision approaches such as iris feature matching and tracking. This paper opens an interesting area to be explored i.e. combining information from any eye-trackers (P-CR, 3D based approaches, appearance-based models) with iris-based estimates. \item We present a modified Kalman filter approach that helps to estimate a reliable signal by disentangling useful pieces of information from two independent sources (one precise, but drifting signal and another accurate but noisy signal). \item With the off-the-shelf components like a digital camera, synchronized displays and IRLEDs, we show sample-to-sample root mean square error (S2S-RMS) of ~$0.05^{\circ}$ for real human-eye. \end{enumerate} \section{Literature Review} Depending on the use of either polynomial gaze function or fitting a 3D model of the eye to predict gaze, video-based eye-tracking methodology is broadly divided into two categories; regression-based and model-based gaze estimation~\citep{hansen2009eye}. Both categories are reliant on eye features such as pupil center, pupil/iris contours, glints (CR), facial features~\citep{chen2008robust}, limbus, eye-corners, iris features, etc.~\citep{tsukada2011illumination,li2005starburst,park2018learning,pelzwitzner,Chaudhary_Pelz_2019,hansen2009eye,chen2008robust,swirski2012robust}. Regression-based gaze estimation uses a mapping function to predict 2D gaze coordinates based on the features. In contrast, model-based approaches allow gaze estimation in 3D space. Model-based approaches such as~\citep{tsukada2011illumination,swirski2012robust,shih2004novel,guestrin2006general,chen20083d} assume a spherical eye model and approximate a gaze direction based on pupil/iris contours. These models approximate the solution based on several assumptions such as neglecting perspective projection and the effects of refraction in~\citep{shih2004novel}, virtual pupil lying in the optical axis in~\citep{chen20083d} and neglecting corneal reflection in~\citep{swirski2012robust}. Moreover, recent publications~\citep{dierkes2018novel,dierkes2019fast} have also accounted for the corneal reflection in the 3D-model. Recently, appearance-based models have appeared in the field of eye-tracking, which try to learn a direct mapping between the images and the gaze direction~\citep{park2018deep,park2018learning}. These models have been shown to perform better than the above models in person-independent gaze estimation and unconstrained environments but are particularly biased towards the training set. Other challenges for appearance-based models are finding ways to incorporate prior knowledge in a differential manner, the need for enormous labeled data sets~\citep{marcus2018deep}, computational cost, and the difficulty of understanding what the models have actually 'learned'~\citep{park2018learning}. Even though appearance-based models were incorporated with additional regression-based or model-based methods in~\citep{park2018deep,park2018learning}, the method is still not reliable for high precision tasks. We propose a regression-based gaze estimation method that has the potential to be further modified for model-based gaze estimation. Our priority is to achieve a high-precision system and are focused on tracking features that are more reliable for that purpose. To do so, we are extending~\citep{Chaudhary_Pelz_2019} previous work, which demonstrated a high-precision task (microsaccade detection) by integrating eye velocity computed from a large number of iris features. To address the issues existing in that method, we enhance that method by optimally adding pupil-center tracking. Pupil location has been tracked in numerous ways including the Starburst algorithm (based on the iterative selection of candidate points obtained by ray following to find best-fit)~\citep{li2005starburst}, an image-aware support function to fit an ellipse to the pupil edge~\citep{swirski2012robust}, and fitting an ellipse to connected components~\citep{Kassner:2014:POS:2638728.2641695}. In this work, we deploy the method of~\cite{Kassner:2014:POS:2638728.2641695} to detect the pupil center, but we capture a high-resolution image of the eye as in~\citep{Chaudhary_Pelz_2019}. Our regression-based gaze estimation method is based on those signals. \section{Methods} This section formulates the problem of estimating an approximate hybrid position ($\pi_t$) by extracting the P-CR relative eye position and iris velocity (\textit{i}). The detailed block diagram is shown in Figure~\ref{fig:block}. Frames are extracted from the video sequence and fed to specific blocks for processing. In one of the blocks, images are fed to a CNN to obtain an iris mask, which is a crucial step to define the region of interest for another step whose objective is to approximate the iris velocity based on the motion distribution of feature matches in consecutive frames. The next step is the determination of the pupil center based on ellipse fitting, as proposed in~\cite{Kassner:2014:POS:2638728.2641695}. To compensate for head movements, we determine the average CR signal of multiple glints as well as approximate head movement velocity based on a fixed head mask on the subject. Based on these signals, $\pi_t$ is computed and demonstrated in applications such as gaze estimation, smooth pursuit analysis, and microsaccade detection. \begin{figure} \begin{center} \includegraphics[width=\linewidth]{block_diagram.png} \end{center} \caption{Basic flow of our methodology.} \label{fig:block} \end{figure} \begin{figure*} \begin{center} \includegraphics[width=\linewidth]{journal_2_plabs_2.pdf} \end{center} \caption{2D pupil center detection based on open-source of Pupil Capture~\citep{Kassner:2014:POS:2638728.2641695}} \label{fig:pupillabs} \end{figure*} \subsection{Pupil position} The pupil center (P) is specified as the ellipse center given by the 2D pupil detection model of the Pupil Labs software of~\cite{Kassner:2014:POS:2638728.2641695}.~\cite{Kassner:2014:POS:2638728.2641695} initially compute an integral image from the grayscale image and find an approximation to the pupil and region of interest (ROI) for pupil detection based on response to Haar-like center-surround features~\citep{swirski2012robust}. In the obtained ROI, spectral glint masks and a dark pupil mask are created based on the maximum intensity and the lowest and highest spike index. Morphological operations (opening with an elliptical structured kernel of size 9) followed by the Canny Edge detector~\citep{canny1986computational} are then used to find the pupil edges. In~\cite{Kassner:2014:POS:2638728.2641695}, the contours are found based on connected components of the edges. On those contours which have a minimum size of three points, the number of points that compose that line segment is reduced to find a similar curve using the OpenCV~\citep{bradski2000opencv} implementation of the Douglas-Peuker algorithm~\citep{douglas1973algorithms}. The extracted contour points are then passed through a curvature test such that any three adjacent contour points must have a curvature more than 80 degrees for the curvature to be maintained. Thus, on the intermediate contours based on continuous curvature, \textit{weak} and \textit{strong} contours are extracted based on parameters such as roundness ratio (ratio of minor and major axis) and user-defined radius limits of ellipse fit. \textit{Strong} contours must also satisfy ellipse criteria for area and perimeter ratio of contour support, whereas weak contours need not. For those contours, either \textit{strong} or \textit{weak}, pruning using an augmented combinatorial search is done in order to find the \textit{solutions}. \textit{Best solutions} out of these \textit{solutions} are found based on the roundness ratio, the user-defined radius of ellipse fit (70, 200), and support ratio based on supporting edge length and the ellipse circumference. The \textit{best contour} is obtained from the \textit{best solution}, which gives us the final \textit{best edges} (intersection of best contour with initial edges). The final \textit{best ellipse} is based on the ellipse fit on those \textit{final edges} when it satisfies all the above criteria. The center of this final \textit{best ellipse} fit is considered as the pupil-center (P) in this paper. These steps are shown in Figure~\ref{fig:pupillabs}. \subsection{Iris velocity} Eye velocity is determined by tracking multiple feature points on the iris, so the first step is defining the iris ROI on the eye images. Semantic segmentation models like U-Net~\citep{ronneberger2015u} and RITnet~\citep{9022181} can be used to extract the segmented iris mask from a given eye image. We adopt the U-Net architecture as in~\citep{Chaudhary_Pelz_2019} with a modification during model training. Instead of reshaping the 960$\times$540 to 224$\times$224 as in~\citep{Chaudhary_Pelz_2019}, we initially partition each eye image to 540$\times$540 before resizing to 224$\times$224. This maintains the aspect ratio of the image and eliminates unnecessary pixels as the eye size $<540$ pixels. Then, we follow the same steps as in~\citep{Chaudhary_Pelz_2019} on the segmented mask, i.e., we extract iris features from a Contrast Limited Adaptive Histogram equalized~\citep{pizer1987adaptive} grayscale image. These features are matched in consecutive frames based on the Lowe's ratio distance test followed by RANSAC. These matched features represent the iris feature movement vector. Final iris velocity is computed by calculating the geometric median of these movement vectors~\citep{Chaudhary_Pelz_2019}. \subsection{Problem Formulation} \label{sec:model_formulate} We have two sources of information: iris \textit{velocity} and pupil \textit{position} which we intend to combine with the Kalman filter, an optimal estimation technique for linear systems with Gaussian error~\citep{anderson2012optimal}. A straightforward interpretation of the Kalman filter update equations is that they scale measurements from two sources by their corresponding precision matrix (the inverse of the covariance matrix) and then take the weighted sum as shown in Equation ~\ref{eq:basic}. \begin{equation} \label{eq:basic} \overline{H}=\Sigma(\beta*P+(1-\beta)*I) \end{equation} where $P$, $I$ and $H$ are the pupil position, the iris position and the hybrid position respectively. In our case, one source of measurement is the pupil position, and the other is the iris velocity (which is integrated to compute the iris position). The information in iris velocity can only provide us information about the iris position up to a constant bias value. If we use a traditional update of the Kalman filter (Equation \eqref{eq:basic}), we would be using incorrect bias induced by the integration of iris velocity, and error would still creep into our estimated solution. The estimated signal would also drift over time, primarily affected by the bias information from the iris velocity measurement. Therefore, while combining iris velocity measurement with the pupil position measurement, we must ignore any bias information obtained from the iris velocity measurement to gain the benefit in precision from the velocity measure without degrading accuracy. Therefore, we need to make some crucial changes to the Kalman filter approach. To do so, we take the probabilistic interpretation of the Kalman filter. Using a probabilistic framework helps us combine two information sources from different domains in the same spirit of the Kalman filter. In a probabilistic interpretation, a Kalman update equation is interpreted as the posterior mean in which prior and likelihood are both linear. In this framework, we can easily integrate two measurements from different domains by defining a prior distribution which behaves like a Gaussian in a gradient domain, i.e., whose derivative is Gaussian. Using this approach, we can derive a Kalman update equation (as in~\cite{ghimire2019noninvasive}). We can fuse the information of the pupil position ($P$) with the iris velocity ($i$ or $\textbf{D}I$) to obtain the hybrid position (H), where \textbf{D} is the spatial gradient operator. In general, if $\textbf{P}(P|H)$ is the likelihood, $\textbf{P}(H|I)$ refers to the prior probability distribution, and $\textbf{P}(H|P,I)$ refers to the posterior distribution, then the posterior probability can be computed as \begin{equation*} \begin{split} \textbf{P}(H|P,I) &=\frac{\textbf{P}(P|H)\textbf{P}(I|H) \textbf{P}(H)}{\textbf{P}(P,I)} =\frac{ \textbf{P}(P|H) \textbf{P}(H|I)}{\textbf{P}(P|I)} \\ \end{split} \end{equation*} where $\textbf{P}(P|I)$ is the normalization factor. So, we have $\textbf{P}(H|P,I)\propto{\textbf{P}(P|H) \textbf{P}(H|I)}$. Here, $\textbf{P}(P|H)$ and $\textbf{P}(H|I)$ are defined as: \begin{equation*} \textbf{P}(P|H)=\frac{\exp^{-\frac{(P-H)^2}{2\sigma_P^2}}}{\sqrt{2\pi\sigma_P^2}}=\frac{\exp^{-(P-H)^T\beta_P\textbf{I}(P-H)/2}}{\sqrt{2\pi\sigma_P^2}} \end{equation*} \begin{equation*} \begin{split} \textbf{P}(H|I)&=\frac{\exp^{-\frac{(\frac{\textbf{D}H}{\textbf{D}t}-\frac{\textbf{D}I}{\textbf{D}t})^2}{2\sigma_I^2}}}{\sqrt{2\pi\sigma_I^2}} =\frac{\exp^{-{({H}-I)^T\beta_I\textbf{D}^T\textbf{D}({H}-I)}/2}}{\sqrt{2\pi\sigma_I^2}} \end{split} \end{equation*} where $\beta_I=1/{\sigma_I^2}$ and $\beta_P=1/{\sigma_P^2}$. Higher values of $\beta$ indicate lower standard deviation and more certainty. Note that we have used the spatial gradient of the iris position. For a prior distribution, the low dimensional structure of the signal can be considered to model the prediction error~\citep{ghimire2019noninvasive}. In our case, we find the hybrid signal by minimizing the mean square estimation between hybrid velocity and iris velocity and also between hybrid position and pupil position. An important property of Gaussian distributions is that the product of two Gaussian distributions is a Gaussian distribution~\citep[p.~638]{bishop2006pattern}. Thus,\\ \begin{equation*} \textbf{P}(H|P,I)={\textbf{P}(P|H) \textbf{P}(H|I)} \end{equation*} \begin{equation}\label{eq:appendix_elaborate} =\frac{\exp^{-(P-H)^T\beta_P\textbf{I}(P-H)/2}}{\sqrt{2\pi\sigma_P^2}}\frac{\exp^{-{({H}-I)^T\beta_I\textbf{D}^T\textbf{D}({H}-I)}/2}}{\sqrt{2\pi\sigma_I^2}} \end{equation} The equation is simplified in Appendix A. Further our term $\textbf{P}(H|P,I)$, can be expressed as \begin{equation}\label{eq:meanestimate} \begin{split} \textbf{P}(H|P,I)&=K{\exp^{-1/2{(H-\overline{H})^T\Sigma^{-1}(H-\overline{H})}}} \\ &=K{\exp^{-1/2{(H^T\Sigma^{-1}H-H^T\Sigma^{-1}\overline{H}+...)}}} \end{split} \end{equation} Comparing, Appendix A (Equation~\ref{eq:longe}) and ~\ref{eq:meanestimate}, we get the mean estimate ($\overline{H}$) and the covariance ($\Sigma$) of the hybrid position~\citep[p.~639]{bishop2006pattern} as \begin{equation*} {\Sigma}^{-1}=(\beta_P\textbf{I}+\beta_I\textbf{D}^T\textbf{D})\label{eq:inv_cov} \end{equation*} \begin{equation} {\Sigma}=(\beta_P\textbf{I}+\beta_I\textbf{D}^T\textbf{D})^{-1} \label{eq:3conv} \end{equation} \begin{equation*} \Sigma^{-1}\overline{H}=\beta_P\textbf{I}P+\beta_I\textbf{D}^T\textbf{D}I \end{equation*} \begin{equation} \overline{H}=\Sigma(\beta_P\textbf{I}P+\beta_I\textbf{D}^T\textbf{D}I)\label{eq:main2} \end{equation} It is important to note that $\textbf{D}^T\textbf{D}$ is a non-invertible matrix. Therefore as the value of $\beta_P$ tends towards 0, the determinant of $\Sigma^{-1}$ approaches 0, as shown in Appendix B. The inverse operation cannot be obtained for the covariance matrix. So it is preferable to keep the value of $\beta_P$ non-zero as it is the limiting case for our approach. With this update strategy, the bias information in the velocity measurement does not influence the solution. Hence, the solution correctly uses the rest of the information in the velocity to give a reasonable estimate of the position. This setup allows handling the drift in the estimated signal, and essential information from the iris velocity is preserved. Additionally, the modifications made to the Kalman filter also handles latency issues (discussed further in Section~\ref{qualitative}) in the traditional Kalman filter-based approach. Rather than a traditional filtering approach, the formulation we use helps in estimation by combining different temporal frequency components from the pupil and iris signals. Low-temporal frequency components of the pupil are combined with the high-temporal frequency components from the iris. This combination of frequency components results in no time-lag (run-time). Note that the addition of high-frequency components is essential as this data mainly carries information about tremors and microsaccades, which are crucial for high precision tasks. \subsection{Positional Difference Compensation} The pupil position and the iris velocity in the above relations are extracted without taking into account the movements of the eye camera (headgear slippage and relative camera movement)~\citep{li2008model}. To compensate for error induced by these events, we compute the P-CR vector to find the relative position of the eye to the camera. Additionally, we compute the head movement velocity to the camera (head velocity: \textbf{D}$H_v$) for a user-defined ROI on the forehead using a similar approach as used for computing iris velocity. Hence, in our case for the hybrid model, the gaze vector is computed when the relative position between the principal eye signal (iris or pupil) is subtracted with a compensatory movement (CR or $H_v$). So, the overall model can be computed as \begin{equation} \pi_t=Pi_t=\overline{h}=\Sigma(\beta_P\textbf{I}(P-CR)+\beta_I\textbf{D}^T\textbf{D}(I-H_v))\label{eq:1} \end{equation} Note that for the CR, we initially segment the iris mask as in ~\citep{Chaudhary_Pelz_2019} to identify the region where the CR is most likely to be present. In the iris segmented region, we identify the bright spots in the mask with an empirically derived hard threshold pixel value of above 140 (for an 8-bit image). For our experiment with four IRLEDs, we initially find the largest bright spot. A small window (ellipse or rectangle depending on the number of points in the contour) around the largest spot is then used to find the remaining valid CRs. The LEDs are placed such that CR usually falls on the iris. However, on infrequent occasions like that seen in Figure ~\ref{fig:roll_off}, one of the CR falls on the sclera. We ignore this CR as a detection but consider all other CRs as valid. So, on those valid CRs, we find the center of the glint using moments. The centers of the detected CRs are used to approximate a circle. The center of this circle is referred to as CR in the following sections. \begin{figure} \begin{center} \includegraphics[width=\linewidth]{results/roll_off.png} \end{center} \caption{Example where one of the four CRs rolls off the cornea onto the sclera.} \label{fig:roll_off} \end{figure} \subsection{Blink Classification and Poor Feature Match} \label{sec:blinks} The hybrid model ($\pi_t$) has weighting parameters $\beta_p$ and $\beta_i$, related to confidence in the pupil position and iris velocity, respectively. Except during a blink, they sum to 1. The weight $\beta_i$ is a function of the number of detected iris feature matches; $\beta_i = min(0.9,0.9*(n_{\mathrm{matches}})/(min_{\mathrm{matches}}))$ , where $min_{\mathrm{matches}}$ is a user-set parameter set. The confidence in iris velocity will be degraded if fewer than $min_{\mathrm{matches}}$ feature points are computed, such as in cases of a large saccadic movement, motion blur, and significant compression artifacts. To avoid abrupt changes in $\beta_i$ (from 0.9 to $<$0.9) between two consecutive timestamps when there are only a few feature matches, we use a linear decay function that takes into account the previous/next two timestamp's $\beta_i$ values. To classify blinks in the pupil signal, we use a confidence value provided by the open-source Pupil Capture software~\citep{Kassner:2014:POS:2638728.2641695}. While pupil detection confidence decreases even in cases of a `partial blink' where the portion of the pupil is occluded, a few iris feature matches still exist during the partial blink. Thus we classify blinks for pupil and iris separately and set values of $\beta_p$ and $\beta_i$ to 0 only in the case of a complete blink. In the case where pupil confidence is less than user defined confidence threshold, but we still have a few iris-feature matches, $\beta_i$ will be low, and the overall confidence in the position will be low. For this paper, we set the user-defined parameters $min_{\mathrm{matches}}$ and confidence threshold to be 50 and 0.3 respectively. \subsection{Gaze Estimation} Equation \eqref{eq:1} describes the combination of the pupil position and the iris velocity. These two components represent the calibrated gaze position and the calibrated gaze velocity for the pupil and iris, respectively, which we combine to get a hybrid gaze position. This relation is valid for both cyclopean eye (midpoint of two eyes)~\cite{ono1982cyclopean,hering1977theory} and independent individual eyes. Independent analysis of the individual gaze of each eye supports the study of vergence eye movements, which is not possible with cyclopean gaze estimation. Many current video-based eye trackers report cyclopean gaze estimates because the precision and accuracy of current eye trackers is insufficient to estimate depth based on gaze position. The improved hybrid signal for each eye may provide adequate signal quality to estimate a useful vergence signal. For computing the calibrated gaze position from the pupil, calibration is performed by a second-order polynomial of the instructed gaze position and its corresponding relative pupil position ~\cite{cerrolaza2012study,swirski2015gaze}. The same calibration routine creates problems for iris gaze position because the iris drifts over time, and additionally, due to possible pupil dilation/constriction and a significant position change of gaze during blinks. So, instead, we use a calibration scheme based on the iris velocity signal; we know the relative distance between calibration target positions, and we can extract the relative distance of iris position across the saccades during calibration, so we can compute a mapping function between them. We integrate velocity from 30 ms before to 30 ms after each saccade that brings gaze to a fixation target. With the calibrated position and velocity gaze components, we compute the hybrid gaze position in terms of visual angle. \section{Experimental Design} \begin{table*}[ht] \caption{Refinements in the hardware-setup compared to~\cite{Chaudhary_Pelz_2019}} \label{tab:2} \begin{tabular}{|c|c|c|} \hline & \textbf{\cite{Chaudhary_Pelz_2019}} & \textbf{Ours}\\ \hline Mirrorless Camera & Panasonic Lumix DMC-GH4 & Panasonic Lumix DC-GH5S \\ \hline Light source & Tungsten halogen source with bifurcated fiber optics & Lite-On HSDL-4261 870nm IRED.\\ \hline Chin rest& Yes & Yes \\ \hline Forehead rest& Yes & No (extra degree of freedom) \\ \hline Stimulus & Printed Snellen Chart & Appearing Intermittently (Teleprompter)\\ \hline Frame rate & 96 Hz & 120 Hz\\ \hline Synchronization & No (finite interval used to localize eye movements) & Yes (Photo-diode setup)\\ \hline \end{tabular} \end{table*} \subsection {Camera Setup} We tested our method with images captured with a Panasonic Lumix DC-GH5S mirrorless digital camera (modified by removing the IR-rejection filter) with a Lumix G Vario 14-140mm II ASPH (H-FSA14140) lens set to a focal length of approximately 100 mm and an aperture of F/8. Sensitivity to visible wavelengths was blocked with a DHD IR760 high-pass filter ($T_{380-740} < 1\%, \ T_{780-1200} > 85\%$). The camera was set to an ISO value of 800 and the shutter speed to $1/400$ sec. We recorded binocular eye movements at 120 frames per second (fps) at a resolution of 1920 $\times$ 1080, with IPB compression [FHD/8bit/100M/59.94Hz] with a slow-motion effect of 1/2). The camera was placed 50 cm from the observers' eyes, whose position was fixed with a UHCOTech HeadSpot chin rest (with no forehead rest). The setup allowed observers to make small rotational and translating head movements without significant distance variation. Four infrared LEDs (IREDs) (HSDL-4261, 870 nm, viewing angle= 26$^{\circ}$), each placed on a square of approximately 2 cm, were used to illuminate each eye uniformly at angle of 25-30 degrees above the horizontal. The IREDs were placed at a distance of approximately 9 cm from the eyes (as shown in Figure~\ref{fig:experiment}) such that an area of approx. 36 $cm^2$ of the eyes was covered to provide proper illumination even if the observer made small head movements. The total irradiance at the eye was 0.01 $W/cm^2$ measured with a calibrated radiometer. Table ~\ref{tab:2} summarizes the refinements made in the hardware setup compared to~\cite{Chaudhary_Pelz_2019}. \begin{figure} \begin{center} \includegraphics[width=\linewidth]{IMG_8856b.jpg} \end{center} \caption{Experimental setup with stimulus presented in iPad-teleprompter setup.} \label{fig:experiment} \end{figure} \begin{figure} \begin{center} \includegraphics[width=\linewidth]{results/image2.png} \end{center} \caption{Grayscale version of the image captured with the setup (Top row). Bottom row contains cropped version of left eye for different subjects with corrected glasses.} \label{fig:experiment_images} \end{figure} \subsection{Display target} We used a teleprompter setup (Glide Gear TMP50 20.3 X 17.8 cm) with an iPad (MR7FZLL/A) to display the stimuli. The stimuli were presented as a 30 fps video, the same temporal resolution as the iPad. To synchronize the displayed stimulus, we use a photo-diode setup, as shown in Figure~\ref{fig:experiment}. A region of the video that is not visible in the teleprompter screen contained a unique binary pattern of black and white patches, which transitioned each time the stimulus display changed. The binary pattern was detected by a photo-diode and Op-Amp (LM-358) circuit. Because the iPad LCD display has a faster black-to-white transition than white-to-black, we used the black-to-white transitions to mark events. To make the display sync signal available in the video record, the output of the Op-Amp drove a 940 nm IRLED in the field of view of the Lumix camera to indicate when a stimulus was presented to the observer in the video sequence. Because iPads are raster displays operating at 30 Hz, it takes approximately 33 ms to rewrite the entire display. We derived a parametric model to find the delay based on the display position on the screen. We have accounted for this time delay in our results. The parametric model is given by \begin{equation} t =(21.4*x)+(4.26*y)-2.35 \end{equation} where $x$ and $y$ refer to horizontal and vertical stimulus position in pixels, and $t$ is the estimated delay in ms. \section{Subjects} We recorded eye movements of seven participants (four males and three females) with a mean age of 31 ($\sigma$=12) with normal or corrected-to-normal (two out of seven subjects) vision. Observers with a varying range of iris pigmentation were selected for the experiment. The experiment was conducted with the approval of the Institutional Review Board, and all participants provided informed consent before starting the experiment. \section{Tasks} Every observer performed a sequence of tasks. Initially, 12 calibration targets were displayed on the screen in a pseudo-random pattern to allow the maximum number of changes in horizontal and vertical directions, as shown in Figure~\ref{fig:calib}. Each target consisted of concentric circles, the larger of which intiially subtended an angle of 1.0 degrees. The target first grew to a size of 1.34 degrees then decreased to a size of 0.5 degrees before disappearing after one second, as shown in Figure ~\ref{fig:stimuli}. The field of view of the calibration targets was 14.19$^{\circ}$ X 9.68$^{\circ}$. The calibration was followed by the tasks described in the following section. \subsection{Task 1: Calibration Verification Task} Six calibration verification targets were shown in sequence, subtending a total angle of 10.02$^{\circ}$ X 3.99$^{\circ}$. The delay between the disappearance of one target and the appearance of the next target was on average 31 ms ($\sigma$=5). The calibration verification points were different from those used during calibration. \begin{figure}[h] \begin{center} \includegraphics[width=\linewidth]{results/calibration_2b.pdf} \end{center} \caption{Calibration targets designed to maximize variations in gaze angle and directions} \label{fig:calib} \end{figure} \begin{figure*} \begin{center} \includegraphics[width=\linewidth]{results/stimuli.png} \end{center} \caption{Visualization of target size animation over 1-second interval: each frame was displayed for 1/30 second.} \label{fig:stimuli} \end{figure*} \subsubsection{Measures} We evaluated the accuracy and precision with which the methods predicted gaze on the verification targets, assuming that the observer fixated each target. Accuracy measures were based on the difference between the displayed target position and the mean reported gaze position of the stable fixation window. The fixation window was determined from a rolling 450 ms window with a minimum dispersion search after the target was displayed on the screen. Another essential metric we considered was precision during fixations. Sample-to-sample root mean square error (S2S-RMS) and standard deviation (STD) are two widely used metrics to measure the precision of eye-trackers~\citep[p.~182-4]{edlund2019advanced}. Both measures are related to the spatial variability in the signal over time, but they contain different information about an eyetracker's behavior~\citep[p.~182-4]{edlund2019advanced},~\citep{niehorster2020characterizing}. Because S2S-RMS is calculated on temporally adjacent data points, its value relays information about the spatio-temporal aspects of a system that are absent from STD measures. S2S-RMS is also inherently sensitive to the update rate of the eye-tracker~\citep{blignaut2012precision}. \begin{equation} S2S-RMS =\sqrt{\dfrac{\sum_{i=1}^{n} {(x_{i}-x_{i-1}})^2+(y_{i}-y_{i-1})^2}{n}} \end{equation} \begin{equation} STD=\sqrt{\dfrac{(\sigma_x^2+\sigma_y^2)}{2}} \end{equation} \subsection{Task 2: Smooth Pursuit Task} To evaluate the eye-tracking methodology, we evaluated two tasks that require very high precision: microsaccade detection and smooth pursuit. For a smooth-pursuit task, observers followed a moving target on a ramp (linear-trajectory) at different velocities (mean=4.6 deg/s, $\sigma$=1.9) with 17 random directional changes. \subsubsection{Measures} \label{SP_describe} Measurement of accuracy and precision in a smooth-pursuit task is not straightforward.~\cite{komogortsev2013automated,komogortsev2010standardization} proposed a method to determine the accuracy based on how closely the smooth-pursuit signal matches the target stimulus. A quantitative smooth pursuit score based on the position and velocity was reported based on the Euclidean distance and differences in speed at every timestamp with respect to the smooth-pursuit target stimulus. We propose a method for measuring precision during smooth pursuit using S2S-RMS and STD after `detrending' the raw data. 'Detrending' a signal subtracts the best-fit line/curve from the data~\cite{moncrieff2004averaging}. So, a constant velocity term can be removed from the smooth-pursuit data resulting in nearly zero-velocity signal. In any smooth pursuit movement with randomly changing directions, it is observed that there is a latency of $100-130$ ms after the direction change~\citep{lisberger1987visual,lisberger1985properties,fukushima2013cognitive}. At that point, the eye either begins moving at approximately the correct velocity (but is lagging the target due to the latency), or the movement starts with a small saccade in the direction of the stimulus. In either case, the eye velocity is then typically similar to that of the target but lags in position. Finally, any positional offset between the eye and target is corrected by a second `catch-up' saccade, as shown in Figure~\ref{fig:sp1}. At that point, the eye position and velocity match the stimulus. \begin{figure}[ht] \begin{center} \includegraphics[width=\linewidth]{results/our_sp.png} \end{center} \caption{Conceptual diagram of eye position (red) and target stimulus (gray) during smooth pursuit after ~\cite{fukushima2013cognitive}.} \label{fig:sp1} \end{figure} In our proposed smooth-pursuit precision metric, we initially find the time interval where both the eye position and eye velocity are closest to the stimulus position and velocity. The eye position at this moment is referred to as the \textit{starting point}. Similarly, we compute the \textit{ending point} just before the stimulus changes direction. An equation describing the line joining the starting and ending gaze points is computed. The gaze signal is detrended using this signal (line), resulting in a signal with zero mean velocity and can be analyzed in the same way as a fixation signal. We can thus compute the precision (S2S-RMS and STD) for the detrended signal. \subsection{Task 3: Microsaccade Detection Task} \label{MS_describe} Motivated by~\citep{shelchkova2018perceptual} and~\citep{Chaudhary_Pelz_2019}, we evoked small, voluntary eye movements with a Snellen acuity chart by displaying a sequence of fixation targets on the teleprompter screen. Any voluntary or involuntary saccade less than 0.5 $\circ$ is considered as \textit{microsaccade} in this paper following ~\cite{engbert2003microsaccades,otero2008saccades,troncoso2008microsaccades,shelchkova2018perceptual,Chaudhary_Pelz_2019}. There were two elements in this task; first, the observer was asked to fixate on a series of thin color bars (6 bars, each (5.2x12 arcmin)), then on six colored boxes, alternating in size between 12x12 and 5.2x12 arcmin. Each target was displaced from the previous target in the horizontal direction by 0.2 degrees (12 arcmin). The total expected number of small eye movements was ten (five each for the color bars and boxes). \subsubsection{Measures} We measured the number of microsaccades detected when the observer looked to the different color bars$/$boxes. Horizontal eye movements detected within 100 - 500 ms of each target onset were identified as microsaccades. Note that horizontal cyclopean velocity was used for microsaccade identification. We used the method described in~\citep{Chaudhary_Pelz_2019}, where the velocity signal is filtered with a 1D total variational denoising filter (regularization value of 0.05). After denoising the velocity signal, a threshold value is determined with an adaptive algorithm by fitting two velocity distributions representing noise and microsaccade based on Gaussian mixture models. Velocities above the adaptive threshold are identified as microsaccades based on the Velocity-Threshold Identification algorithm (I-VT)~\citep{salvucci2000identifying}. We refer the reader to~\citep{Chaudhary_Pelz_2019} (Section: Microsaccade detection) for additional details. \section{Results} \subsection{Iris segmentation} Maintaining the aspect ratio by cropping to 540$\times$540 before resizing to 224$\times$224 boosted the performance by 1.8\% and 2.9\% for the uncorrelated and correlated test data respectively as seen in Table~\ref{tab:1}. \begin{table}[ht] \caption{Note improvement in segmentation results due to change in aspect ratio} \label{tab:1} \begin{tabular}{|c|c|c|} \hline \textbf{Dataset} &~\cite{Chaudhary_Pelz_2019} & Ours\\ \hline Training & 89.8\% & 92.4\% \\ \hline Uncorrelated test & 89.1\% & 90.7\% \\ \hline Correlated test & 86.6\% & 89.1\%\\ \hline \end{tabular} \end{table} \subsection{Qualitative Results} \label{qualitative} The dramatic difference in noise between the traditional P-CR and $\pi_t$ methods can be seen in Figure~\ref{fig:long_PCR}. The top panel shows the horizontal and vertical position signals for both methods; the inset panels show the indicated segments at $4\times$ magnification. Note that the noise reduction from the $\pi_t$ method does not introduce a temporal lag in the signal as temporal filtering methods do (distinguishable with (*) marker in position plots). The lower panel shows the velocity signals over the same periods for both methods. The reduced noise inherent in the $\pi_t$ method is especially evident in the velocity signals. Note that all the results presented for traditional P-CR and $\pi_t$ methods are analyzed for same video at the same timestamps. \begin{figure}[h] \begin{center} \includegraphics[width=\linewidth]{results/position_latency.png} \end{center} \caption{Comparison of position (top panel) and velocity (bottom panel) signals from P-CR and $\pi_t$ methods in horizontal and vertical directions (best viewed on online version of the paper). Each zoomed-in section (in yellow) is 200 ms in duration (4$\times$).} In zoomed-in section (*) marker shows estimate of individual timestamp and represents similar latency to P-CR based method. \label{fig:long_PCR} \end{figure} \subsection{Task 1: Verification Task Performance} \subsubsection{Accuracy} Figure~\ref{fig:Accxverify} (left) shows the accuracy of $\pi_t$ and P-CR methods along the horizontal axis. Both plots indicate accuracy for the left, right, and cyclopean eye. Each point in the figure represents an individual participant. Figure~\ref{fig:Accxverify} (right) shows the same data for accuracy along the vertical axis. Note that accuracy is the same for $\pi_t$ and P-CR based methods. \begin{figure*}[h] \begin{center} \includegraphics[width=\linewidth]{results/accuracy_2_rot.pdf} \end{center} \caption{Box plot indicating \textbf{accuracy} in the horizontal and vertical direction using $\pi_t$ and P-CR based methods for left, right, and cyclopean eyes. Similar accuracy values indicate drifts are addressed in $\pi_t$ based method.} \label{fig:Accxverify} \end{figure*} \subsubsection{Precision} While the accuracy values are the same, the $\pi_t$ method has significantly better precision. Figure~\ref{fig:STDPrecisio} represents the precision for $\pi_t$ and P-CR based methods measured with S2S-RMS (left panel) and standard deviation (STD) (right panel) metrics. Each figure has results for individual left and right eyes and for the combined, cyclopean eye. The median sample-to-sample root mean square (S2S-RMS) and the standard deviation value are improved by at least 55\% and 23\%, respectively. \begin{figure*}[h] \begin{center} \includegraphics[width=\linewidth]{results/precision_2_order.pdf} \end{center} \caption{Box plot indicating \textbf{precision} (S2S-RMS and standard deviation) using $\pi_t$ and P-CR based methods for left, right, and cyclopean eyes.} \label{fig:STDPrecisio} \end{figure*} \subsection{Task 2: Smooth Pursuit Performance} Figure~\ref{fig:sp_display} represents the gaze map of eye movements during a smooth pursuit task for one participant. Note that small, high-frequency fluctuations during smooth pursuit are minimized in the $\pi_t$ record compared to P-CR. Figure~\ref{fig:sp_std} represents the precision for $\pi_t$ and P-CR based methods using S2S-RMS (left) and STD (right) metrics. Each figure has results for individual left and right eye and the combined cyclopean eye. Note that the reported precision is for the detrended signal, as described in Section~\ref{SP_describe}. The median sample-to-sample root mean square (S2S-RMS) and the standard deviation value are improved by at least 48\% and 10\%, respectively. \begin{figure} \begin{center} \includegraphics[width=\linewidth]{results/sp_calib3.png} \end{center} \caption{Gaze map of eye movements during a smooth pursuit task for one participant. The red and blue traces show movements calculated with $\pi_t$ and P-CR methods, respectively. The orange points indicate the extreme position of the target for each direction change. Rectangular box indicates the zoomed in section (4$\times$) (best viewed on online version of the paper).} \label{fig:sp_display} \end{figure} \begin{figure*}[h] \begin{center} \includegraphics[width=\linewidth]{results/sp_2_order.pdf} \end{center} \caption{Box plot indicating \textbf{precision} (S2S-RMS and standard deviation) \textbf{using detrended smooth pursuit} signal obtained from $\pi_t$ and P-CR based methods for left, right, and cyclopean eyes.} \label{fig:sp_std} \end{figure*} \subsection{Task 3: Microsaccade Detection Performance} As described in section~\ref{MS_describe}, out of ten possible small microsaccades per subject, the number of microsaccades detected by the seven subjects was [10, 8, 8, 7, 7, 6, 5]. Only the first detected microsaccade event during a time interval of 100-500 ms of each target onset was counted. If no small-movements were beyond the threshold value during that time interval, then the count was zero. Note that 27\% of the microsaccades are not detected, mainly because of the significant head movement and simultaneous eye movement of the person to fixate at the gaze position. Figure~\ref{fig:microsaccade} shows a number of microsaccades detected with the $\pi_t$ model. The P-CR signal has too much noise to allow the microsaccades to be detected. \begin{figure*} \begin{center} \includegraphics[width=\linewidth]{results/microsaccade_analysis_2.png} \end{center} \caption{Figure shows the velocity signals for P-CR and the $\pi_t$ model. Each microsaccade event starts with a display of a stimuli (indicated in vertical black line). The time period where an event is likely to occur is indicated in green and the detected microsaccade is indicated in cyan. The yellow boxes indicate special events when microsaccades are not detected, or multiple microsaccade detected in the time interval (best viewed on online version of the paper).} \label{fig:microsaccade} \end{figure*} \subsection{Simulation Test} In this section, we explore the mathematical formulation in Equation~\ref{eq:main2} using simulated data. Our hypothesis is, given any two random signals ($A_{noise}$ and $B_{drift}$) which are related to each other by first-order derivative/integration; where signals $A_{noise}$ and $B_{drift}$ are influenced by spatial noise and temporal drift respectively, then the $\pi_t$ algorithm can be used to estimate a signal that compensates for both spatial noise and temporal drift. Note that rather than attempting to replicate eye-gaze data we are simulating random signals $A_{noise}$ and $B_{drift}$ that fulfill the stated requirements. Signals $A_{noise}$ and $B_{drift}$ are derived from a 2 Hz square wave with an amplitude of three units sampled at 250 Hz for 2 sec followed by a 1 Hz sine wave with a peak amplitude of two units sampled at 250 Hz for the next two seconds. Signal $A_{noise}$ consists of the addition of random Gaussian noise ($\mathcal{N}(0,0.03)$ with a sampling size of 1000) to the \textit{original signal} (position-like signal; noisy). Signal $B_{drift}$ consists of the addition of random Gaussian noise ($\mathcal{N}(0,0.01)$) in the \textit{spatial gradient of the original signal} (velocity-like signal; temporal drift). Figure \ref{fig:simulation} shows ten such trials and its derived output based on $\pi_t$. For quantitative results, Table \ref{tab:sim} shows the performance of our approach $\pi_t$ generated using these two signals ($A_{noise}$ \& $B_{drift}$) in terms of mean square error (MSE) and $R^2$ computed against the original signal for 100 trials. Note MSEo $R^2$o represents computation of these metrics in the original signal domain, MSEt $R^2$t represents computation with the gradient of the signal. We observe an improvement in the original domain signal as well as a gradient-domain signal for both metrics MSE, and $R^2$ for our $\pi_t$ derived signal. \begin{table}[h] \caption{Simulation test; MSEo $R^2$o represents computation of these metrics in the original signal domain, MSEt $R^2$t represents computation with the gradient of signal. MSEt and MSEo are in $*10^{-4}$ units. } \label{tab:sim} \begin{tabular}{|c|c|c|c|} \hline & Signal $A_{noise}$ & Signal $B_{drift}$ & $\pi_t$ \\ \hline MSEo & 9.04 $\pm$ 0.38 & 475.71 $\pm$ 480.30 & \textbf{1.51 $\pm$ 0.12}\\ \hline MSEt & 18.12 $\pm$ 1.06 & 1.0 $\pm$ 0.04 & \textbf{0.88 $\pm$ 0.04}\\ \hline $R^2$o & 0.9998 & 0.9914 & \textbf{0.9999} \\ \hline $R^2$t & 0.9931 & 0.9996 & \textbf{0.9997} \\ \hline \end{tabular} \end{table} \begin{figure*} \begin{center} \includegraphics[width=\linewidth]{results/simulation.png} \end{center} \caption{The figure shows the original signal (solid grey line), ten trials of signals $A_{noise}$ and $B_{drift}$, and its recovered $\pi_t$ output. Note that signal $A_{noise}$ has spatial noise (dashed red lines visible in block II indicated in a yellow box), signal $B_{drift}$ has temporal drift (solid green lines visible in block III indicated in a yellow box). The derived signal output (blue lines, distinguishable in zoomed-in blocks IV (position signal) and V (velocity signals) handles the temporal drift and minimizes the spatial noise (best viewed on online version of the paper).} \label{fig:simulation} \end{figure*} \section{Discussion} The previous methods based on tracking motion of iris features offer significant improvements over existing methods, but an important limitation of these methods is the temporal drift in the estimation of gaze. The major contributing factor for the drift was the compounding of small errors in the approximation of velocity. Our work addresses this issue by considering the pupil edges (extensively used in traditional gaze tracking methodologies) as support for velocity approximation. We present a new mathematical formulation which handles drift in gaze position by considering a weighted sum in a Kalman filter framework. Moreover, our approach is being extended further such that we will also be capable of handling cases during blinks and insufficient texture matches. During calibration, the use of positional information from $\pi_t$ helps to eliminate the need for integration of velocity, which was the bottleneck during blinks in~\citep{Chaudhary_Pelz_2019, pelzwitzner}. Our modification in $\beta_P$ and $\beta_I$, as described in section ~\ref{sec:blinks}, helps to handle cases of blinks and insufficient texture matches. Note that in cases of partial blinks, complete pupil edges are often not visible, and ellipse fits cannot be computed reliably. In such scenarios, there is still a possibility of a good number of feature matches. The proposed method allows for the study of eye movements even during the period immediately before and after a full blink, which leads to errors when relying on ellipse fits. Further, with traditional methods, there is a high possibility of ellipse fit on false edges, which is eliminated in our method as we rely on a large number of iris features. Our mathematical formulation can further be interpreted as the superposition of contributions from separate pupil and iris estimates. In this case, we consider the signal as the combination of a high-temporal frequency component from the iris motion vectors and low-temporal frequency components from pupil position. This combination helps to maintain the accurate low-frequency position signal while supporting high precision tasks based on the high-frequency component from the stable iris motion vectors. This formulation eliminates reliance on high-frequency components from the pupil position, which are noisy and interfere in the study of eye movements such as smooth pursuit and microsaccades. Our method of calibration of the two components separately is critical. This is because the iris position drifts over time, and we need the same scaling factor for the combination. A mismatch in the scaling factor creates undershoot or overshoot during saccades as the mathematical formulation is the weighted sum of two components when the low-frequency component is significant. Thus, we propose a new iris calibration technique based solely on the relative change in iris velocity with the change in calibration targets. The hybrid ($\pi_t$) approach shows a comparable accuracy with the P-CR based approaches, suggesting that drift is not prevalent in our method even when iris information is incorporated. The simulation results in Table ~\ref{tab:sim} show a low value of MSEo and MSEt in $\pi_t$ compared to original individual signals $A_{noise}$ and $B_{drift}$, suggesting that this work can be applied in any domain where noise is prevalent in one signal and temporal drift in another. The small values in MSEo verify our contribution in handling temporal drift existing in $\pi_t$ based methods. The advantage of our ($\pi_t$) method is the improvement in the precision values without affecting the accuracy in the system. An important performance metric for eye-tracking systems is S2S-RMS, as it is highly influenced by the frame rate and temporal variation. Our method also shows an improvement in median value of S2S-RMS with at least a 55\% reduction (0.132$^{\circ} \rightarrow$ 0.042 $^{\circ}$, 0.145$^{\circ} \rightarrow$ 0.052$^{\circ}$, and 0.099 $^{\circ} \rightarrow$ 0.044 $^{\circ}$ for left, right and cyclopean eyes) in the verification task for the same video sequences. Further, we have shown an improvement of 23\% in STD, which can be thought of as a combination of both eye movement and eye-tracking methodology noise. Additionally, we show an improvement of at least 48\% in S2S-RMS and 10\% in STD for smooth pursuit tasks, demonstrating the value of the method for studies of smooth pursuit. We also highlight an essential contribution of~\citep{Chaudhary_Pelz_2019}'s previous work in detecting eye movements as small as 0.2$^{\circ}$ and also verifies that this formulation does not deteriorate the eye gaze signal quality, as all the missing detection were because of simultaneous head and eye movements to fixate at the target. Lowering the regularization value (section ~\ref{MS_describe}) helps in detection of few of these movements but it increases the number of false alarms. A relevant field of application to this strategy would be the study of vergence eye movement as we have boosted the ability of eye trackers to study movements with small changes. Our study improves the precision of current video-based eye trackers by relying on multiple features of the human eye. The method is not without limitations, of course. First, it requires multiple calibration points in order, which include a series of changes in X-Y direction (refer to Figure~\ref{fig:calib}). It will require an extra effort for calibration design, though the present study does not answer the minimum calibration point changes required for proper iris calibration; we used 12 changes, and addressing the minimum number is recognized as future work. Second, the performance of our method falls in the case of blurred images as we rely on iris features for the velocity signal and on pupil edges for pupil position estimates. Lack of a sharp eye image is also a problem for many current video-based systems as well, but this can be solved with a higher-resolution camera and proper exposure time. Third, finding the precision matrix in Equation ~\ref{eq:3conv} is a time-consuming step that increases as the time series increase. For our short videos, it was not an impediment, but for general use using long series, we can incorporate a precision matrix using techniques like LU-decomposition~\citep{banachiewicz1938methode} or use small windowing blocks to speed processing. Finally, compression artifacts are still a problem in our method as mentioned in~\citep{Chaudhary_Pelz_2019} In summary, the main contributions of this paper are handling of spatial drift, a novel strategy that incorporates the two signals in different domains that are related by first-order derivative/integration (one noisy the other with temporal drift), a new calibration routine for iris calibration, a way to compute precision in smooth pursuit signals by signal detrending, and most importantly, a method for estimating gaze that allows for significant improvement of precision compared to current video-based eye-tracking methodology. At the same time, this method is also useful in tasks requiring high precision, such as the study of microsaccades, smooth pursuit, and even vergence eye movements. This methodology can be used with any eye tracker (P-CR, 3D based approaches, appearance-based models) that estimate the head compensated gaze position to improve its precision. It also gives a confidence value for each signal component, supporting further study and error analysis. \section{Acknowledgements} The authors want to acknowledge the contribution of our high school intern, Brian Cowburn, for helping hardware setup for synchronizing iPad display and the IRLED with a photo-diode setup. \newpage \bibliographystyle{ACM-Reference-Format}
{'timestamp': '2020-09-22T02:14:07', 'yymm': '2009', 'arxiv_id': '2009.09348', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09348'}
arxiv
\section*{Appendix A. Network Architecture and Training} For encoders $\text{Enc}_1$ and $\text{Enc}_2$ in simulation we use stride-2 convolutions with a $5\times5$ kernel. We perform 4 convolutions with filter sizes 64, 128, 256, and 512 followed by two fully-connected layers of size 1024. We use LeakyReLU activations with leak 0.2 for all layers. The translation module $T(z_1, z_2)$ consists of one hidden layer of size 1024 with input as the concatenation of $z_1$ and $z_2$ and output of size 1024. For the decoder $\text{Dec}$ in simulation we have a fully connected layer from the input to four fractionally-strided convolutions with filter sizes 256, 128, 64, 3 and stride $\frac{1}{2}$. We have skip connections from every layer in the context encoder $\text{Enc}_2$ to its corresponding layer in the decoder $\text{Dec}$ by concatenation along the filter dimension. For real world images, the encoders perform 4 convolutions with filter sizes 32, 16, 16, 8 and strides 1, 2, 1, 2 respectively. All fully connected layers and feature layers are size 100 instead of 1024. The decoder uses fractionally-strided convolutions with filter sizes 16, 16, 32, 3 with strides $\frac{1}{2}$, 1, $\frac{1}{2}$, 1 respectively. For the real world model only, we apply dropout for every fully connected layer with keep probability 0.5, and we tie the weights of $\text{Enc}_1$ and $\text{Enc}_2$. We train using the ADAM optimizer with learning rate $10^{-4}$. We train using 3000 videos for reach, 4500 videos for simulated push, 894 videos for sweep, 180 videos for simulated push with real videos, and 135 videos for real push with real videos. \section*{Appendix B. Ablation Study} To evaluate that the different loss functions while training our translation model, and the different components for the reward function while performing imitation, we performed ablations by removing these components one by one during model training or policy learning. To understand the importance of the translation cost, we remove cost $\mathcal{L}_{\text{trans}}$, to understand whether features $z_3$ need to be properly aligned we remove model losses $\mathcal{L}_{\text{rec}}$ and $\mathcal{L}_{\text{align}}$. We see that the removal of each of these losses significantly hurts the performance of subsequent imitation. On removing the feature tracking loss $\hat{R}_\text{feat}$ or the image tracking loss $\hat{R}_\text{image}$ we see that overall performance across tasks is worse. \begin{figure}[h!] \centering \includegraphics[width=0.95\textwidth]{plot/barablation.png} \caption{Ablations on model losses and reward functions for the reaching, pushing and pushing with real world demonstrations tasks. Across tasks, all components of the model are necessary for success.} \label{fig:allablations} \end{figure} \newpage \section*{Appendix C. Sample Videos} \subsection*{Reach Simulation} \begin{figure}[h!] \centering \includegraphics[width=0.9\textwidth]{diagrams/reach/reach6.jpg} \includegraphics[width=0.9\textwidth]{diagrams/reach/reach8.jpg} \caption{Example expert training demonstrations from different viewpoints with variations in color, distractor objects, and goal position.} \end{figure} \begin{figure}[h!] \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/reach/reachsrc16.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/reach/reachctx16.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/reach/reachtrans16.jpg}}\\ \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/reach/reachsrc21.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/reach/reachctx21.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/reach/reachtrans21.jpg}}\\ \caption{Example illustrations of demonstrations for a reaching task (top) being performed in a new context (middle), with the translated observation sequences (bottom).} \end{figure} \newpage \subsection*{Push Simulation} \begin{figure}[h!] \centering \includegraphics[width=0.9\textwidth]{diagrams/push/push0.jpg} \includegraphics[width=0.9\textwidth]{diagrams/push/push6.jpg} \caption{Example expert training demonstrations from different viewpoints with variations in distractor objects, start and goal position.} \end{figure} \begin{figure}[h!] \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/push/push2src.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/push/push2ctx.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/push/push2trans.jpg}}\\ \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/push/push6src.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/push/push6ctx.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/push/push6trans.jpg}}\\ \caption{Example illustrations of demonstrations for a pushing task (top) being performed in a new context (middle), with the translated observation sequences (bottom).} \end{figure} \newpage \subsection*{Sweep Simulation} \begin{figure}[h!] \centering \includegraphics[width=0.9\textwidth]{diagrams/sweep/sweep5.jpg} \includegraphics[width=0.9\textwidth]{diagrams/sweep/sweep7.jpg} \caption{Example expert training demonstrations from different viewpoints.} \end{figure} \begin{figure}[h] \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/sweep/sweep25src.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/sweep/sweep25ctx.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/sweep/sweep25trans.jpg}}\\ \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/sweep/sweep23src.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/sweep/sweep23ctx.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/sweep/sweep23trans.jpg}}\\ \caption{Example illustrations of demonstrations for a sweeping task (top) being performed in a new context (middle), with the translated observation sequences (bottom).} \end{figure} \newpage \subsection*{Striking Simulation} \begin{figure}[h!] \centering \includegraphics[width=0.8\textwidth]{diagrams/strike/strike1.jpg} \includegraphics[width=0.8\textwidth]{diagrams/strike/strike2.jpg} \caption{Example expert training demonstrations from different viewpoints.} \end{figure} \begin{figure}[h] \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/strike/strikesrc1.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/strike/strikectx1.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/strike/striketrans1.jpg}}\\ \small{Source Video} \hspace*{0.73cm} \vcenteredinclude{ \includegraphics[width=0.8\textwidth]{diagrams/strike/strikesrc2.jpg}}\\ \small{Target Context $o_0$} \hspace*{0.45cm} \vcenteredinclude{\includegraphics[width=0.145\textwidth]{diagrams/strike/strikectx2.png}}\\ \small{Translated Video} \hspace*{0.3cm} \vcenteredinclude{\includegraphics[width=0.8\textwidth]{diagrams/strike/striketrans2.jpg}}\\ \caption{Example illustrations of demonstrations for a striking task (top) being performed in a new context (middle), with the translated observation sequences (bottom).} \end{figure} \end{document} \section{Introduction} Given a set of parts and their relative positions in a product, the assembly sequencing problem is to find a sequence of collision-free motions that will merge the separated parts into the final assembly \cite{halperin2000general}. While the problem is PSPACE-hard in general~\cite{pspace}, efficient algorithms have been developed for restricted types of motions, which guarantee to find a valid assembly sequence when one exists. However, even under such restrictions, there may be exponentially many valid sequences and so the computational hardness remains for the task of choosing an optimal sequence (based on a desired measure). We focus on such a task in this paper -- finding a \textit{robust} assembly sequence, which we define as one having a high probability to succeed under small deviations from the planned motions. Such deviations arise in real scenarios where noise is introduced due to uncertainties in control and sensing. \begin{figure}[H] \vspace{-5pt} \centering \includegraphics[width=0.45\textwidth]{\RobustnessFiguresDir/Intro-robust.png} \caption{Examples of 3 highly-robust operations. In each operation one subassembly moves as a rigid body in the direction shown while the other one is fixed.} \label{fig:intro-robust} \vspace{-5pt} \end{figure} To provide some intuition about the problem and the effects of deviations, we present examples of assembly operations and their robustness levels, starting with highly robust ones in Figure \ref{fig:intro-robust}. Note that the poly-lines along which the subassemblies in this figure are mated are characterized by wide ``funnels'', where mechanical compliance can guide subassemblies into alignment. Together with an appropriate direction for mating, these motions guide the moving subassemblies into the correct final position. We contrast these operations to ones that are not robust in the next figure: \begin{figure}[H] \vspace{-5pt} \centering \includegraphics[width=0.45\textwidth]{\RobustnessFiguresDir/intro-not-robust.png} \caption{Examples of operations that are not robust, in which noise along the planned path (shown by the green arrow) can result in undesirable motions (represented by red dashed arrows). We assign operations (a) and (b) a score of 0.5 (out of 1), and operation (c) a score of only 0.14 (see text for how it is obtained). We provide an explanation for the low scores: In operation (a) any deviation of the moving part to the left would result in it sliding away from the target along the part that is below it. The mating direction aggravates the situation (a better one would bring the moving part from the North-Northeast). In operation (b), only a single direction can be used and a similar scenario can occur if the moving part deviates left. In both (a) and (b), a deviation to the right should still allow successful completion. In contrast, operation (c) has a particularly low success rate since a deviation either way would likely result in failure: Missing right would cause the moving part to rotate and settle in a configuration (shown by the red dashed line) that can only be recovered from by fully backing up. A deviation to the left could end up the same way, since recovering from such a deviation would entail some momentum to the right.} \label{fig:intro-not-robust} \vspace{-5pt} \end{figure} \begin{wrapfigure}{r}{2.7cm} \vspace{-15pt} \includegraphics[width=2.65cm]{\RobustnessFiguresDir/hex_assembly.png} \caption{Example of a final assembly.} \label{fig:hex} \vspace{-15pt} \end{wrapfigure} These are just a few examples out of the exponentially many possible operations for the assembly in Figure \ref{fig:hex}. Our task is to find assembly sequences with robust operations (like those in Figure~\ref{fig:intro-robust}) by avoiding difficult configurations of parts already assembled (like those in Figure~\ref{fig:intro-not-robust}) and choosing appropriate mating directions. In order to evaluate the robustness of assembly operations, we use a physics simulator, as we can exploit its immediate ability to capture the dynamics of the task, compared to analytic approaches (which would require handling potentially challenging intricacies, as we exemplify in Section~\ref{sec-clearance}). In particular, in this work we evaluate robustness by simulating object mating using a proportional feedback controller~\cite{franklin1994feedback} that moves an object along the assembly trajectory in the presence of actuation noise. In this case, robustness corresponds to the ability of the planned motion to tolerate noise. Since the noise we add is random, multiple simulations are required to get the score, rendering it computationally burdensome. The effect on run time is compounded by the fact that finding a good sequence involves scoring a myriad of candidate operations. Although planning robust assembly sequences can be performed offline for a given assembly, efficient algorithms can facilitate efficient design for assembly (DfA), where small changes in geometry can increase robustness and planning is executed inside an optimization cycle. We therefore introduce a convolutional neural network (CNN) that has potential to efficiently identify high scored assembly operations, given their visual representation, using binary classification. We plan assembly sequences by obtaining a set of possible operations at each step using geometric planning and then greedily selecting the most robust one among them using the CNN. In case the CNN classifies all available operations as \textit{not} highly robust, we fall back on the physics simulator to choose the best one (though this rarely occurred in our experiments). While our proposed method handles planar assemblies, where the motions are one-step translations (like those in Figures~\ref{fig:intro-robust}~and~\ref{fig:intro-not-robust}), it is an initial step towards handling spatial assemblies. The planar case already has a high combinatorial complexity and raises interesting challenges, as we illustrate in Section \ref{sec:hardness}. \textbf{Contribution.} We present the Robust Assembly Planning (RAP) algorithm, which takes a planar assembly and returns a robust two-handed assembly sequence using one-step translations (or determines that no feasible sequence exists under such motions). RAP also considers assembly operations that are not linear (i.e., ones which bring together more than one part into an existing subassembly). \input{Sections_2-4.tex} \section{The RAP Algorithm}\label{sec:the-algorithm} We first give an overview and then explain how the planning, physics simulation, and CNN are used. Given a planar assembly $A$, we wish to find an assembly sequence for it with the best robustness score. Due to the hardness of optimizing sequences we use a greedy approach, which selects the most robust assembly operation available at each step. To this end, we first construct the NDBG for $A$ and then apply Algorithm~\ref{alg:RAP} on the complete assembly. The algorithm recurses on subassemblies introduced by partitions, following the assembly-by-disassembly approach. \vspace{-5pt} \begin{algorithm} \SetKwInOut{Input}{Input} \SetKwInOut{Output}{Output} \Input{Subassembly $S \subseteq A$} \Output{Assembly sequence for $S$} P $\gets$ List of feasible partitions for $S$ obtained from NDBG \label{alg1:ndbg} \If {no feasible partitions exist} { return failure } $(S_1, S_2, \overrightarrow{d}) \gets$ \textbf{select\_best\_partition}(P) \label{alg1:scoring} Output $(S_1, S_2, \overrightarrow{d})$ Continue recursively on $S_1$ and $S_2$ (when more than a single part remains) \caption{A generic greedy approach for finding a robust assembly sequence.} \label{alg:RAP} \end{algorithm} \vspace{-5pt} Section~\ref{sec-NDBG-query} explains how the NDBG is used (line~\ref{alg1:ndbg}). As for the procedure \textbf{select\_best\_partition} (line~\ref{alg1:scoring}), we have two implementations: an efficient CNN-based one, which we use for RAP, and baseline that only uses the physics simulator to score partitions (returning the one with highest score). We describe the former in Section~\ref{sec-scoring}, providing more details on the simulator in Section~\ref{sec-sim}, and compare the two implementations with experiments in Section~\ref{sec-exp}. \begin{comment} Given a planar assembly, the algorithm first constructs an NDBG for it and then continuously uses it to grow an AND/OR graph representing various disassembly sequences, following the assembly-by-disassembly approach. Assembly operations that arise in the sequences are scored in order to find the most robust sequence. \tzvika{Maybe it should be made clear how scores are saved in the AND/OR tree in the preliminaries} \end{comment} \subsection{The Use of the NDBG} \label{sec-NDBG-query} Since the motions we allow are one-step translations, a single angular parameter representing the direction of the translation defines the motion. Our NDBG is therefore a unit circle ${\cal S}^1$ that is decomposed into an arrangement of vertices and arcs. To construct it we use the implementation of Fogel and Halperin~\cite{fogel2013polyhedral} (adapted to 2D), which is performed once at the beginning of the algorithm. To obtain a choice of possible partitions for a given subassembly $S \subseteq A$, we examine each cell in the NDBG and its associated DBG (restricted to $S$). As outlined in Section~\ref{sec:ndbg}, each DBG encodes all possible partitions for the directions of motion represented by the cell. In order to keep the overall running time polynomial, we consider only a single partition per DBG (out of a potentially exponential number, e.g., when no part is blocked by another part in some direction). This entails choosing two subassemblies, $S_1, S_2 \subset S$, which is done arbitrarily among the valid options, and a direction, for which we have the freedom of choice only when the cell is an arc of ${\cal S}^1$. Such a cell represents a range of directions along which $S_1$ and $S_2$ can be mated and we select the middle of that range. This is a heuristic, which in many cases would result in a large clearance for the assembly operation, relative to other directions in the range.\footnote{For this to hold, adjacent NDBG cells that admit the same subassemblies in their partitions need to be merged. Indeed this is what our algorithm does. We omit the details.} While experiments mostly support this choice of direction, a more sophisticated selection can be considered in future work (e.g. by learning it as well). In Section \ref{sec-clearance} we further discuss clearance as a robustness measure. We make two remarks on the restriction of one partition per DBG: First, our approach remains complete, as all directions are considered. Another fact that remains is that the space of feasible sequences is still potentially exponential. What reduces it further to a polynomial one is the greedy selection of the best partition. \subsection{Scoring and Selecting Partitions} \label{sec-scoring} As a preprocessing step, the CNN is trained on examples that are scored by the simulator and learns to classify operations as either \textit{high}, i.e., having a score in the range [0.95,~1], or \textit{not high}. Given a list of assembly operations as an argument to \textbf{select\_best\_partition} in the main algorithm, we first classify them using the CNN. If there are operations classified as \textit{high}, we choose the one with the highest \emph{confidence}, as measured by the softmax output of the network~\cite{geifman2017selective}. Otherwise, we resort to the simulator, scoring all partitions with it, and choose the one with the highest score. While a finer output from the CNN might be more desirable, we find that our use of binary classification is suitable, as the simulator does not need to be queried in almost all our experiments (see Section~\ref{sec-exp}). \subsubsection{Clearance as an Attempted Analytic Robustness Measure}\label{sec-clearance} In this section we introduce clearance, an alternative \textit{analytic} scoring method, and present its pitfalls. We define this score as the average minimum distance between the subassemblies during the mating motion. Intuitively, a higher clearance should minimize physical interaction between subassemblies that could hinder the success of the operation under noise. Indeed, we observe an overall positive correlation between this score and the simulator score, but we also find that it can mislead, as we show in Figure~\ref{fig:clearance}. While (d) has the highest clearance score among the four examples, it has the lowest simulator score. A deviation of the moving part to the right that brings the marked edges in (d) into contact, would result in an almost unrecoverable slide away from the target. This possible failure is not captured by clearance, as (c) has a slightly lower clearance even though its shape makes it robust to similar failures. Similarly, if we had to decide between (a) and (b) based on clearance, we would also end up forgoing the robust operation for one that is not. In this case, the part above the square in (a) reduces clearance, but allows the subassembly to slide to the correct place in case it misses to the left and touches the top rectangle. The above cases exemplify just a few intricate details that would have to be accounted for in an analytic solution and therefore encourage the use of a simulator. \begin{figure}[H] \vspace{-4pt} \centering \includegraphics[width=0.3\textwidth]{\RobustnessFiguresDir/clearance.png} \caption{Examples where clearance does not correlate with robustness.} \label{fig:clearance} \vspace{-4pt} \end{figure} \subsection{Time Complexity} \label{sec-complexity} Let $n$ be the number of parts in the input assembly $A$ and $q$ be the maximal number of edges in a single part. The NDBG has $O(n^2)$ cells and we compute it once in the beginning using $O(n^2(\log n +q^2))$ time~\cite{halperin2000general}. In line~\ref{alg1:ndbg} we obtain partitions by computing the strong components of each cell's DBG. This allows obtaining a partition using $O(n^2)$ time per cell, resulting in a total number of $O(n^2)$ partitions (one per cell) for the subassembly. In line~\ref{alg1:scoring} we score the partitions by feeding their images to the CNN and (if required) by simulating the assembly operations they represent. Let $t(n, q)$ be the time bound for scoring a single partition in this manner (a polynomial that mainly depends on the simulator's internals). We thus require $O(n^2(n^2+t(n, q)))$ time for lines~\ref{alg1:ndbg}-\ref{alg1:scoring}. These lines are repeated exactly $n-1$ times, as each time they run an assembly operation is chosen and that is the length of the sequence. The overall run time is therefore $O(n^2q^2+n^3(n^2+t(n, q)))$. \section{Physics Simulation} \label{sec-sim} To evaluate robustness, we use the Box2D physics engine \cite{catto2011box2d} to simulate a controlled assembly motion of two objects with actuation noise. We start the simulation when the two objects are separated, and apply translational forces on one object to drive it to an assembled configuration, while the second object is held fixed. Rotational forces are also applied, though only for correcting the orientation of the moving object. We used a proportional feedback controller~\cite{franklin1994feedback} to track a linear path connecting the object's initial position and the goal (see~Figures~\ref{fig:intro-robust}~and~\ref{fig:intro-not-robust}). We add actuation noise at each control loop iteration as follows: Let $F$ be the correct force that the controller should currently apply. We add to $F$ a random noise component drawn uniformly from the interval $[-\eta\left\lVert F\right\rVert, \eta\left\lVert F\right\rVert]$ on the axis perpendicular to $F$ and output the sum as the noisy force, resulting in a stochastic system. Currently we set $\eta=9$ as it gives a reasonable amount of noise when visualizing the operations while also resulting in a sufficiently varied distribution of robustness scores. We measure the robustness of the operation as the success rate of the controller in driving the object sufficiently close to the goal within a fixed time, after performing 100 trials. At the beginning of each trial, we place the moving object such that it is completely outside of the bounding box of the static object (aligned with the direction of motion) and is also located at least a fixed distance away from it. \section{Neural Network} \label{sec-NN} Using a physics simulator to predict the success probability of an assembly operation, as outlined in the previous section, adds significant computational overhead to the planning algorithm. We hypothesize, however, that in a practical setting, it is possible to exploit similarities between different assemblies to reduce the computational burden. For example, it may be that peg-in-hole type assemblies are particularly difficult for our robot, and we can identify such structures and avoid them without requiring extensive simulations. Here, we propose a general approach for identifying such structural properties by using supervised learning~\cite{Bishop2006Pattern}. In our approach, we generate $N$ random assembly operation instances, $x_1, \dots, x_N$. A single assembly operation instance $x_i$ includes the initial, unassembled, position of two subassemblies, and their assembled position. For each instance $x_i$, we use the physics simulator to obtain a robustness score $y_i$. We propose to use supervised learning to learn a mapping $f$ from some features of the assembly instance $\phi(x)$ to their score $y$, such that during planning, we can use $f$ instead of the physics simulator to obtain robustness scores. Selecting features that are relevant to the robustness score is not trivial. Here, we build on the recent success of deep convolutional neural networks (CNNs;\cite{goodfellow2016deep}) in automatically learning features from image input. We observe that in a 2D setting, an image of the subassemblies contains all the geometric information that is input to the physics simulator, and is therefore sufficient, in principle, for a CNN to decode features relevant to predict robustness. For each instance $x_i$, we therefore generate two images (see Figure~\ref{fig:CNN}): \textbf{start image}, where the subassemblies are in their initial position, and \textbf{goal image}, where the subassemblies are assembled. These images are input to a CNN, which predicts whether the operation has high robustness. \subsection{CNN Architecture} CNNs have been previously used for various geometric tasks such as shape recognition~\cite{su2015multi}, pose estimation~\cite{xiang2017posecnn}, and evaluating robotic grasp success~\cite{mahler2019learning}. Here, we follow a similar approach, and design a CNN for evaluating assembly robustness, as described in Figure~\ref{fig:CNN}. Our input is represented as a 2-channel $64 \times 64$ image, where each channel corresponds to a grayscale rendering of the start and goal images. In principle, this image contains all the information about the planned trajectory and the geometry of the parts involved, and we expect that a CNN-based architecture would be able to extract this information to predict a robustness score. \begin{figure}[H] \vspace{-5pt} \centering \includegraphics[width=0.45\textwidth]{\RobustnessFiguresDir/CNN.png} \caption{CNN architecture for predicting robustness. Given $64 \times 64$ grayscale images of the starting position and goal position of two subassemblies, the network predicts whether the assembly operation is highly robust or not (see text for details). The CNN is composed of four convolution layers with $4\times 4$ kernels, ReLU activations and max-pooling, followed by three fully connected layers with ReLU activations, and a final linear connection to the output layer.}\label{fig:CNN} \vspace{-5pt} \end{figure} We use the popular CNN architecture of several convolutions and pooling layers, followed by fully connected layers with dropout~\cite{goodfellow2016deep,lecun1998gradient,krizhevsky2012imagenet}, as depicted in Figure~\ref{fig:CNN}. For the output, we found that the numerical value of the robustness score was hard to predict accurately, and instead we quantize the score into 2 classes: \textit{high}, corresponding to the score range [0.95, 1], and \textit{not high}. We trained our networks in PyTorch~\cite{paszke2017automatic}, using Adam~\cite{kingma2014adam} with default parameters to optimize the cross-entropy loss~\cite{goodfellow2016deep}. \begin{figure}[H] \vspace{-4pt} \centering \includegraphics[width=0.365\textwidth]{\RobustnessFiguresDir/assemblies.png} \caption{The assembly tasks in our experiments.} \label{fig:assemblies} \vspace{-4pt} \end{figure} \subsection{Dataset Normalization} In our experimental setting, gravity is not considered and therefore the robustness score is invariant to the orientation of the operation as a whole. We therefore preprocessed the input images by rotating them such that the moving subassembly translates downward, which resulted in a small performance gain. In the absence of such symmetry, similar gains can be obtained by increasing the data size. \section{Experiments} \label{sec-exp} \begin{comment} Tables: NN accuracies Main algorithm table: Columns: Assemblies + average Rows for robustness: Sim score, NN score, Optimal score, Random score Separator row Time comparison (Num sim calls and work not really interesting here Inside simulator section need to say that optimization save an average of X trials. Can discuss rectilinear and its sim calls separately) \end{comment} We now evaluate the prediction accuracy of the CNN and RAP's run time and sequence robustness. Figure~\ref{fig:assemblies} shows the assembly tasks in our experiments and the number of parts in each of them. We chose to analyze these puzzle-like assemblies due to their highly constrained nature, which increases the interaction between parts and requires careful planning. \subsection{Performance of the CNN} One question that arises when using a machine-learning approach to predicting robustness is how well the trained model generalizes to assemblies not in the training data. We investigate this question by performing 6-fold cross-validation on the data obtained from the assemblies in Figure~\ref{fig:assemblies}, consisting of 40,000 examples for each of them.\footnote{We obtain many examples for each assembly using its NDBG by exhaustively considering all possible partitions for each subassembly, as opposed to choosing just one like in RAP's online phase (i.e. we generate all possible sequences).} We test the CNN model on data for each one of the assemblies in turn, while using the rest for training. In Table~\ref{nn-table} we report the accuracy in predicting robustness. These results suggest that the CNN can indeed generalize and predict robustness for assemblies it had not seen during training. Thus, with sufficient training data obtained off-line, we can learn an effective model for predicting robustness during online planning, thereby reducing planning time. \begin{comment} Using the datasets described above, we evaluate our CNN model using an all-but-one approach, i.e. a different CNN is evaluated on each assembly such that it is trained on all assemblies other than the one it is evaluated on. \end{comment} \begin{comment} For each assembly all assembly operations were exhaustively generated, as described in section \tzvika{6 B, ref}, resulting in the following number of examples for each of them: \end{comment} \begin{table}[H] \vspace{-3pt} \begin{tabular}{rccc} \hline \textbf{Test Assembly} & \multicolumn{1}{l}{\textbf{Accuracy}} & \multicolumn{1}{l}{\textbf{Low Robustness}} & \multicolumn{1}{l}{\textbf{High Robustness}} \\ \hline Hexagon & 84.79 & 93.17 & 69.87 \\ Mixed Square & 84.73 & 77.77 & 89.48 \\ Pentagons & 74.93 & 94.17 & 72.09 \\ Rectilinear & 82.64 & 80.70 & 90.99 \\ Grid & 81.70 & 70.98 & 90.35 \\ Triangles & 93.13 & 88.77 & 96.41 \\ \hline \end{tabular} \caption{Overall accuracy of our CNN model in predicting robustness alongside individual class accuracy. Each row shows results for a CNN trained on examples from all assemblies other than the one it was evaluated on.} \label{nn-table} \vspace{-8pt} \end{table} \subsection{Performance of RAP} \subsubsection{RAP vs Simulator-Only Baseline} For each assembly task we compare the time taken to find a sequence and its robustness score using RAP and the baseline. Regardless of the approach used, sequences are evaluated using the simulator (as it is our "ground truth"). Also note that when applying RAP on an assembly, we use the CNN that has not seen the data for that assembly in training. \begin{figure*}[!t] \centering \includegraphics[width=0.85\textwidth]{\RobustnessFiguresDir/seqs.png} \caption{Two sequences each for the \mixedSquare assembly, (a) and (b), and the \rect assembly, (c) and (d). For each of them the bottom sequence is returned by RAP, while the top one is an arbitrary one with low robustness. Individual motion scores are shown for non-robust steps (i.e., with a score less than 0.95). Total robustness score $R$ is the product of individual scores. Sequence (d) shows how crucial it is to consider non-linear sequences, as the operation that results in the second to last subassembly (before the S-shaped part is inserted) would be a tight insertion if we only allowed a single part to be inserted.} \label{fig:seqs} \vspace{-19pt} \end{figure*} The average run time on all examples for the simulator-only baseline is 21.58 seconds (with low variance) while for RAP it is 2.38 seconds. In all but the \rect assembly task RAP does not query the simulator, resulting in an average run time of 1.4 seconds for these tasks. In the \rect example, the search leads to a subassembly for which the CNN classifies all possible operations as not robust (even though one is), leading to a simulator query for them, which results in a run time of 7.0 seconds. Nevertheless, even in this case RAP improves run time by more than 3-fold (compared to 10-fold overall). As for robustness, the scores end up very close: the average difference between the baseline and RAP is only -0.005 (scores for RAP are shown in Figure~\ref{fig:ScoreComparison}). These results indicate that the time improvements resulting from using a CNN within RAP do not come at the expense of robustness. \subsubsection{Evaluating Robustness} \begin{figure}[!b] \vspace{-18pt} \centering \includegraphics[width=0.51\textwidth]{\RobustnessFiguresDir/greedy_comparison.png} \vspace{-15pt} \caption{Comparison of average scores of 50 random sequences, scores of sequences obtained by RAP, and the optimal ones for the different assembly tasks. Indeed our learning-based approach offers significant robustness gains, which are close to optimal, using a fraction of the running time required by the optimal procedure.} \label{fig:ScoreComparison} \vspace{-1pt} \end{figure} For this evaluation we must first note that absolute robustness scores do not necessarily indicate the quality of the optimization, since an assemblies' sequences can naturally tend towards a certain level of robustness. For example, there might be unavoidable steps that are not robust, such as the C-shaped part in the \rect assembly, which induces a peg-in-hole scenario (see "unavoidable" examples in (c) and (d) in Figure~\ref{fig:seqs}). To take such inherent difficulties into account, we compare the sequences obtained by RAP to both optimal and many random sequences. For the purpose of the comparison we fix the possible operations available for each subassembly, i.e. we always use the NDBG as we describe in Section~\ref{sec-NDBG-query}, which maintains consistency in the returned partitions. We find optimal sequences using an exhaustive search that considers all possible partitions for each subassembly and scores all of them using the simulator (a process which is more than 100 times slower than RAP). As for the random sequences, in which each next step is selected uniformly at random, we find the average score of 50 such sequences. We present the comparison in Figure~\ref{fig:ScoreComparison}. In Figure~\ref{fig:seqs} we present sequences for two assemblies, comparing two obtained by RAP alongside two with a low robustness score. For both assemblies, the sequence with the lower score introduces configurations that hinder the successful insertion of parts, with a clear negative impact on robustness. The impact in the \rect example is especially severe, since four more peg-in-hole operations are performed compared to the only (unavoidable) one in the sequence returned by RAP. We observe similar benefits of RAP in the other instances as well. \begin{comment} The score in the SIM+NN case is evaluated using the simulator only. As the score is stochastic, there are small variations between simulator scores in different runs which can result in different sequences. The displayed scores are therefore the average of 50 runs. \end{comment} \section{Conclusions and Future Work} \label{sec-conc} In this work, we learned a robustness metric by using a physics simulator to provide the ground truth labels. A recent study noted the difficulty of such CNNs in capturing geometric properties such as coordinate transforms~\cite{liu2018intriguing}. We conjecture that a special purpose architecture would further improve our results. Even after a sequence is fixed, individual motions can be optimized. As we pointed out, within one NDBG cell, one can typically choose from an infinitude of directions. In the current work we choose the middle direction, which is well defined in the one-dimensional motion space. Selecting a good direction in general is in itself an interesting problem, requiring first to define what makes a direction better than others. More generally, one could replace a one-step translation with an arbitrary path, e.g. to rely on compliant motion to further improve robustness. \begin{comment} many researchers consider only assembly parts in their model and assume them as free-flying objects that can move in the space among surrounding obstacles, thus avoiding the complications of manipulating parts by robots within tight spaces around the assembly. (from taxonomy paper) \end{comment} \section{Related Work}\label{sec:related} \subsection{Assembly Planning and Optimization} Assembly planning is a well-studied problem in manufacturing and robotics. Some early planners employ a potentially exponential running-time generate-and-test approach, which enumerates all possible operations and tests their feasibility~\cite{gen-and-test} while others pose questions to a human expert in order to establish precedence between operations~\cite{user-queries}. A pioneering work by Wilson and Latombe~\cite{wilson1994geometric}, on which our geometric planner is based, introduces the \textit{non-directional blocking graph}, which uses geometric reasoning and examines assembly operations in the space of the allowable assembly motions. This approach avoids the inherent combinatorial trap and leads to polynomial time algorithms for motions such as one-step translations and infinitesimal rigid motions~\cite{halperin2000general}. Given the algorithmic success in finding feasible assembly sequences, a natural goal is to find ones that meet desired properties or optimality criteria. Goldwasser et al.~\cite{goldwasser1996complexity, goldwasser-thesis} show that optimizing assembly sequences under simple motions can be NP-hard even to approximate (we list some of their cost measures in Section~\ref{sec:hardness}). Assembly optimization is therefore typically solved with heuristic techniques. As the subject is vast, with many possible optimization criteria~\cite{constraints-survey}, we refer to the following surveys:~\cite{jimenez2013survey, ghandi2015review}. \subsection{Robustness} A great deal of work revolves around planning and executing fine motions to handle challenging peg-in-hole style assembly tasks (e.g~\cite{kim2012hole-tight-task, tang2016autonomous-tight-task}). We, on the other hand, seek to plan inherently robust sequences that minimize difficult tasks during assembly. We mention a few works that plan sequences using quality measures reminiscent of ours. Heger~\cite{heger2008generating} focuses on the assembly environment by considering planar assemblies inside a constrained workspace, where robots would be operating. The work combines symbolic and motion planning to generate sequences and greedily optimizes them for two relevant measures: clearance along the path around the part being inserted and the reachability of its docking locations in each step. Moving the partial assembly between steps is allowed for improving these measures. Wan et al.~\cite{wan2018assembly} optimize sequences based on a score for the ease of 3D part insertion derived from contact normals (ignoring potential disturbances that can occur along the motion). Anders et al.~\cite{anders2018reliably} also learn from simulation to plan pushing motions for planar objects. They approach uncertainty with conformant planning, in which actions are sequenced to guarantee a successful configuration without intermediate sensing. They acquire a belief-state transition model for pushing squares into an arrangement by training a random-forest regressor. \begin{comment} As for robustness, Previous work relevant to assembly planning falls into two main categories: approaches that tackle the problem as a sequencing problem on an abstract symbolic level, and ones that consider fine-grained motions of the robots involved \end{comment} \subsection{Learning} The use of neural networks in assembly planning has been explored in~\cite{hong1995neural,sinanouglu2005assembly,chen2008three}. In these works, supervised learning was used to learn a mapping from geometric features in an assembly to a complete assembly sequence, with the goal of replacing the search computation with a learned heuristic. In our work we use neural networks differently: we use them to replace physics simulation in predicting the robustness of an assembly operation, from a visual representation of the proposed assembly. We incorporate the predictions from this neural network into the assembly planning framework. Neural networks have been used to learn controllers for assembly tasks, using inverse models~\cite{kim2000neural}, and reinforcement learning~\cite{thomas2018learning}. Neural networks have also been used for solving various planning problems in robotics, such as motion planning~\cite{pfeiffer2016perception,ichter2017learning}, grasping~\cite{mahler2019learning}, and pose estimation~\cite{xiang2017posecnn}. In this work, we apply deep CNNs to learning the robustness of an assembly operation, namely the motion that puts two subassemblies together to form one larger subassembly. \begin{comment}{ From motion space approach: Recently it has been shown that several variants of cost measure optimization in assembly planning are hard, even in their approximate versions [13], [15]. We cite here one hardness result from [14], for a problem that at first glance seems very simple.} \end{comment} \section{Preliminaries}\label{sec:prelim} \subsection{Assembly Planning} An \textbf{assembly} is a collection of bodies (also called parts) in some given relative placements, such that no two bodies overlap. A \textbf{subassembly} is a subset of the bodies composing an assembly $A$ in their relative placements in $A$. We say that two subassemblies are \textbf{separated} if they are arbitrarily far apart from one another. Given an assembly $A$, an assembly operation is a motion that merges $s$ ($s \geq 2$) pairwise separated subassemblies of $A$ into a new subassembly of $A$. During this motion, each subassembly moves as a single rigid body and no overlapping between bodies is allowed.~\footnote{As is common in \emph{assembly planning} we allow motion of parts in contact, such as one part sliding over the other, but forbid overlap of the interior of parts during the motion.} In this paper the assembly operations are \textbf{two-handed}, i.e., every operation merges exactly two subassemblies. The reverse of an assembly operation is a \textbf{partitioning} operation. We denote both types of operation as a tuple $(S_1, S_2, m)$, where $S_1, S_2 \subset A$ are the subassemblies merged/partitioned by the motion $m$. An \textbf{assembly sequence} is a total ordering on assembly operations that merges the separated parts composing an assembly into this assembly. A common approach in assembly planning is \textbf{assembly-by-disassembly}, whereby a \textit{dis}assembly sequence is obtained and then reversed. As the final assembly configuration is the most constrained, the approach reduces the search space and naturally offers valid operations. Disassembly consists of partitioning, first the input assembly $A$ into subassemblies and then, recursively, the resulting subassemblies that are not individual parts. When only considering geometric feasibility, and assuming that the parts are rigid, the sequences are symmetric, though this is not true if we also care about robustness (e.g., the peg-in-hole scenario). Nevertheless, the approach is suitable for our setting, since we treat partitioning operations as the respective assembly operations when evaluating robustness. Due to this interchangeability of assembly and disassembly, we sometimes simply use the term \textbf{sequence}. \subsection{The Motion Space Approach}\label{sec:ndbg} To complete the description of the disassembly process, we give an overview of the partitioning procedure using the so-called \textbf{motion space approach}~\cite{halperin2000general}. The \textbf{motion space} is defined to be the space of parametric representations of all allowable motions for partitioning operations: every point in it uniquely defines a path of the subassemblies moved by an operation. A key concept in this approach is the \textbf{directional blocking graph} (DBG)~\cite{wilson1994geometric}. Given a specific motion, a DBG is a directed graph that represents the blocking relation between parts: each node represents a part and an edge from part $A$ to part $B$ exists if applying the motion on part $A$ results in a collision with part $B$ (see Figure~\ref{fig:dbgs}). Given a DBG, it is sufficient to compute its strongly connected components in order to find a valid partition that uses this motion (or determine that no such partition exists, as is the case when the DBG is strongly connected). \begin{figure}[H] \vspace{-5pt} \centering \includegraphics[width=0.335\textwidth]{figures/dbgs-shorter.pdf} \caption{DBGs for two directions used for one-step translation~\cite{halperin2000general}.} \label{fig:dbgs} \vspace{-6pt} \end{figure} An important insight is that a single DBG can represent many motions, as the blocking relations are not necessarily affected by small changes to a given motion. This fact allows for decomposing the motion space into regions called \textbf{cells}, such that all motions in the same cell induce a single DBG. The decomposed motion space is called the \textbf{non-directional blocking graph} (NDBG)~\cite{wilson1994geometric}. Once an NDBG is obtained for a given assembly, partitioning it involves finding a feasible partition for any of the DBGs (i.e., motions) it contains, meaning the NDBG captures all the geometric information required for partitioning. Its structure, particularly the number of cells in the decomposition, is therefore a critical run-time factor that depends on the type of allowed motions. For one-step translations (in both 2D and 3D) this number is polynomial in the number of parts in the assembly (and their complexity), which allows for finding an arbitrary assembly sequence in polynomial time (exact bounds for our setting appear in Section~\ref{sec-complexity}). For more details on NDBG construction and the application of the motion space approach for a few families of motions see~\cite{halperin2000general}. \section{Problem Statement} \label{sec:problem_statement} Given a planar assembly with $n$ parts, we would like to find the most robust two-handed sequence for it, where the motions are one-step translations, such as those in Figure~\ref{fig:intro-robust}. To evaluate a sequence for robustness we use the simulator to score the individual assembly operations in it, resulting in the scores $r_1, \ldots, r_{n-1} \in [0,1]$ (note that a two handed sequence for $n$ parts always has $n-1$ steps). As we define the robustness of a single operation as its success probability under noise, the score we assign to the whole sequence is the product of these individual scores, $R \vcentcolon= \prod r_i$, and our goal is to find a sequence that maximizes it. As the search space involved here is potentially exponential, we restrict it to a polynomial one by greedily choosing assembly operations and in a few other ways, which will be described in the sequel. \section{The Hardness of Finding Optimal Sequences} \label{sec:hardness} In this section we illustrate the hardness of finding optimal sequences by considering a generic cost function, which takes an assembly sequence and returns a real value as its cost. \begin{proposition*} Finding an optimal assembly sequence is NP-hard. \end{proposition*} \begin{proof} We give a reduction from the PARTITION problem, which is: given $n$ positive integers $a_1, \ldots, a_n$, decide whether they can be partitioned into two subsets whose sums are equal. Given such an instance $I$, we define an assembly $A$ to be a row of $n$ axis-aligned rectangles with the same height, where the width of rectangle $i$ is $a_i$. We define a cost function that only takes into account the last operation, which merges two subassemblies, $S \subset A$ and $A \setminus S$, into the final assembly: The cost is the absolute difference between the sum of the widths of the rectangles in $S$ and the corresponding sum for the rectangles in $A \setminus S$. Clearly, under this cost function $I \in$~PARTITION if and only if the optimal cost of assembling $A$ is 0. \end{proof} A possible motivation for the cost function used is a desire to have the weights of the two subassemblies be close for balance reasons. Note that PARTITION was also used to show the NP-hardness of finding a feasible sequence for a planar rectilinear block puzzle, where each block is allowed to move multiple times using translations that are also rectilinear~\cite{chazelle1984complexity}. More NP-hard (dis)assembly optimization goals under one-step translations include minimizing the number of directions used to mate subassemblies and minimizing the number of parts that need to be removed from an assembly in order to remove a key part~\cite{goldwasser-thesis}. These hardness results motivate us to follow an approximate solution to robust assembly sequencing, which we describe next.
{'timestamp': '2020-09-22T02:15:59', 'yymm': '2009', 'arxiv_id': '2009.09408', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09408'}
arxiv
\section{INTRODUCTION}\label{introduction} \indent The problem of path finding and scheduling of agents over a transportation network attempts to identify paths for the agents to move from their defined start position to their destination position without colliding with any other agent. Collision is defined to occur when two objects occupy the same edge or vertex at the same time. Most of the earlier works have been for point sized agents, which take unit travelling time across nodes of the network. The problem has been attempted using search based approaches using variants of A*~\cite{Standley2011,Silver2005}, Conflict Based Search~\cite{Sharon2015,Felner2018,Boyarski2015}, Propositional logic~\cite{Surynek2019} etc. The problem has also been addressed in a modified form in problems like Automated Guided Vehicle (AGV) routing~\cite{Ling2002} and Vehicle Routing~\cite{Bodin1983}. The variations being defined in terms of constraints imposed on the movement, the characteristics of the moving agents etc. \\ \indent Approaches for Multi Agent Path Finding (MAPF) while considering the dimensions of the agents have also been attempted where the agents are variously termed as large agents ~\cite{Li2019}, multi-sized agents ~\cite{Harabor2008}, train agents ~\cite{Atzmon2019} and spatially extended agents~\cite{shivashankar2009}. Real world versions of the problem includes Convoy Movement Problem~\cite{Chardaire99,Ramkumar2015,Khemani2012,Thomas2008}, Train Scheduling~\cite{Bettinelli2017,Wang2018} etc. MAPF for spatially extended agent is more challenging than point objects as (\textit{i}) At a given time instance, spatially extended agents may occupy multiple edges of a road network, (\textit{ii}) Edge transitions are durative and equals the time taken by the complete length of the agent to cross over, (\textit{iii}) Conflicts can occur on edges when two agents cross over in opposite directions, or one overtakes another in the same direction. Conflicts can also occur on vertices when two agents cross over.\\ \indent In a new approach to the problem, eXtended Conflict Based Search with Awareness (XCBS-A) \cite{Thomas2018} was proposed to handle multiple conflicts simultaneously thereby leading to faster convergence to the solution. To identify sets of mutually conflicting agents, the paper proposes a new spatio-temporal data structure namely, Temporal Occupancy (T.O.) Graph. The conflict resolution strategy is based on awareness of other agents plans. In this approach, the search space is maintained as a Constraint Tree (CT); exploration of any node of the CT leads to a maximum of $i^j$ child nodes being generated, where $j$ is the number of conflicting blocks and $i$ being the number of agents per block, resulting into a huge search space. \\ \indent The first contribution of this paper is a theoretical evaluation of XCBS-A and experimental evaluation of its performance in terms of variances in agent, road and plan characteristics. To prove the claim of a distributed algorithm we evaluated the algorithm by distributing the agents on multiple machines and compared performance. Our next contribution is a methodology for reducing the search space, where we only add selective CT-nodes to the Open Set to be explored and retain the remaining in a Potential Set; three heuristic functions are defined to extract the nodes from Potential Set into the Open Set and the approach is empirically evaluated for efficacy.\\ \indent As our third contribution in this paper, we address the second concern of XCBS-A namely optimality. XCBS-A results in suboptimal solutions primarily because it assumes plans of other agents in a block to be fixed, down the branch of the CT. We propose a revision to this approach and call it as XCBS-LA i.e. XCBS with Local Awareness. We prove that the algorithm guarantees optimality and completeness. \\ \indent This paper is organised to include a brief overview of related work in Section \ref{related_work}, we then define the terms used in the paper in Section \ref{terminology}. Sections \ref{xcbsa}, \ref{xcbsa-theoretical} \& \ref{xcbsa-experimental} cover a description of the XCBS-A algorithm, theoretical analysis and empirical evaluation. In Section \ref{xcbsa-eff}, we propose the heuristics for reducing the search space and bring out the XCBS-LA algorithm in Section \ref{xcbsla}. The conclusions drawn from the effort have been covered in Section \ref{conclusion} of the paper. \section{RELATED WORK}\label{related_work} \subsection {Multi Agent Path Finding (MAPF)} The MAPF problem has been handled in various varieties for point based objects. One of the notable work was the approach of Conflict Based Search~\cite{Sharon2015} which proposed an optimal, complete path planning solution for multiple agents using a two level search on a Constraint Tree. A low level planner would find consistent plans for individual agents satisfying constraints imposed on each of them individually. A high level planner then would search the Constraint Tree for valid (non-conflicting) solutions. There have been several variations and extensions to the approach. Some of the notable ones include meta-agent based CBS~\cite{Sharon2012} in which agents with multiple conflicts are grouped together. Another approach is the Improved Conflict Based Search (ICBS)~\cite{Boyarski2015} in which plans were restarted for merged agents and conflicts were prioritised as cardinal, semi-cardinal and non-cardinal cases and handled accordingly. Another complete algorithm for multi-agent planning was the Push and Rotate approach~\cite{De2014} where conflicting agents on a biconnected graph were de-conflicted for plan generation by executing push and rotate actions, leveraging the concept of bridge on the graphs.\\ \indent There have been some attempts on planning for agents of non-point size. Planning for agents with definite geometric shapes, occupying multiple locations was attempted in the algorithm Multi-Constraint Conflict Based Search (MC-CBS)~\cite{Li2019}. In another approach~\cite{Atzmon2019}, agents which occupied multiple locations at the same time instance owing to their length, termed as train agents, were planned for. The agent transitions from one location to another were instantaneous in nature. The approach handled two types of conflicts i.e. self conflict when an agent conflicts with itself, and occupation conflict, when an agent occupied a location, which was occupied by another agent at the given time instance. The solution proposed, Multi-Train Conflict Based Search (MT-CBS) was developed along the lines of CBS, the variation being at the low level planning and conflict detection approach. A continuous time formulation of the problem was proposed in Continuous-Time Conflict Based Search (CCBS)~\cite{Roni2019}, an adaptation of CBS and a customized version of Safe Interval Path Planning (SIPP), to arrive at a sound, complete and optimal solution to the problem.\\ \indent Spatially extended agents also find manifestation in real-world problems like train scheduling and Convoy Movement Problem (CMP). A brief overview on the centralised as well as distributed approaches adopted for CMP is covered in the following paragraphs. \subsection{Convoy Movement Problem} The CMP was proposed and solved using an integer programming (IP) formulation based on the concept of a time-space network with a combination of Lagrangian Relaxation and heuristic-based optimization techniques~\cite{Chardaire99,Harrison2000}. Kumar et.al. arrived at the lower bounds of the CMP in ~\cite{RamKumar2011}. Several other integer programming formulations have been formulated for the approach including ~\cite{RamKumar2008} and~\cite{Bovet91}.\\ \indent While formulating CMP for peacetime operations with the objective of minimizing total travel time and the travel space, goal programming and simulated annealing based approaches was explore in ~\cite{RamKumar2009}. The solutions were demonstrated on small and medium sized problems. Another look into the peacetime movement of convoys was attempted where the objective was to minimize civilian traffic disruption~\cite{Sadeghnejad2017}. The paper proposed an exact hybrid algorithm that combines the \textit{k}-shortest path algorithm, finding a minimum weighted \textit{k}-clique in a \textit{k}-partite graph and branch-and bound strategy. In~\cite{Robinson2006} a genetic algorithm was adopted with a discrete event simulation and Swarm algorithm based approaches have been looked into in~\cite{Ramkumar2015,Lee96}.\\ \indent Distributed approaches to the problem were attempted, in~\cite{Thangarajoo2010}, using a hybrid conflict resolution by coalition formation and distributed constraint optimisation approach. The concept of reservations on the time-windows of the network resources for convoy agents was used in~\cite{Adriaan2009}. This approach assumed point nature of the moving object. An A* based approach was discussed in~\cite{Thomas2008}. A centralised plan was generated by a state space search on the states achieved by the convoys on occurrence on each transition event. The approach demonstrated achievement of optimal results. A Planning Domain Definition Language (PDDL) based planning approach was explored in~\cite{Khemani2012} wherein the problem was first captured as a PDDL domain and then using standard planners, they demonstrated results for different problem sets.\\ \indent Multi agent based approaches have also been attempted for the problem. In~\cite{Thomas2015}, eXtended Conflict Based Search (XCBS) was proposed with two levels of search. The first level is at a local plan level by individual agents. The second level of search for optimised solution was at the level of a centralised agent which attempts to optimise the overall solution. \subsection{Multi Agent Conflict Detection} For the planning of the spatially extended agents, given that conflict detection is one of the prime concerns, a brief look into the various approaches which have been adopted for conflict detection in literature is in order. In~\cite{Silver2005} a concept of reservation table was introduced where following a predefined ordering an agent would plan its path and ensure it did not conflict with the plans stored by the agents before it in the reservation table. In~\cite{Standley2011}, a conflict avoidance table is used to show the positions of all agents at a given time instance. For point objects, such approaches will enable conflict detection by linear search over all the time-instances. In XCBS~\cite{Thomas2015}, the conflict detection was achieved by dividing the entire plan-time into equal sized time intervals. The spatial location of every pair of agents was compared to check for conflict. In MT-CBS,~\cite{Atzmon2019}, the conflict detection for train agents is accomplished by defining an occupation-list, a list of locations occupied by an agent at an instance of time. As transition from one location to another is instantaneous, the occupation list is checked for every pair of agents at every instance of time. Overlapping occupation list indicated a conflict. \section{Terminology}\label{terminology} Table \ref{tab:notations} refers to the notations used in this paper. \begin{table}[h] \resizebox{\textwidth}{0.35\textwidth}{ \begin{tabular}[c]{|l|p{3.5cm}|p{8.5cm}| } \hline \multicolumn{1}{|c|}{\textbf{ }}&\multicolumn{1}{|c|}{\textbf{Notation}}&\multicolumn {1}{|c|}{\textbf{Description}} \\ \hline \multirow{3}{*}{Network}&$\mathcal{G(V,E)}$ &Road network with $\mathcal{V}$ vertices and $\mathcal{E}$ edges \\ &$\mathcal{L}_i$ &length of edge $e_i$, $e_i \in \mathcal{E}$ \\ &$\mathcal{S}_i$ &speed on edge $e_i$, $e_i \in \mathcal{E}$ \\ \hline \multirow{6}{*}{SEAgent}&$A$ &Set of spatially extended agents \\ &$a_j$ &Spatially Extended Agent \\ &$\mathbb{L}_j$ &Length of the agent \\ &$\mathbb{I}_j$ &Initial (Source) vertex\\ &$\mathbb{F}_j$ &Final (Destination) vertex \\ &$\mathbb{S}_j$ &Average Speed \\ &$\mathbb{E}(t)$ = $\lbrace l_1, l_2, ....,l_n \rbrace$, $l_i \in (\mathcal{E} \cup \mathcal{V})$ &locations occupied by $a_j$ \\ \hline \multirow{2}{*}{Agent Actions}&move($l_i$, $t$) &head($a_j$) enters location $l_i$ at time $t$ \\ &wait($t$, $t_d$) &$a_j$ waits at time $t$ for $t_d$ time-units with no change in the position.\\ \hline \multirow{2}{*}{Plan}&$\mathtt{P_\textit{j}} = \{\mathit{move(l_1,t_1)}$ , $\mathit{move(l_2, t_2)}$, $\mathit{wait(t_3, d) \ldots\}}$, where, $t_1<t_2<t_3$&The sequence of actions to be executed by an agent $a_j$ to travel from $\mathbb{I}_j$ to $\mathbb{F}_j$. A plan $P_j$ is \textit{consistent} if it satisfies all constraints imposed on $a_j$. \\ \hline \multirow{2}{*}{Solution}&$\mathtt{S} = \{\mathtt{P}_1, \ldots ,\mathtt{P}_k\}$ & Solution $S$ should satisfy: \textit{(i)} $\forall{j_{1..k}}\mathtt{P}_j$ is consistent and \textit{(ii)} $\mathtt{S}$ is \textit{valid} i.e. plans are conflict-free.\\ \hline \end{tabular} } \caption{Description of notations used in this paper} \label{tab:notations} \end{table} \section{XCBS-A}\label{xcbsa} \indent We now describe the eXtended Conflict Based Search with Awareness (XCBS-A), which is based on the principle of the two-level search used in XCBS. The algorithm proposes a novel approach for conflict detection, low level search and conflict resolution. \subsection{Definitions} The definitions used in this approach are as follows: \begin{definition} The search space for the plans is maintained in a \textbf{Constraint Tree} (CT). A node of the CT, the CT-node $N$, is consistent with the definition given in XCBS~\cite{Thomas2015}. It comprises: \begin{enumerate} \item \textit{N.Id}: Unique identifier for the CT-node. \item \textit{N.Solution}: $\{\mathtt{P_\textit{1}},\ldots ,\mathtt{P_\textit{k}}\}$ is a set of consistent optimal plans $\mathtt{P_\textit{i}}$ for each agent. \item \textit{N.Cost}: Cumulative cost of the plans of the individual agents i.e.,$ \sum_{j=1}^k cost(\mathtt{P}_j)$ \end{enumerate} \end{definition} \begin{definition} The coordination for the search to achieve a valid solution is done by the \textbf{Central Agent} (CA). The CA executes a high-level search on the Constraint Tree (CT) to identify potential nodes to be explored for validity of solution. \end{definition} \begin{definition} Every agent for which the path is to be planned is termed as the \textbf{Spatially Extended Agent} (SEA). The agent executes a low-level search to generate a consistent plan with respect to the spatio-temporal constraints imposed by its own preferences as well as other agents' plans. \end{definition} \begin{definition}The \textbf{Temporal Occupancy (t.o.) node} $\gamma$, expressed as a tuple $<l,\tau, Z>$, is used to describe the occupancy details of a location $l$ during a given time period $\tau$. The list of exact time durations, during $\tau$, during which each SEA occupies the location $l$ is given by AgentDetails $Z$. There exists at least one t.o. node, for each location $l \in \mathcal{E} \cup \mathcal{V}$, which is in any plan $\mathtt{P}_j \in \mathtt{S}$. For a given location $l$, if the time-intervals spent by different agents on $l$ overlap, then $\tau_{l}$ for the corresponding t.o. node $\gamma_{l}$ will be defined as the maximal covering time interval, else multiple t.o. nodes will be generated for the edge or vertex $l$. \end{definition} \begin{definition} A directed graph $G(\Gamma,\Delta)$ is called the \textbf{Temporal Occupancy (T.O.) graph} comprising $\Gamma$, the set of t.o. nodes, and $\Delta$, the set of edges which connects the t.o. nodes. A directed edge $\delta \in \Delta$, exists between two t.o. nodes, $\gamma_i$ and $\gamma_j$, when $\gamma_i.g$ and $\gamma_j.g$ are distinct and are consecutive locations in the plan $\mathtt{P_j}$ of agent $a_j$. Each edge $\delta$ has a property $\delta.agent$ to indicate the agent whose plan makes that edge valid. Two t.o. nodes may have multiple edges between them, if more than one agent occupies the corresponding $\gamma_i.g$ during the time periods of the t.o. nodes. \end{definition} The T.O. graph may contain multiple t.o. nodes for which $\gamma_i.g$ is same. For such $\gamma_i$, $\gamma_i.\tau$ will be governed by the meets, meets inverse, after or before relation as defined in Allens temporal relations~\cite{Allen1983}. These nodes indicate occupancy details over a road over non-overlapping time-intervals. At its initial and final vertices $\mathbb{I}_j$, $\mathbb{F}_j$, an agent cannot collide with any other agent. For this, TO nodes are not generated for the agent for its initial and final vertices. The graph can also have several singleton t.o. nodes, which can occur when the path of the agent comprises a single edge between its initial and final vertices. \subsection{Algorithm} \subsubsection{High Level Search} The High Level Search, shown in Algorithm \ref{xcbsa-highlevelsearch}, is executed by the CA, on the search space of the plans of all the agents, to arrive at a valid solution. The CT, which maintains the search space of the plans, is initialised with the root CT-node, with $N_r.Solution$ having the initial plans $\mathtt{P_\textit{i}}$ of SEAs, and cost $N_r.Cost$. The initial plans are made assuming that the entire road network is fully available to each agent. The Open Set $O$, comprising the unexplored CT-nodes is populated with the CT-nodes generated (initially it will have only the root CT-node, as in Line 2). At Line 5, the CA chooses the least cost CT-node, $N_e$, for exploration from $O$. This CT-node, $N_e$, is validated to identify presence of conflicts between the plans of the agents, as discussed in Algorithm \ref{Validate CT-node}. If conflicts are detected, the conflicting plans are sent to the SEAs for resolution. The resolution plans generated by the SEAs through a Low-Level search are combined into child CT-nodes, discussed under section \ref{conflictResolution}, which are added to $O$ for further exploration. The search is continued till a conflict-free CT-node is found. \\ \begin{algorithm} \caption{\textbf{High Level Search}}\label{xcbsa-highlevelsearch} \begin{algorithmic}[1] \State Define root CT-Node $N_r$ with optimal consistent plan for each $a_i$ agents. \State OpenSet $O \gets \{N_r\}$ \State $ResultFound \gets false$. \While {!$O.empty$ or !$ResultFound$} \State $N_e \gets arg min_{N^{'} \in O} N^{'}.Cost$ \State $O \gets O \setminus {N^{'}}$ \State $conflictPresent \gets Validate(N_e)$ \If {$conflictPresent$} \State $\{ChildCTNodes\} \gets ResolveConflict(N_e)$ \State $O \gets O \cup \{ChildCTNodes\}$ \Else \State $ResultFound \gets true$ \EndIf \EndWhile \If {$ResultFound$} \State $Solution \gets N_e.Solution$ \EndIf \end{algorithmic} \end{algorithm} \subsubsection{Solution Validation}\indent Solution validation checks for presence of conflicts between the plans in the CT-node $N_e$ being explored and identifies all mutually conflicting sets of agents. A solution is valid if no conflicts are detected among the plans in $N_e$. Solution validation involves three stages: \textit{(a)} Creation of TO Graph $G_e$, \textit{(b)} Creation of partition set, \textit{(c)} Decision on validity of solution. We step through each stages in the following paragraphs.\\ \indent Stage (a): For the CT-node $N_e$ being explored, a TO graph $G_e$ is created as shown in Lines 1-18 of Algorithm \ref{Validate CT-node}. The t.o.node, $\gamma$, represents the occupancy information of every location for periods of time. Every location in the plan of an agent $a_i$, is compared with the previous t.o. nodes to check if a t.o. node, $\gamma$ exists for the given location. If so, $\gamma.Z$ and $\gamma.\tau$ is updated to include the new agent and covering time-period. In case such a t.o. node does not exist, then creation of a t.o. node with the relevant values is done. Further, every t.o. node so created/updated, is then linked to the previous t.o. node through an edge $\delta$ with the relevant agent property being set. In the TO graph so created, t.o. nodes with multiple incoming and outgoing edges indicate that there are multiple agents occupying that particular edge at the given time period and hence possibility of collision needs to be evaluated only for those nodes.\\ \indent Stage (b): Lines 19-26 of the Algorithm \ref{Validate CT-node} cover the creation of partition $X$, from $G_e$. From the list of the t.o. nodes with in/out degree $>$ 1, the overlapping agents are added to the same block of the partition. When adding to a block, if none of the agents pre-existed in any block then a new block is created with both agents as members. If either one of the agents is a member of some pre-existing block of the partition, then the other agent is also added to the same block. If both agents pre-exist and belong to different blocks, then the two blocks are merged into a single block. Once all the t.o. nodes have been evaluated, if there are still agents which do not belong to any block of the partition, they are created into singleton blocks.\\ \indent Stage (c): The non-singleton blocks of the partition comprise the mutually conflicting agents. The $N_e.Solution$ is valid when the plans are conflict free. When a partition $X$ comprises only of singleton blocks, it indicates that the plans are consistent and conflict free and hence the solution of the CT-node is valid.\\ \begin{algorithm} \caption{\textbf{Validate $N_e$}}\label{Validate CT-node} \begin{algorithmic}[1] \Procedure{Validate}{$N_e$} \For {plan $p_i \in N_e.Solution$} \Comment {Stage (a): Create TO Graph $G$} \State $prevNode \gets null$, $currNode \gets null$ \For {location $l_{ij} \in p_i$} \If {$\exists \gamma \in G.\Gamma, (\gamma.g = l_{ij})\bigwedge (l_{ij}.TimeDuration$ overlaps $\gamma.\tau) $} \State $\gamma.Z.agent \gets agent_i \cup \gamma.Z.agent$ \State $\gamma.Z.AgentTime \gets l_{ij}.TimeDuration \cup \gamma.Z.AgentTime$ \State $\gamma.\tau \gets covering(\gamma.\tau, l_{ij}.TimeDuration)$ \Else \State Create t.o.node $\gamma$ \State Add $agent_i$ to $\gamma.Z.agent$ \State Add $l_{ij}.TimeDuration$ to $\gamma.Z.AgentTime$ \State $\gamma.\tau \gets l_{ij}.TimeDuration$ \State Add $\gamma$ to $G$ \EndIf \State $currNode \gets \gamma$ \If {$prevNode != null$} \State Create edge $\delta \in G.\Delta$, between $prevNode$ and $currNode$ \State $\delta.agent \gets agent_i$ , $prevNode \gets currNode$, $currNode \gets null$ \EndIf \EndFor \EndFor \State Create blank partition $X$. \Comment Stage (b): Create Partition on $G$ \For {t.o. node $n_e \in G, degree(n_e) > 1$} \For {$a_i, a_j \in n_e.Z.agent$} \If {$Relates(n_e.Z_{a_i}.AgentTime, n_e.Z_{a_j}.AgentTime)$} \If {$\exists b \in X, a_i \lor a_j \in b$} \State Update $b$ to include $a_i$, $a_j$. \Else \State Create block $b$ , Add $a_i$, $a_j$ to $b$. \EndIf \EndIf \EndFor \EndFor \If {$\exists a_i \in \mathbb{A}, \forall b \in X, a_i \not\in b}$ \Comment Add singleton blocks to the partition. \State Add singleton block $b$ containing $a_i$ \EndIf \If {number of non-singleton blocks in $X \geq 1$} \Comment Stage (c): Decision. \State return true. \Else \State return false. \EndIf \EndProcedure \end{algorithmic} \end{algorithm} \indent In XCBS, in case of $t$ time intervals for $k$ agents, an agent could occupy $l$ locations during that interval; the time taken for detection would be $O(t\cdot k^2 \cdot l)$. However, in our approach of using TO graph for conflict detection, we need to consider the time taken for creation of the TO graph as well as the time for consequent conflict-detection. The creation of the TO graph requires iteration over the plan of each of the $k$ agents. For each agent, if there are $l$ locations in the plan, then the creation time is $O(k\cdot l)$. Consequent to the creation of the TO graph $G$, only the set of t.o. nodes with an in-degree or out-degree $>$ 1 or $AgentDetails > 1$ need to be evaluated for checking the conflict time. If there are $n$ such conflicting t.o. nodes, the overall time for conflict-detection (including TO graph creation time) is $O(k \cdot l + n \cdot k^2)$. \subsubsection{Conflict Resolution}\label{conflictResolution} \begin{algorithm} \caption{\textbf{ResolveConflict $N_e$}}\label{resolveConflict} \begin{algorithmic}[1] \Procedure{ResolveConflict}{$N_e$} \For {each agent $a_i$ in non-singleton blocks} \State $P^{'}_{i}$ = LowLevelSearch($a_i, N_e$). \EndFor \For {each combination on the members of non-singleton block $b$ in the partition of $N_e$} \State Create child CT-node $N_c$ with revised plan of one agent $a_i$ from each of $b$ and the unchanged plans for the remaining agents. \State Compute Cost($N_c$). \State Add to the openset $O$ \EndFor \EndProcedure \end{algorithmic} \end{algorithm} \indent When a conflict is detected on a CT-node $N_e$, each SEA in a non-singleton partition block invokes a LowLevelSearch for itself to generate an alternate plan, as shown in line 2 of Algorithm \ref{resolveConflict}. All agents' plans are passed to each of the SEA to generate the alternate plan such that it does not conflict with the other agents' plans. The LowLevelSearch will always be able to generate an alternative plan either by deviation in terms of path or by introducing a wait before the conflict location. When revised plans $P^{'}_{i}$ are received from the SEAs, the Central Agent composes the revised plans into child CT-node, as shown in Line 4. If $N_e$ resulted in $j$ non-singleton blocks of partition, one agent's revised plan is added for each non-singleton block and the plans of the remaining agents of the same block remain unchanged in a generated child CT-node. The plans for the singleton block agents are added unchanged. Thus, if $N_e$ resulted in $j$ non-singleton blocks of partition then, each child CT-node will have $j$ revised plans in $N.Solution$. A combination on the agents in the non-singleton blocks is done to generate child CT-nodes. Thus, for $j$ non-singleton blocks with $i$ agents each, the number of CT-nodes generated will be $i^j$. \\ \indent For the revised plan generated by an SEA in each of the child CT-node generated by the CA, a conflict can only potentially arise between the new $j$ revised plans generated independently by the agents in $j$ blocks of the partition. The child CT-nodes so generated, are added to the Open-Set $O$ to be further explored. \\ \subsubsection{Low Level Search} \begin{algorithm} \caption{\textbf{Low Level Search $N_e$}}\label{LowLevelSearch} \begin{algorithmic}[1] \Procedure{Low Level Search}{$N_e$} \If {!agentPlansAvailable} \State Get shortest path from $\mathbb{I}_i$ to $\mathbb{F}_i$ \State Define plan $P_i$ with the above path. \Else \State Get constraints set from the plans of other agents. \State $R_r \gets$ CreateRootReplanNode(). \State OpenSet $O \gets R_r$ ; $O \gets O \setminus \{R_{r}\}$;$ResultFound \gets false$. \While {!$O.empty$ or !$ResultFound$} \State $R_e \gets arg min_{R^{'} \in O} R.cost $ \State $consistent \gets checkConsistency(R_e)$ \If {$!consistent$} \State $Child_1 \gets createAltPath(R_e)$ ; $Child_2 \gets createWait(R_e)$ \State $O \gets O \cup \{Child_1, Child_2\}$ \Else \State $ResultFound \gets true$ \EndIf \EndWhile \EndIf \EndProcedure \end{algorithmic} \end{algorithm} \indent Each SEA executes a Low-Level search to identify consistent plans for itself, as shown in Algorithm~\ref{LowLevelSearch}. During the first run of the algorithm (no other agent plans are available), each SEA generates its optimal path using Djikstra's algorithm~\cite{Djiktstra1959} assuming full availability of road-space, as in Lines 2-4. The plan so obtained is the best plan for each agent. In subsequent iterations of the algorithm (Lines 6-16), each SEA identifies spatio-temporal constraints which are imposed on it by the current known plans of the other agents. The SEA then generates an alternate plan $P^{'}$, to meet all the newly generated spatio-temporal constraints. Consistency with respect to plans of other agents is maintained either by identifying an alternate location or by introducing a wait. The optimal plan with no conflict is sent to the CA as the alternative plan. The new plan so generated is different from the initial plan either spatially or temporally or both. This change leads to the cost of the new plan being same or higher than its earlier plan. \\ \begin{figure} \centering \begin{subfigure}{0.6\textwidth} \includegraphics[width=1.2\textwidth]{1.png} \centering \caption{Sample network with root CT node $N_r$} \label{fig:roadgraph} \end{subfigure} \begin{subfigure}{.5\textwidth} \includegraphics[width=0.9\textwidth]{2.png} \centering \caption{TO Graph with partition of $N_r$ } \label{fig:TOGraph} \end{subfigure}% \begin{subfigure}{.5\textwidth} \centering \includegraphics[width=0.9\textwidth]{3.png} \caption{Replanning for agent $C_2$} \label{fig:Replan} \end{subfigure} \caption{Figure shows the TO Graph and the replanning at an agent level, as a consequence of validation of $N_r$ } \label{fig:Replan_TOGraph} \end{figure} \subsection{Example} We will walk through an example scenario with five SEAs moving in a grid network, as shown in Figure \ref{fig:roadgraph}. There is a t.o. node created for every unique location which is a part of the plans of any SEA. For SEA $C_1$, travelling through $e_1,v_2,e_2$, the t.o. nodes $TO_1, TO_2$ and $TO_3$ are created. When $C_2$ is evaluated, it passes through $e_4, v_2$ and $e_2$ and hence t.o. node $TO_3$ is updated to include $C_2$ in its agents' list and the time duration is the covering time-period of the two agents. Similarly $C_5$ which travels through only one edge $e_5$ creates a singleton t.o. node $TO_{11}$. Using the TO graph, the partition $X$ of the agents is created. $C_1$ shares location $e_2$ with $C_2$, similarly, $C_2$ and $C_3$ conflict on edge $e_4$, and $C_3$, $C_4$ collide on edge $e_6$, thus any change in the schedules of $C_3$ may have cascading impact on $C_1, C_2$ or $C_4$, hence they are put in the same block $b_1$ of the partition. As $C_5$ does not intersect with any other SEA, it is put into singleton block $b_2$ of the partition $X$. Thus, for the CT-node, a partition with two blocks is generated; the TO Graph and the partition is shown in Figure \ref{fig:TOGraph}. The block $b_1$, has agent $C_2$ as a member, and the tree for replanning, generated as part of the Low-Level search for agent $C_2$ is shown in Figure \ref{fig:Replan}. The spatio-temporal constraints on $C_2$ from the plans of the other agents is shown as R.Constraints. The root Replan-node (R.Id:1), contains the current plan for $C_2$. From the constraint set, the first identified constraint that gets violated is road $e_2$. Replan-nodes 2,3 handle the repath and the waiting plans respectively. Replan node 2 being the lower cost node is explored next and found to violate constraint with respect to road $e_7$ and hence resolved to generate Replan-nodes 4 and 5. The final plan which is consistent with respect to all other agent plans is shown by the highlighted bordered node (Id:3)\\ \section{ANALYSIS}\label{xcbsa-theoretical} \begin{lemma} The number of singleton blocks in the partition of a CT-node is non-decreasing down the branch of a CT.\\ \end{lemma} \indent Let $N_0$ be the node at the head of a branch of the CT, with its partition set containing $s$ singleton blocks and $c$ non-singleton blocks. In the child CT-node $N'_0$, the singleton nodes remain unaffected; however, one element from each of the $c$ blocks will be reduced because of conflict resolution. These $c$ elements will either conflict with each other, or form singleton blocks. Thus the number of singleton blocks in the child CT-node will be either $s$ i.e. same as the parent CT-node or will increase by a maximum of $c$. \\ \begin{lemma} The average size of non-singleton blocks is non-increasing at every level down a branch in the CT. \\ \end{lemma} \indent Let the total number of non-singleton blocks in a partition of the root CT-node be $c$, with an average size \textbar${c}$\textbar, and the number of singleton blocks be $s$. If the number of agents be $k$ then\\ \begin{equation*} |c| *c + s = k \end{equation*} \begin{equation} |c| = (k - s)/c \end{equation} After the first step of resolution, one element from each of the non-singleton blocks is revised and removed from the block, reducing the size of the non-singleton blocks by one. Each of these plans can either all conflict among themselves to generate a new additional block in the partition, or can have no conflicts among themselves leading to independent singleton blocks, or can form multiple additional blocks. We will consider the three boundary cases: \textit{Case 1:} No new conflicting blocks due to revised plans are introduced in the child CT-node partition.\\ \indent In this case, consequent to revised plans, one element from each of the $c$ blocks will form a singleton block by themselves.\\ \begin{equation} \implies s' = s + c \end{equation} since $|c'|*c' + s' = k$ \\ \begin{equation*} \implies |c'| = (k- s')/ c' \\ \end{equation*} from (3), \begin{equation}|c'| = (k - s -c)/c' \end{equation} As the number of non-singleton blocks are unchanged from the previous step, hence $c' = c$ \\ $\implies |c'| = (k - s -c)/c \\$ $\implies |c'| = (k - s)/c - 1 \\$ $\implies |c'| = |c| - 1 \\$ \textit{Case 2:} The revised plans all mutually conflict to introduce one additional non-singleton block in the child CT-node partition.\\ In this case, consequent to revised plans, number of non-singleton blocks $c'$ will be $c' = c+ 1$\\ As the number of singleton blocks are unchanged from the previous step, hence $s' = s$ \\ $\implies |c'| = (k - s')/c'$\\ $\implies |c'| = (k - s)/(c + 1)$\\ $\implies |c'| < |c|$\\ \textit{Case 3:} The revised plans all pairwise conflict to introduce $c/2$ additional non-singleton block in the child CT-node partition.\\ In this case, consequent to revised plans, number of non-singleton blocks $c'$ will be $c' = c+ c/2$\\ As the number of singleton blocks are unchanged from the previous step, hence $s' = s$ \\ $\implies |c'| = (k - s')/c'$\\ $\implies |c'| = (k - s)/(3/2 c)$\\ $\implies |c'| < |c|$\\ \begin{lemma} The Cost of a CT-node is non-decreasing down a branch of the CT. \end{lemma} \indent The evaluated CT-node $N_e$ has $N_e.Solution = \{P_1,\ldots, P_k\}$ where,\\ $\forall_{i=1 \ldots k}P_i = \min( cost(P_{i_1}),\ldots,cost(P_{i_j}))$.\\ $\implies \nexists \bar{P}_i \colon cost(\bar{P}_i) < cost(P_i)$.\\ In other words, $N_e.Solution$ comprises the least cost plans of the individual agents.\\ The child CT-node $\acute{N}_e$ of $N_e$ may have $m$ agents with revised plans $\acute{P}_i$ generated to avoid conflict with other agents' plans. Further, $cost(\acute{P}_i) >= cost(P_i)$, as the revised plan for the agent will be generated to handle the additional spatio-temporal constraints imposed due to potential conflict.\\ $\implies cost(\acute{N}_e.Solution) >=cost(N_e.Solution)$. \\ \begin{theorem} XCBS-A is complete. \end{theorem} Proof: The CT contains all the possible consistent plans of the agents as CT-nodes, which are explored based on their cost. The algorithm systematically explores all equal cost CT-nodes, before choosing a higher cost CT-node, for possible valid solution. Hence it is akin to a uniform-cost search and hence is complete. Further, the algorithm keeps resolving the partition set of the root CT-node to arrive at singleton sets, down a branch of the CT. From Lemmas 1\&2, we know that the partition eventually resolves to singleton sets and hence cannot be resolved further. Thus each branch of the CT will lead to a leaf CT-node and hence the algorithm will terminate either when a solution is found or when there are no-more CT-nodes to be explored. \section{EXPERIMENTAL ANALYSIS}\label{xcbsa-experimental} We have evaluated the time taken to arrive at a valid solution and the search space explored by XCBS-A with respect to some of the other available solutions. The road networks were maintained using JGraphT library~\cite{Dex2007} and its APIs were used to find the shortest path (based on A*~\cite{Nilsson1968}) in the road network. The test cases were run on Intel Xeon (4 Core) processor @ 3.26 GHz with 12 GB RAM. In the following sections, the results plotted and tabulated for all the analysis have been computed as the average-value of ten iterations on the same test data. \subsection{Performance Evaluation on agent, plan and network characteristics} \indent For performance evaluation, we have used the algorithms for the Convoy Movement Problem (CMP) which are based on spatially extended objects. The performance of the optimised version of XCBS-A was compared with XCBS~\cite{Thomas2015}, the A* based solution for CMP~\cite{Thomas2008} and PDDL solution~\cite{Khemani2012}. A distributed priority based allocation strategy, along lines similar to XCBS was also compared with. Each SEA generates an optimal schedule for itself; a central conflict resolver, then does a priority ordering of the SEAs. The conflict resolution is priority based, wherein the higher priority SEA continues unhampered on the conflict area, while the lower priority SEA either waits or takes the nearest diversion. The algorithms were tested for performance to assess the impact of agent characteristic, plan characteristic and the road network characteristics. The first is captured in terms of the number of agents in the plan, the plan characteristics is evaluated in terms of the max plan length, while the road characteristics is studied in terms of road density and network size.\\ \indent Figure~\ref{fig:XCBSA} shows the results of the executed test cases. The tests were executed on a grid based network, with uniform length roads. The agents themselves were homogeneous in terms of speed and length, however their source and destination locations were randomly decided to ensure that the path-length are uniformly maintained. In some of the tests, PDDL based solution could not be executed for all range of values as the planner used, LPG-td~\cite{LPG2004} did not support the number of predicates which were getting generated for the testcase. \\ \indent In Figures~\ref{fig:XCBSA-Agents} to~\ref{fig:XCBSA-Density}, the comparative performance of the five algorithms indicates XCBS-A shows significantly better performance with respect to all the other approaches being compared with, in terms of variation in number of agents, path lengths, network sizes and network density. These results also imply that the algorithm is able to scale to solve large problem sizes without issues in terms of memory or computation time.\\ \begin{figure}[h] \centering \begin{minipage}{0.5\textwidth} \centering \includegraphics[width=1\textwidth, height=1\textwidth]{4} \subcaption{Number of agents} \label{fig:XCBSA-Agents} \end{minipage}% \begin{minipage}{0.5\textwidth} \centering \includegraphics[width=1\textwidth, height=1\textwidth]{5} \subcaption{Path Length} \label{fig:XCBSA-PathLength} \end{minipage} \begin{minipage}{0.5\textwidth} \centering \includegraphics[width=1\textwidth, height=1\textwidth]{6} \subcaption{Network Size} \label{fig:XCBSA-NetworkSize} \end{minipage}% \begin{minipage}{.5\textwidth} \centering \includegraphics[width=1\textwidth, height=1\textwidth]{7} \subcaption{Network Density} \label{fig:XCBSA-Density} \end{minipage} \caption{Comparative Performance of XCBS-A with other approaches} \label{fig:XCBSA} \end{figure} \begin{figure} \begin{center} \begin{minipage}[t]{0.45\textwidth} \vspace{0pt} \centering \includegraphics[scale=0.3]{8} \caption{Evaluation of distributivity of XCBS-A} \label{fig:XCBSA-Distributive} \end{minipage}% \begin{minipage}[t]{0.45\textwidth} \vspace{0pt} \captionsetup{type=table} \begin{tabular}[c]{|c|c|r|r|r||r|r|r| } \hline \multicolumn{1}{|c|}{\multirow{2}{*}{\textbf{$\lvert A \rvert$}}} &\multicolumn{1}{|c|}{\multirow{2}{*}{\textbf{$\lvert B \rvert$}}}&\multicolumn {3}{|c|}{\textbf{XCBS}} &\multicolumn{3}{|c|}{\textbf{XCBS-A}}\\ \cline{3-8} & &\textbf{$t$} &\textbf{$N_g$} &\textbf{$N_e$} &\textbf{$t $} &\textbf{$N_g$} &\textbf{$N_e$}\\ \hline 5&1 &40757 &41&11 &\textbf{245}&\textbf{15}&\textbf{5}\\ 7&1 &85147&85 &22 &\textbf{300}&\textbf{21}&\textbf{6}\\ 9&1 &91565&17&27 &\textbf{554}&\textbf{36}&\textbf{8}\\ 14 &7 &30337 &29 &8 &\textbf{490} &\textbf{129} &\textbf{2}\\ 15 &5 &62493 &61 &16 &\textbf{649} &\textbf{179} &\textbf{3}\\ 16 &4 &86632 &85 &22 &\textbf{708} &\textbf{164} &\textbf{4}\\ 15 &3 &123041 &121 &31 &\textbf{785} &\textbf{171} &\textbf{5}\\ 12 &2 &122442 &111 &31 &\textbf{602} &\textbf{71} &\textbf{6}\\ 14 &2 &126414 &125 &32 &\textbf{633} &\textbf{66} &\textbf{7}\\ 16 &2 &138487 &137 &35 &\textbf{666} &\textbf{59} &\textbf{8}\\ \hline \end{tabular} \caption{Comparison of Nodes generate $N_g$, nodes evaluated $N_e$ and time taken $t$} \label{tab:XCBSA-XCBS-Comparison} \end{minipage} \end{center} \end{figure} \subsection{Performance Evaluation for distributivity} \indent The XCBS-A is a completely distributed but centralised algorithm. For testing the distributivity and scalability, the algorithm was also implemented as a multi-agent system using Java Agent DEvelopment (JADE)~\cite{Jade2005}. JADE is a popular open source agent development framework which provides support for agent creation as well as agent monitoring, maintenance and communication. Each of the SEAs and the Central Agent was instantiated as JADE Agents on different physical machines. The SEAs were instantiated with their initial and final locations defined, while the Central Agent was instantiated with an awareness of the total number of SEAs to participate in the planning. The communication between the SEAs and the CA was through Agent Communication Language (ACL)~\cite{fipaacl2002} message, which is the standard format for communication among agents in JADE. \\ \indent The performance of XCBS-A as a multi-threaded application and as JADE based distributed deployment on multiple physical systems was compared with XCBS deployed on a single system, and is shown in Figure~\ref{fig:XCBSA-Distributive}. In the figure, XCBS-A(1) denotes multi-threaded implementation of the algorithm on a single machine. XCBS-A(2) refers to JADE implementation of the algorithm with all agents deployed on the same physical system, using unshared memory. XCBS-A(3) refers to the JADE implementation with agents distributed across three identical machines. While all three instances of the XCBS-A algorithm performed better than XCBS, the multithreaded implementation of XCBS-A was better than XCBS-A with JADE. This can be explained as the additional time taken in terms of communication between agents. This demonstrated that the algorithm is completely distributed in nature and can be scaled over multiple machines in a networked environment, seamlessly and continues to outperform XCBS.\\ \subsection{Performance Evaluation for search space generation and exploration} \indent The performance of XCBS-A with respect to XCBS was evaluated in terms of time taken to arrive at the solution and the size of the search space, primarily in terms of casacading conflicts. Table ~\ref{tab:XCBSA-XCBS-Comparison} compares the performance of the two algorithms, for different number of agents $\lvert A \rvert$ and different number of blocks $\lvert B \rvert$, in terms of time taken $t$, number of CT-nodes generated $N_g$ and number of CT-nodes evaluated $N_e$. As seen from the table, XCBS-A shows significant improvement in terms of time taken to arrive at a valid solution. Secondly, in some cases, the number of CT-nodes generated as a consequence of conflict resolution is found to be large as compared to XCBS, leading to a very huge search space, as seen in the table. There are four child CT-nodes generated for each CT-node being explored in case of XCBS, whereas in case of XCBS-A, if the partition for the CT-Node $N_e$ has $j$ non-singleton blocks with $i$ agents each, then the number of child CT-nodes generated will be $i^j$. This explains the large search tree in case of XCBS-A. However, in spite of the large tree, XCBS-A handles multiple conflicts simultaneously hence converges to a solution faster than XCBS. \section{Memory Efficient XCBS-A}\label{xcbsa-eff} \indent In XCBS-A, at each level of the CT there are $i^j$ CT-nodes which may be of the same cost. As the cost of the CT-nodes is non-decreasing down the tree, all CT-nodes of same cost at a level of the CT would have to be explored before higher-cost CT-nodes, in lower branches, could be explored. This leads to the generation and exploration of the large search space as was seen in the results discussed above. We looked into anytime approaches \cite{Thayer2010} which try to arrive at optimised solutions by iteratively expanding the search space based on the deliberation time available. In these approaches \cite{Cohen2018,Pearl1982,Thrun2003} different sets were used to maintain the explored, unexplored, inconsistent and select nodes of the search space.\\ \indent Inspired by the above mentioned approaches, we formulated a strategy of adding only potentially explorable CT-nodes into the Open set. Meta-data for regeneration of other child CT-nodes is stored in another set called Potential Set (PS). The revised high-level search is as shown in Algorithm \ref{algo-memory-eff}. As per the strategy, when a CT-node $N_e$ is being chosen to be explored, it is compared with the best-node from the Potential Set. If cost of the CT-node from Potential Set is lesser than the cost of the node from the Open Set, then it is removed from Potential Set and explored. This is shown in Line 6-10 of the algorithm. Further, on conflict resolution from among the multiple child CT-nodes generated, only one least cost node is added to the Open Set. The metadata with respect to the remaining nodes is placed in the Potential Set. This approach ensures that the CT comprises only one of the least-cost CT-nodes generated by the exploration of a CT-node. Hence the search space is reduced significantly. Moreover since only meta-data of a child node is maintained in Potential Set, hence it does not consume much storage space.\\ \begin{algorithm} \caption{\textbf{Memory-Efficient High Level Search}}\label{algo-memory-eff} \begin{algorithmic}[1] \State Define root CT-Node $N_r$ with optimal consistent plan for each $a_i$ agents. \State OpenSet $O \gets \{N_r\}$ \State Potential Set $PS \gets \phi$ \State $ResultFound \gets false$. \While {!$O.empty$ or !$ResultFound$} \If{$min_{N^{'} \in O} N^{'}.Cost <= min_{\tilde{N} \in PS} \tilde{N}.Cost}$ \State $N_e \gets arg min_{N^{'} \in O} N^{'}.Cost$ \State $O \gets O \setminus {N^{'}}$ \Else \State $N_e \gets PS.getBestNode()$ \EndIf \State $conflictPresent \gets Validate(N_e)$ \If {$conflictPresent$} \State $\{ChildCTNodes\} \gets ResolveConflict(N_e)$ \State $N_{min} \gets arg min_{N^{'} \in ChildCTNodes} N^{'}.Cost$ \State $O \gets O \cup \{N_{min}\}$ \State $PS \gets ChildCTNodes\setminus N_{min}$ \Else \State $ResultFound \gets true$ \EndIf \EndWhile \If {$ResultFound$} \State $Solution \gets N_e.Solution$ \EndIf \end{algorithmic} \end{algorithm} \begin{figure} \includegraphics[width=\textwidth]{9} \caption{Figure shows comparative generation and exploration of CT in XCBS-A (left) and XCB-A-Eff (right).} \label{fig:xcbsaeff} \end{figure} \indent \textbf{Example:} Figure \ref{fig:xcbsaeff} shows a small illustrative example indicating the growth of the CT in the normal mode and in the optimised mode. The root CT-Node, $N_r$, has the partition as shown in the figure. In Step 1 (indicated by arrow numbered 1), CT-node.Id 1, is explored to generate the CT-nodes with combined revised plans of agents from blocks $b_1$ and $b_2$ of the partition. In normal CT (shown in the left figure), this leads to generation of CT-nodes 2 to 7. In the optimised mode (shown in the right figure) only one CT-node, which is the least cost node among all solutions is added to the CT. The remaining solutions are maintained cost-wise at the Potential Set. Thus as a consequence of Step 1, in optimised mode, the Potential Set makes entries with costs 340 and 350, for the parent CT-node 1. The CT-nodes explored $2^{nd}$ and $3^{rd}$ are indicated by the corresponding numbered arrowheads. Consequent to Step 3, the least cost node in the optimised mode CT is of cost 343, while the least cost node available in the Potential Set is of cost 340. This node is then extracted from the Potential Set and added to the optimised CT, with its parent as defined in the Potential Set. The node (marked with arrowhead 4) is then explored, and the entire search process is consistent across both modes of operations. The reduced search space is evident from the example.\\ \indent The Potential Set ends up having several CT-nodes with the same cost and hence choosing one from among them as the best-node is guided by a heuristic measure. We attempted three different heuristic measures for the same. \begin{itemize} \item Deeper-first: The child node which is to be positioned deeper, would have resolved more conflicts as compared to other nodes of the same cost, on higher branches. This would favour search paths of the tree where search has progressed more. \item Largest-block first: The child node, the partition set of whose parent had the largest block. The idea being that resolving the group with the largest mutually conflicting agents will likely lead to solution faster. \item Most-singletons first: The child node, the partition set of whose parent had the maximum number of singletons. The idea being that greater the number of singletons, the closer the node is to the solution. \end{itemize} However, preliminary experimentation revealed that the XCBSA-Eff approach gave an advantage in terms of the total number of nodes in the CT. Further, in terms of the number of nodes explored to arrive at the solution, Deeper-first heuristic gave better performance as compared to the other heuristics. Hence for the rest of the paper, all our references to XCBSA-Eff will be with respect to the Deeper-first heuristic. \\ \begin{table} \resizebox{\textwidth}{!} { \begin{tabular}[c]{|c||c||r|r|r||r|r|r||r|r|r|| } \hline \multicolumn{1}{|c||}{\textbf{$\lvert A \rvert$}} &\multicolumn{1}{|c||}{\textbf{$\lvert B \rvert$}}&\multicolumn {3}{|c||}{\textbf{Nodes Generated}} &\multicolumn{3}{|c||}{\textbf{Nodes Evaluated}}&\multicolumn{3}{|c||}{\textbf{Time Taken}}\\ \cline{3-11} & &{XCBS} &{XCBSA} &{XA-Eff} &{XCBS} &{XCBSA} &{XA-Eff} &{XCBS} &{XCBSA} &{XA-Eff}\\ \cline{1-11} \multirow{3}{*}{10} &2 &41 &32 &7&23 &19 &7& 1011 &368 &248\\ &3 &56 &39 &9 &33 &21 &9& 1345 &381 &328\\ &5 &81 &55 &6 &46 &38 &6& 351 &352 &285\\ \cline{1-11} \multirow{3}{*}{20} &2 &125 & 108 &9&32 & 20&9& 1823 & 1048 &906\\ &3 & 156 & 132 &9 &76 &48 &7& 2047 &1429 &1081\\ &5 &161 &159 &6 &41 &35 &6& 1893 &1251 &843\\ &10 &218 &189 &15&125 &78 &10 &4924 &1783 &1294\\ \cline{1-11} \multirow{3}{*}{30} &2 &173 &152&18&44 & 27&18&7591 &3561 &2680\\ &3 &212 &173 &15 &119 &84 &12 &9334 &5839 &3901\\ &5 &225 &169 & 23&157 &125 &17&12590 &7598 &5998\\ &10 &318 &228 & 43&216 &163 &37&23459 &10231 &8921\\ &15 &572 &432 & 71&347 &216 &56&59011 &32054 &12116\\ \hline \end{tabular} } \caption{Evaluation of XCBS, XCBS-A , XCBSA-Eff with Deeper-first heuristic (XA-Eff) for CT-nodes generated, CT-Nodes explored and time taken.} \label{tab:XCBSA-Eff Eval} \end{table} \subsection{Results} The comparative performance of the efficiency of the new approach XCBSA-Eff, with the Deeper-first heuristic, was carried out with respect to XCBS and XCBS-A. The primary difference expected was in terms of the number of CT-nodes generated and number of CT-nodes evaluated. The test suite comprised a grid based network, with uniform length roads. The agents themselves were homogeneous in terms of speed and length, however their source and destination locations were randomly decided to ensure that the path-length are uniformly maintained. \\ \indent The Table~\ref{tab:XCBSA-Eff Eval} captures the comparative performance of the three approaches. It is seen that overall, XCBSA-Eff performs better than XCBS and XCBSA, in terms of the number of nodes generated, evaluated and consequently time taken to arrive at the solution. However we bring out a few points to note. First, the difference between the number of nodes generated and evaluated in XCBSA-Eff is not very significant. This is primarily because the homogenity of the road network and agent characteristics leads to large number of alternative solutions of the same cost, which are all put in the Potential Set. In a non-uniform road network, the number of nodes generated and evaluated in terms of XCBSA-Eff is expected to be greatly different, however it will always be lesser than that generated by either XCBS or XCBS-A. The second point is that the number of cascading conflicts has a direct influence on the number of nodes which are generated and explored. This is seen in some rows, where though the number of agents and blocks were higher, lesser number of cascading conflicts resulted in lesser number of nodes being generated and explored both for XCBSA and XCBSA-Eff. \section{XCBS-Local Awareness (XCBS-LA)}\label{xcbsla} In XCBS-A, one agent from every conflict block is replanned while the plans of all other agents remain unchanged. This ensures that the search down a branch terminates but the drawback is that singleton agents' plans remain unchanged, which generates a bias in favor of the singleton agent blocks. This bias sometimes keeps the algorithm from arriving at an optimal solution. \\ \indent Towards this, we propose a revised approach, XCBS-Local Awareness (XCBS-LA), which explores all possibilities of plans without a bias and leads to an optimal solution. The principle difference between XCBS-LA and XCBS-A lies in conflict resolution, which happens among agents within the same partition block, without awareness of agents of other blocks. Since in this mechanism any agent is looking to resolve conflicts only with agents in its own block, we have termed this approach as XCBS-Local Awareness. The conflict resolution leads agents in the same block to make a \textit{commitment} to the resolved plans of each other, which is maintained down the branch of the Constraint Tree.\\ \begin{definition} A \textit{commitment} $C$, is a binary relation on $A$, such that \begin{equation} aCb = \{constraints(b) \cup plan(b)| a,b \in A\} \end{equation} The commitment relation implies that the plan of agent $a$ satisfies all constraints of agent $b$ and those imposed by the plan of agent $b$. By definition itself, $C$ is asymmetric, and as it maintains the commitments it made with itself in the parent CTnode, hence $C$ is also reflexive. \end{definition} \indent In XCBS-LA, the High-Level Search and Validate procedures remain the same as in XCBS-A, however, the Conflict Resolution is revised as discussed in the following section. \begin{algorithm} \caption{\textbf{ResolveConflict $N_e$}}\label{resolveConflict-LA} \begin{algorithmic}[1] \Procedure{ResolveConflict}{$N_e$} \For {each non-singleton block $b_i$ in partition} \State $P^{'}_{i}$ = BlockLevelSearch($b_i, N_e$). \EndFor \State $\mathfrak{B} \gets $combinations of $P^{'}_{i}$ \For {each $\mathfrak{b} \in \mathfrak{B}$ } \State Child CT-node $N_c \gets P^{'}_{b}$. \State Compute Cost($N_c$). \State $O \gets O \cup N_c$ \EndFor \EndProcedure \end{algorithmic} \end{algorithm} \subsection{Conflict Resolution} \indent Once a partition of the agents into blocks of mutually conflicting agents is created, in XCBS-LA, the ResolveConflict is invoked as shown in Algorithm~\ref{resolveConflict-LA}. In XCBS-LA, the conflicts are resolved by ensuring that agents within the same block generate an optimal conflict free plans with respect to each other, ignoring the plans of agents in other blocks. Any optimal MAPF algorithm can be adopted for generating plans for the agents in the same block. We have used XCBS in our implementation. Thus the BlockLevelSearch in Line 3 of the algorithm, executes XCBS on the agents in a block. The revised plans $P^{'}_{i}$ are composed by the Central Agent into child CT-node. If $N_e$ resulted in $j$ non-singleton blocks of partition, there will be $j^2 -1$ child CT-nodes generated.\\ \subsection{Block Level Search} \indent An agent $a_i$ makes a \textit{commitment} with an agent $a_j$, if the plan and constraints of $a_j$ are satisfied by $a_i$ to generate a consistent solution. In Block Level Search, the XCBS algorithm is invoked for each non-singleton block of the partition. The XCBS call returns an optimal conflict-free solution for all the agents in the block. This results in each agent establishing a commitment with respect to the other agents and their generated plan. Once a commitment is established, thereafter, anytime an agent $a_i$ is replanned by XCBS, it will get its constraints with respect to the current constraints and plans of all other agents $a_j$ with which it has a commitment.\\ \subsection{Theoretical Analysis} \begin{lemma} \label{XCBSLA-Lemma1}Given any two agents $a_i$, $a_j$, if $a_i$ makes a commitment with respect to $a_j$ in a branch of the CT, it will not conflict with it further down in that branch. \end{lemma} \begin{lemma} \label{XCBSLA-Lemma2}Down the branch of a tree, the commitments of an agent with others, leads to more constraints in its plans and hence the cost of the individual plan will be non-decreasing down a branch of the CT.\end{lemma} \begin{lemma}If $\mathfrak{S}$ be the set of all optimal solutions for a given MAPF instance, then any $S \in \mathfrak{S} $ will be generated by XCBS-LA in the CT.\end{lemma} Let us consider the case by contradiction, let $\exists S \in \mathfrak{S}$, such that $S$ is not in CT. Since $S$ comprises conflict free plans of all the agents, it implies that the plan of atleast one of the agents, say $a_i$, is different from the solutions in the CT. If $P(a_i)$ is its most optimal plan, then it will be there in $N_r$ of CT. Further, if it does not conflict with any other agent plan, then $P(a_i)$ will also be present in the child-CT nodes, because plans are changed only if there is a conflict. Hence if $P(a_i)$ is the optimal plan of the agent $a_i$ it will be in CT. Now we consider the second case, i.e. $P(a_i)$ is not the most optimal plan of agent $a_i$, which implies it has conflicts with one or more agents, say $a_j$. Now XCBS generates the optimal plan for the block of agents comprising $a_i$ and $a_j$ and gives the optimal plan for the block. Since XCBS is proven to be optimal, the plan generated by XCBS for $a_i$ will be optimal and will be part of CT. Thus, in both the cases, the assumption is contradicted.\\ \textbf{Theorem 1} \textit{XCBS-LA is optimal. }\\ Proof: The CT contains all the possible combinations of plans of the agents as CT-nodes, which are explored based on their increasing cost. When a least code CT-node is found to be valid, all other remaining CT-nodes to be explored, are either of the same cost or higher. Therefore any other valid unexplored solution will either be of the same cost or higher as per Lemma~\ref{XCBSLA-Lemma2}. Hence the solution found is optimal. \\ \textbf{Theorem 2} \textit{XCBS-LA is complete. }\\ Proof: A CT-node can expand into a finite number of child-CT nodes. Further, on exploring down a branch of a tree, as per Lemma~\ref{XCBSLA-Lemma1}, once an agent makes a commitment, it will not conflict with the other agent down the tree. Hence either all agents eventually will form commitments with each other, or remain mutually exclusive, thereby resulting in a valid solution. \subsection{Results} The performance of XCBS-LA was evaluated against four approaches namely the priority based Greedy algorithm, the XCBS, the XCBS-A and XCBS-A(Eff). A test-suite for a 100$\times$100 grid network with 50 agents was generated such that in their initial plans the agents could be split into blocks of definite sizes. These block sizes were a key factor in the comparison of the performance of the algorithms. \indent The evaluation results are captured in Figure~\ref{fig:XCBS_LA} for the time taken and the quality of the solution. As seen in the Figure~\ref{fig:XCBSLA_time}, in terms of time taken to arrive at a solution, XCBS-LA performs poorly as compared to XCBS-A or XCBS-A(Eff), though better than XCBS. This can be attributed to the fact that it internally invokes XCBS, which takes time depending on the number of agents in the block. The quality of the solution is compared in terms of the sum-of-plan costs. It is observed that XCBS-LA gives the optimal solution, same as XCBS and better than the other approaches, as shown in Figure~\ref{fig:XCBSLA_qlty}. \begin{figure} \begin{subfigure}{0.4\textwidth} \includegraphics[scale=0.33]{10} \caption{Comparison of time taken to arrive at solution} \label{fig:XCBSLA_time} \end{subfigure} \hspace{35pt} \begin{subfigure}{0.4\textwidth} \includegraphics[scale=0.33]{11} \caption{Comparison of solution quality, in terms of Plan Cost. } \label{fig:XCBSLA_qlty} \end{subfigure}% \caption{Figure shows the comparative performance of XCBS-LA with respect to other approaches. } \label{fig:XCBS_LA} \end{figure} \section{CONCLUSION}\label{conclusion} In this paper, we have looked into an approach for multi agent path finding for spatially extended agents. We have analysed a distributed algorithm called eXtended Conflict Based Search with Awareness(XCBS-A) for conflict-free path finding of spatially extended agents. XCBS-A was successfully tested for several agents over different types of networks. The comparative performance of XCBS-A with four other approaches in terms of agent characteristics, plan characteristics and road network characteristics indicate that XCBS-A performs significantly better than the other algorithms. We have been able to demonstrate the performance of the algorithm over distributed machines using a multi agent framework JADE, which makes it a good solution for on-field deployment. \\ The memory footprint of the XCBS-A algorithm was reduced by a memory-efficient version of the XCBS-A which tries to prune the search tree, CT, by pushing nodes of similar costs into a Potential Set. This reduces the size of the CT and also helps in reducing the number of nodes evaluated to arrive at a solution. \\ Finally, we proposed another approach namely, the eXtended Conflict Based Search with Local Awareness (XCBS-LA). This algorithm overcomes the bias which XCBS-A introduces in favour of singleton agents or agents which do not conflict with any other agents. This algorithm guarantees optimal solution though at a cost of a higher processing time as compared to XCBS-A. \\ In further steps, we need to look into using the network and the agent characteristics as heuristics to prune the CT in case of XCBS-LA and lead to reduction in the processing time. Further, the performance of these algorithms varies depending on the number of casacading conflicts, nature of the road network etc. Hence a framework which could analyse the characteristics of the problem and then choose the appropriate algorithm for an efficient and quick solution is another area to be looked into. Another direction of research also needs to be in the line of faster conflict-detection and resolution. These topics remain the focus of future research work in this area. \bibliographystyle{apacite}
{'timestamp': '2020-09-22T02:14:12', 'yymm': '2009', 'arxiv_id': '2009.09355', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09355'}
arxiv
\section{Introduction} Synthetic data is a data object that is artificially created rather than collected from actual events. It is widely used in applications like harmonizing multiple data sources or augmenting existing data. In many practical settings, sensitive information such as names, email addresses, phone numbers are considered personally-identifiable, and hence are not releasable. However, these fields are natural keys to combine multiple data sources collect by different organizations at different times. To overcome this, synthetic data generation becomes a very attractive alternative to obtaining data for practitioners. To efficiently produce high quality data, we study a procedure called downscaling, which attempts to generate high-resolution data (e.g., individual level records) from multiple low-resolution sources (e.g., averages of many individual records). Because low-resolution data is no longer personally-identifiable, it can be published without concerns of releasing personal information. However, practitioners often find individual level data far more appealing, as aggregated data lack information such as variances and distributions of variables. For the downscaled synthetic data to be useful, it needs to be \textit{fair} and \textit{consistent}. The first condition means that simulated data should mimic realistic distributions and correlations of the true population as closely as possible. The second condition implies that when we aggregate downscaled samples, the results need to be consistent with the original data. A more rigorous analysis is provided in the later section. Synthetic data generation is often seen as a privacy-preserving way to combine multiple data sources in cases where direct collection is difficult or when common keys among multiple sources are missing. In applications where large-scale data collection involves manual surveys (e.g., demographics), or when the collected data is highly sensitive and cannot be fully released to the public (e.g., financial or health data), synthetically generated datasets become an ideal substitute. For example, due to privacy laws such as the General Data Protection Regulation \cite{eu-269-2014}, organizations across the world are forbidden to release personally identifiable data. As a result, such datasets are often anonymized and aggregated (such as geographical aggregation, where variables are summed or averaged across a certain region). Being able to join the lower-resolution sources, therefore, is a key step to reconstruct the full information from partial sources. Common techniques for synthetic data generation are synthetic reconstruction (SR) \cite{beckman1996creating} and combinatorial optimization (CO) \cite{huang2001comparison,voas2000evaluation}. Existing approaches have specific data requirements and limitations which usually cannot be easily resolved. To address these challenges, we propose a new framework called \textsc{SynC}\xspace (\textbf{Syn}thetic Data Generation via Gaussian \textbf{C}opula) to simulate microdata by sampling features in batches. The concept is motivated by \cite{jeong2016copula} and \cite{kao2012dependence}, which are purely based on copula and distribution fitting. The rationale behind our framework is that features can be segmented into distinct batches based on their correlations, which reduces the high dimensional problem into several sub-problems in lower dimensions. Feature dependency in high dimensions is hard to evaluate via common methods due to its complexity and computation requirements, and as such, Gaussian copula, a family of multivariate distributions that is capable of capturing dependencies among random variables, becomes an ideal candidate for the application. In this study, we make the following contributions: \begin{enumerate} \item We propose a novel combination framework which, to the best of our knowledge, is the first published effort to combine state-of-the-art machine learning and statistical instruments (e.g., outlier detection, Gaussian copula, and predictive models) to synthesize multi source data. \item We perform simulation studies to varify \textsc{SynC}\xspace's performance as a privacy-preserving algorithm and its ability to reproduce original datasets. \item We demonstrate \textsc{SynC}\xspace as a feature engineering tool, as well as an alternative to data collection in situations where gathering is difficult through a real-world datasets in the automotive the industry. \item We ensure the methodology is scalable at the production level and can easily incorporate new data sources without the need to retrain the entire model. \item To foster reproducibility and transparency, all code, figures and results are openly shared\footnote{See supplementary material available at \url{https://github.com/winstonll/SynC}}. The implementation is readily accessible to be adapted for similar use cases. \end{enumerate} \section{Related Works} \subsection{Synthetic Reconstruction} Synthetic reconstruction (SR) is the most commonly used technique to generate synthetic data. This approach reconstructs the desired distribution from survey data while constrained by the marginal distributions. Simulated individuals are sampled from a joint distribution which is estimated by an iterative process to form a synthetic population. Typical iterative procedures used to estimate the joint distribution are iterative proportional fitting (IPF) and matrix ranking. The IPF algorithm fits a n-dimensional contingency table base on sampled data and fixed marginal distributions. The inner cells are then scaled to match the given marginal distribution. The process is repeated until the entries converge. IPF has many advantages like maximizing entropy, minimizing discrimination information \cite{ireland1968contingency} and resulting in maximum likelihood estimator of the true contingency table \cite{little1991models}. However, IPF is only applicable to categorical variables. The \textsc{SynC}\xspace framework incorporates predictive models to approximate each feature, which can be used to produce real-valued outputs as well and probability distribution that can be sampled from to produce discrete features. \subsection{Combinatorial Optimization} Given a subset of individual data with features of interest, the motivation behind combinatorial optimization (CO) is to find the best combination of individuals that satisfy the marginal distributions while optimizing a fitness function \cite{barthelemy2013synthetic}. CO is typically initialized with a random subset of individuals, and individuals are swapped with a pool of candidates iteratively to increase the fitness of the group. Compared to SR based approaches, CO can reach more accurate approximations, but often at the expense of exponential growth of computational power \cite{wong2013optimizing}. \subsection{Copula-Based Population Generation} Copula is a statistical model used to understand the dependency structures among different distributions (details are discussed in Section \textit{Proposed Framework}), and has been widely used in synthetic data generation tasks \cite{kao2012dependence}. However, downscaling is not possible, and the sampled data stay at the same level of granularity as the input. Jeong et al. discuss an enhanced version of IPF where the fitting process is done via copula functions \cite{jeong2016copula}. Similar to IPF, this algorithm relies on the integrity of the input data, which, as discussed before, can be problematic in real-world settings. Our method, \textsc{SynC}\xspace, is less restrictive on the initial condition of the input dataset as it only requires aggregated level data. Therefore \textsc{SynC}\xspace is more accessible compared to previous approaches. \section{Proposed Framework} \label{proposed_method} \subsection{Problem Description} Throughout the rest of this paper, we assume that the input data comes from many different sources, $X_1,...,X_T$. Each source, called a batch, takes the form $X_t = [X_1, ..., X_M]$, where $X_m = [X_m^1, ..., X_m^{D_t}]$ is a $D_t$ dimensional vector representing input features of batch $t$. Together, there are $D$ features across the entire $B$ batches. Each $m \in M$ represents an aggregation unit containing $n_m$ individuals, and every individual belongs to exactly one $m$. All batches contain the same aggregation units, however, each has their own set of features. When referring to specific individuals within an aggregation unit, we use $x_{m,k}^d$ to denote the $d^{th}$ feature of the $k^{th}$ individual who belongs to the aggregation unit $m$. For every feature $d \in D$ and aggregation unit $m$, we only observe $X_m^d = \sum_{k=1}^{n_m} x_{m,k}^d/n_m$ at an aggregated level. We use the term \textit{coarse data} to refer to this type of low-resolution observations. In practice, aggregation units can be geopolitical regions, business units or other types of segmentation that make sense for specific industries. The goal of \textsc{SynC}\xspace is to combine all batches in order to reconstruct the unobserved $\{x_{m,1}^d,\cdots, x_{m,n_m}^d\}$ for each feature $d$ in every batch and aggregation unit $m$. We assume that $M$ is sufficiently large, especially relative to the size of each $D_t$, so that fitting a reasonably sophisticated statistical or machine learning model is permissible, and we also assume that the aggregation units, $n_m$, are modest in size so that not too much information is lost from aggregation and reconstruction is still possible. Thus for a $M \times D$ dimensional coarse data $X$, the reconstruction should have dimensions $N \times D$, where $N = \sum_{m=1}^{M} n_m$ is the total number of individuals across all aggregation units. This finer-level reconstruction is referred to as the \textit{individual data}. \textsc{SynC}\xspace is designed to ensure the reconstruction satisfies the following three criteria \cite{munnich2003simulation}: \begin{enumerate} \item For each feature, the marginal distribution of the generated individual data should agree with the intuitive distribution one expects to observe in reality. \item Correlations among features of the individual data need to be logical and directionally consistent with the correlations of the coarse data. \item Aggregating generated individual data must agree with the original coarse data for each $m \in M$. \end{enumerate} The main idea of \textsc{SynC}\xspace is to simulate individuals by generating features in batches based on core characteristics and scaling the result to maintain hidden dependency and marginal constraints. As illustrated in Fig. \ref{fig:flowchart}, \textsc{SynC}\xspace contains one preliminary phase and four key phases. Their formal descriptions are provided below. \begin{figure*}[ht] \centering \includegraphics[scale=0.4]{Flowchart_new.pdf} \caption{\label{fig:flowchart}Flowchart of the \textsc{SynC}\xspace framework} \end{figure*} \subsection{Phase 1: Outlier Removal} Outliers are the deviant samples from the general data distributions that may be a result of recording mistakes, incorrect responses (intentionally or unintentionally) or tabulation errors\cite{zhao2019lscp,li2020copod}. The presence of outliers can lead to unpredictable results \cite{zhao2019pyod,zhao2020suod}. Microsimulation tasks are sensitive to outliers \cite{passow2013adapting}, and conducting outlier detection before any analysis is therefore important. Outlier removal methods are often selected by the underlying assumptions and the actual condition of the data. Notably, the necessity of this process depends on the practitioners' definition of abnormality, although it is recommended in most cases. In Section \ref{sec:results_applications}, we study \textsc{SynC}\xspace's performance with and without the Outlier Removal Step. \subsection{Phase 2: Dependency Modeling} \label{Dependency Modeling} We propose to use the copula model to address criteria i) and ii) since copula models, with their wide industrial applications, have been a popular choice for multivariate modeling especially when the underlying dependency structure is essential. First introduced by Sklar \cite{sklar1959fonctions}, a copula is a multivariate probability distribution where the marginal probability distribution of each variable is uniform. Let $X=(x_1, x_2...x_D)$ be a random vector in $\mathbb{R}^D$, and the marginal cumulative distribution function be \(P_i(x) = Pr[x_i<x]\), define \(U_i\) as \small \begin{equation} U = (u_1, u_2, ..., u_D) = (P_1(x_1), P_2(x_2), ..., P_D(x_D)) \end{equation} \normalsize A copula of the random vector \(X\) is defined as the joint CDF of a random uniform vector U: \small \begin{equation} C(u'_1, u'_2, ... u'_D) = Pr(u_1<u'_1, u_2<u'_2, ..., u_D<u'_D) \end{equation} \normalsize \RestyleAlgo{ruled} \begin{algorithm}[!htp] \small \SetAlgoLined \KwData{Coarse Data} \KwResult{Simulated Individual Data} initialization\; X = input coarse data \\ M = number of aggregated unit\\ D = dimension of coarse data\\ $\Sigma$ = $D \times D$ covariance matrix of $X$\\ $\Phi$ = cumulative distribution function (CDF) of a standard normal distribution \\ $F^{-1}_d$ = inverse CDF of the marginal distribution of the $d^{th}$ component of $X$\\ \For{$m$ in $1...M$}{ Draw $Z_{m} = Z_m^1, \cdots, Z_m^D \sim N(0,\Sigma)$, where $N(\mu, \Sigma)$ denotes a $d$-dimensional Normal distribution with mean $\mu$ and covariance matrix $\Sigma$ \\ \For{$d$ in $1...D$}{ $u_m^d = \Phi(Z_m^d)$\\ $y_m^{'d} = F^{-1}_d(u_m^d)$ \\ (This implies that $Y_m^{'d}$ follows the desired distribution) \\ } \textbf{Return} $Y'_m = \{Y_m^{'i}\}_{i=1}^d$ } \textbf{Return} $Y' = \{Y'_j\}_{j=1}^M$ \caption{Gaussian copula sampling} \label{cop sample} \end{algorithm} In other words, we can describe the joint distribution of a random vector $X$ using its marginal distributions and some copula functions. Additionally, Sklar's Theorem states that for any set of random variables with continuous CDFs, there exists a unique copula as described above. It allows us to isolate the modeling of marginal distributions from their underlying dependencies. Sampling from copulae is widely used by empiricists to produced deserved multivariate samples based on a given correlation matrix and the desired marginal distributions of each of the components. Nelsen \cite{nelsen2007introduction} outlines a simpler version of Algorithm \ref{cop sample} for bivariate sampling, which can be generalized to multivariate cases. In order to properly specify $F^{-1}_d$, we make a reasonable assumption that the size of each aggregation unit is significant and diverse enough such that $var(X_m^d)$ is approximately constant $\forall m$. This assumption implies that $var(X_m^d)$ can be estimated by $(\sum_{k=1}^{m} (X_m^d)^2 - \bar{X}_.^d)/M-1$, the unbiased sample variance estimator. Thus, given $\mu_m^d$ is observed from aggregation unit averages, $F^{-1}_d$ can be uniquely specified so long as we are willing to make an assumption on the distribution. For example, if the desired output is a positive continuous variable (such as income), we assume $F_{Y_m^d}(y)$ follows a lognormal distribution with mean $\mu_m^d$ and standard deviation $\sigma_m^d$. In the case of categorical variables, we assume $F_{Y_m^d}(y)$ follows a beta distribution with parameters $\alpha$ and $\beta$ such that $\frac{\alpha}{\alpha+\beta} = \mu_m^d$ and $\frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)} = (\sigma_m^d)^2$. Our assumptions imply that $\mu_m^d$ and $\sigma_m^d$ can be derived from coarse data mean and standard deviation for feature $d$. \small \begin{equation} \mu_m^d = \textit{mean of feature $d$ in aggregation unit $m$} \end{equation} \begin{equation} \sigma_m^d = \sigma^d * \sqrt{M} * \sqrt{n_m} \end{equation} \normalsize Algorithm 1 incorporates the above assumptions with Gaussian copula to satisfy criteria i) and ii). \subsubsection{Gaussian Copula} \hfill\\ Being one of the most popular and simple form of copula models, the Gaussian Copula is easy to interpret, implement and sample (and will be the copula used in Section \ref{sec:results_applications}). It is constructed from multivariate normal distribution through probability integral transformation. For a given covariance matrix, $\Sigma$, Gaussian Copula requires the joint distribution of given variables can be expressed as: \small \begin{equation} C_{\Sigma}^{\text { Gauss }}(u)=\Phi_{\Sigma}\left(\Phi^{-1}\left(u_{1}\right), \dots, \Phi^{-1}\left(u_{d}\right)\right) \end{equation} \normalsize where $\Phi$ is the CDF of normal distribution. \small \begin{equation} V = \left({\Phi^{-1}\left(u_{1}\right)}, \ldots, {\Phi^{-1}\left(u_{d}\right)}\right) \end{equation} \normalsize \small \begin{equation} c_{\Sigma}^{\mathrm{Gauss}}(u)=\frac{1}{\sqrt{\operatorname{det} \Sigma}} \exp (-\frac{1}{2}\left(V \cdot\left(\Sigma^{-1}-I\right)\cdot V^{t} \right)\\ \end{equation} \normalsize Because of the popularity of the normal distribution and the other advantages mentioned above, Gaussian copula has been one of the most widely adopted dependence models. The earliest application of Gaussian Copula was in the finance industry: Frees and Valdez applied the technique to insurance pricing \cite{frees1998understanding}, while Hull and White used it in credit derivative pricing \cite{hull2006valuing}. More recently, the application of Gaussian copula models have been found in many fields such as linkage analysis \cite{li2006quantitative}, functional disability data modeling\cite{dobra2011copula} and power demand stochastic modeling \cite{lojowska2012stochastic}. \subsubsection{Archimedean Copula}\hfill\\ Like the Guassian copula models, Archimedean copula modles are defined more generally as: \small \begin{equation} C\left(u_{1}, \ldots, u_{p}\right)=\psi\left(\sum_{i=1}^{p} \psi^{-1}\left(u_{i}\right)\right) \end{equation} \normalsize where $\psi :[0,1] \rightarrow[0, \infty)$ is a continuous, strictly decreasing and convex function \footnote{$(-1)^{k} d^{k} \psi(x) / d^{k} x \geq 0$ for all x $\geq$ 0 and $k=1$, \ldots, $p-2$, and $(-1)^{p-2} \psi^{p-2} (x)$ \text { is non-increasing and convex.}}. With different $\psi$ functions, Archimedean Copula have many extensions. The popular cases are Clayton's Coupla which as been used in bivariate truncated data modelling \cite{wang2007analysis} and hazard scenarios and failure probabilities modelling \cite{salvadori2016multivariate}, and Frank's Copula, which has been used in storm volume statistics analysis \cite{salvadori2004analytical} and drought frequency analysis \cite{wong2013comparison}. Archimedean copulae have gained some attention in recent years and their unique generator functions have outstanding performances in particular situations. Yet the fitting process for the generator function can be computational expensive. As \textsc{SynC}\xspace preforms data generation in batches and wishes to be computationally efficient, we will use Gaussian copula for modeling the dependency structure of features. \subsection{Phase 3: Predictive Model Fitting} In theory, we could construct a complex enough covariance matrix with all variables, and then fit a giant copula model using Algorithm 1. However, two reasons make this approach nearly impossible: 1) the curse of dimensionality makes it difficult when $D$ is sufficiently large, and 2) certain columns of $X$ may update more frequently, and it is inefficient to train new models each time. In this section, we introduce an alternative method, Algorithm \ref{cop sample}, to resolve this issue with minimal computation requirements. Starting with the core batch $T_0$, a subset of $X$ containing the utmost important features selected from \textbf{Phase 0}, we apply Algorithm \ref{cop sample} to $T_0$ and the resulting data set, $Y'$, should satisfy the first two criteria mentioned in \textbf{Phase 2}. Secondly, together with $T_0$, all $T_j$ are inputted into Algorithm \ref{batch sample} sequentially. The resulting sampled data set, $K_j$, contains features from $T_0$ and $T_j$. However, a problem immediately presents: the sampled individuals in $K_j$ do not match those from $Y'$. Furthermore, individuals sampled in each $K_j$ does not necessarily match the sampled individuals in $K_l$ (for $l \neq j$). To fix it, we can train a predictive model on $K_j$ to approximate the distribution of $P(T_j \mid S = s)$, and use the model to predict the values of features $K_j$ given their values of the core features from $X'$. The choice of the predictive model depends on the complexity and nature of the data on a case by case basis. Finally, we merge the predicted values with the original data set $Y$ and iterate until all features are processed. This step is summarized in Algorithm \ref{batch sample}. \RestyleAlgo{ruled} \begin{algorithm}[!tp] \small \SetAlgoLined \KwData{Coarse Data} \KwResult{Simulated Individual Data} initialization\; $X$ = Input coarse data\\ $B$ = total number of batches of non-core features\\ $S$ = predefined set of core features\\ $T_j$ = $j^{th}$ batch of non-core features\\ $Y'$ = Initial sampled individual data with only core features using Algorithm \ref{cop sample}\\ \For{$j$ in $1...B$}{ $X_j' = X[S\cup T_j]$\\ $K_j$ = Sampled data by applying Algorithm \ref{cop sample} to $X_j'$\\ $F(T_j \mid S = s)$ = an approximated distribution function trained on $K_i$\\ $Q_j$ = $\argmax_{Q}$ $F(Q\mid S = Y)$\\ $Y'$ = $Y'\Join Q_j$ \text{where $\Join$ is the natural join operator} } \textbf{Return} $Y'$ \caption{Batch sampling via Gaussian copula} \label{batch sample} \end{algorithm} \subsection{Phase 4: Marginal Scaling} The final step is to address criterion iii), which is to ensure sampled individual data agree with the input coarse data. If $Y^d$ is categorical with $c^d$ classes, we constrain the output, $Y'^d$ to the mean vector of $m$, $\mu_m^d = n_m \times X_m^d$. As $n_m$ is the population count of aggregation unit $m$, and $X_m^d$ is the observed proportion vector for feature $d$, $\mu$ is the count of each classes to be assigned to individuals for $m$. One thing to note that the predicted values from \textbf{Phase 3} for individual $k$ in aggregated unit $m$, represented by $p_{m,k}^d=\{p_{m, k, i}^d\}_{i=0}^c$, is a probability distribution. Hence it is natural to assume $Y^d \sim Multi(1, c^d, p_{m,k}^d)$, where $Multi(n, c^d, p^d)$ denotes a multinomial distribution with $n$ samples, each taking a category between $c^1, ..., c^d$, with probabilities $p^1, ..., p^d$. To determine the exact class of individual $k$, we generate a random sample from the distribution. After initial sampling, the percentage of each category may not match the marginal constraint. To resolve this, whenever a sample is produced, we subtract 1 from the corresponding dimension of the marginal distribution and resample if the corresponding dimension has already reached 0. The is summarized in Algorithm \ref{scaling}. If $Y^d$ is continuous, the sampled mean and variance should be in proximity with the original coarse data given the way $F^{-1}_d$ is constructed in \textbf{Phase 2}. In case of small discrepancy, we apply the standard scaling of $Y' - (\mu_{sample} - \mu_{core})$ to horizontally shift each data point by the difference between sample mean and the coarse data mean. \RestyleAlgo{ruled} \begin{algorithm}[!t] \small \SetAlgoLined \KwData{Simulated Individual Data} \KwResult{Individual Data with Categories Assigned} initialization\; $Y'$ = Initial sampled individual data outputted by Algorithm \ref{batch sample}. There should be $n_m$ individuals for each aggregation unit.\\ $c^d = [c_1^d,...,c_k^d]$ categories for dimension $d$. \\ $\mu_{m}$ = The marginal vector for aggregation unit $m$. \\ \For{$d$ in $1...D$}{ \For{$i$ in $1...m$}{ \For{$j$ in $1...n_i$}{ $p_i = Y'[j, :]$\\ Draw class $\Tilde{c^d}$ from $Multi(1, c^d, p_j)$\\ \textbf{If} $\mu_{i}[\Tilde{c^d}] > 0$ \\ \textbf{Then} $Y_j = \Tilde{c^d}$ and $\mu_{i}[\Tilde{c^d}] = \mu_{i}[\Tilde{c^d}] - 1$ \\ \textbf{Else} Repeat lines 9-11.\\ } \textbf{Return} $Y_j = [Y_1,...,Y_{n_i}]$ } \textbf{Return} $Y = [Y_1,...,Y_m]$ } \caption{Marginal Scaling of Output Data} \label{scaling} \end{algorithm} \section{Results and Applications} \label{sec:results_applications} In this section, we demonstrate the validity of \textsc{SynC}\xspace by a number of simulation studies, as well as show how \textsc{SynC}\xspace can be used in real world applications. Through two demonstrations, we show: \begin{enumerate} \item \textsc{SynC}\xspace's reconstruction ability by measuring how close the generated dataset is to its original unaggregated version, \item the improvements on model accuracy when \textsc{SynC}\xspace is used as a feature engineering tool when training data has limited number of features. \end{enumerate} For the first experiment, we use a dataset from a Canadian market research company with 65,000 respondents evenly selected across Canada. For the next two experiments, our data comes from the 2016 Canadian National Census, which is collected by Statistics Canada and compiled once every five years. The census is aggregated at the postal code level and made available to the general public. There are 793,815 residential postal codes in Canada (in the format L\#L\#L\#, where L is a letter and \# is a digit), with an average of 47 residents per postal code. The dataset contains more than 4,000 variables ranging from demographics, spending habits, financial assets, and social values. Table \ref{census data} illustrates a subset of this dataset with 3 postal codes and 4 variables. All datasets are made available in our GitHub repository. \begin{table}[!tp] \resizebox{\columnwidth}{!}{ \begin{tabular}{c|c|c|c|c} \hline \textbf{Postal} & \# \textbf{Population} & \textbf{Avg Age} & \makecell{\textbf{\% with} \\ \textbf{Mortgage}} & \makecell{\textbf{\% Speaks} \\ \textbf{two languages}} \\ \hline \hline M5S3G2 & 467 & 35.1 & 0.32 & 0.69 \\ \hline V3N1P5 & 269 & 37.2 & 0.35 & 0.67 \\ \hline L5M6V9 & 41 & 49.1 & 0.67 & 0.43 \\ \hline \end{tabular} } \caption{An excerpt of three variables from the census data}\label{census data} \end{table} \subsection{Reconstruction Accuracy Assessment} To assess \textsc{SynC}\xspace's performance as a privacy preserving algorithm, we run experiments by taking a dataset, identify an appropriate aggregation unit and group individual records to form proportions and/or averages. Then we try to reconstruct the original dataset by applying \textsc{SynC}\xspace to the aggregated version. As the first of its kind, we found very little competing implementations of similar algorithms, and as such, we compare \textsc{SynC}\xspace's performance against itself in different cases. Specifically, we study \textsc{SynC}\xspace's performance with different aggregation unit sizes, as well as whether outlier removal (OR) was included. \subsubsection{Data Description} \hfill\\ We use a dataset from a Canadian market research company with 65,000 respondents evenly selected across Canada. To keep the computations simple, we use 14 variables from this dataset, which are \textit{Age}, \textit{Gender}, \textit{Ethnicity}, \textit{Income}, \textbf{Education} and whether the respondent uses the internet to \textit{Read News}, \textit{Listen to Podcasts}, \textit{Sports}, \textit{Fashion}, \textit{Food}, \textit{Health}, \textit{Travel} and \textit{Social Media}. Forward Sortation Areas (FSA), which are geographical region in which all postal codes start with the same three characters, are used as aggregation units. \textit{Age} is a categorical variable with 7 classes, \textit{18 or under}, \textit{18-25}, \textit{26-34}, \textit{35-44}, \textit{45-54}, \textit{55-64} and \textit{65+}. \textit{Gender} is a binary variable, taking values of \textit{Male} and \textit{Female}. \textit{Ethnicity} assumes 5 classes (\textit{White}, \textit{Asian}, \textit{Middle Eastern}, \textit{African Canadian} and \textit{Others}. \textit{Income} has 13 classes (intervals of \$10,000 from \$0 up to \$100,000, \$100k-\$125k, \$125k-\$150k and \$150k+). Finally, \textit{Education} has 3 classes, which are \textit{High School or Below}, \textit{Post-secondary} and \textit{Postgraduate}. All internet related variables are binary valued, with \textit{Yes} and \textit{No} as the only two possible values. \subsubsection{Experiment Setup} \hfill\\ We first aggregate the data by FSA, and then reconstruct the original data using \textsc{SynC}\xspace. After the generation, we rank all individuals by age and then gender, and accuracy is measured by comparing the number of matching cells from the raw data and the generated data with the same row number. As an example, the first individual in the raw data is a 20-24 year old female with \$40,000 - \$50,000 income, and uses the internet to read sports, listen to podcast and use social media. In the reconstructed data, the first individual is a 20-24 year old female but with \$50,000 - \$60,000 income and uses the internet to read sports, fashion and travel. In this case, \textsc{SynC}\xspace's accuracy would be $6/12 = 50\%$, as we have correctly predicted \textit{age}, \textit{gender}, the consumption of \textit{sports} related content online, and have also correctly that she does not use internet for \textit{news}, \textit{food} and \textit{health} related content. \subsubsection{Comparison by Aggregation Unit Size} \hfill\\ We run this analysis for all 65,000 individuals, and report our findings in Table \ref{accuracy_n}. In order to properly evaluate \textsc{SynC}\xspace's performance, we give a breakdown of accuracy by the size of the aggregation unit, as well as whether or not the \textit{Outlier Removal Phase} was performed. \begin{table}[!t] \resizebox{\columnwidth}{!}{ \begin{tabular}{c|c|c|c|c|c} \hline \textbf{Agg. Unit Size} & 1-10 (n=45) & 10-25 (n=264) & 25-50 (n=509) & 50-100 (n=238) & 100+ (n=87) \\ \hline \hline \textbf{\% with OR} & 0.414 & 0.339 & \textbf{0.298} & \textbf{0.272} & 0.226 \\ \hline \textbf{\% wihtout OR} & \textbf{0.476} & \textbf{0.346} & 0.283 & 0.256 & \textbf{0.245} \\ \hline \end{tabular} } \caption{Reconstruction accuracy by size of aggregation unit}\label{accuracy_n} \end{table} We can see that reconstruction accuracy varies greatly. For smaller aggregation units, we can, on average expect close to 50\% accuracy in reconstruction, whereas for larger aggregation units, reconstruction accuracy is just over 20\%. This is expected because as the size of the aggregation unit grows, less information gets preserved from only observing averages or proportions of the categories. \subsubsection{Comparison by Variable Categories} \hfill\\ Another way to assess \textsc{SynC}\xspace's performance is to look at accuracy across variables with different numbers of classes. In this particular application, we have 10 variables with 2 classes (\textit{Gender} and all 9 Internet related variables), 1 variable with 3 classes (\textit{Education}), 1 variable with 5 classes (\textit{Ethnicity}), 1 variable with 7 classes (\textit{Age}) and 1 variable with 13 classes (\textit{Income}). Reconstruction accuracy, grouped by variable category sizes, are summarized below, and benchmarked against the baseline measure of assigning by complete random. \begin{table}[!tp] \resizebox{\columnwidth}{!}{ \begin{tabular}{c|c|c|c|c|c} \hline \textbf{Number of Classes} & c=2 & c=3 & c=5 & c=7 & c=13 \\ \hline \hline \textbf{\% with OR} & \textbf{0.800} & \textbf{0.727} & 0.494 & 0.396 & 0.240 \\ \hline \textbf{\% wihtout OR} & 0.783 & 0.705 & \textbf{0.501} & \textbf{0.411} & \textbf{0.268} \\ \hline \textbf{Baseline} & 0.500 & 0.333 & 0.200 & 0.143 & 0.077 \\ \hline \end{tabular} } \caption{Reconstruction accuracy by number of categories}\label{accuracy_c} \end{table} One point worth mentioning is that the effect of including the outlier detection step varies. When fewer numbers of classes are present, the result suggests that outlier is an useful step to include, but when the number of classes increases, the effect of OR seems to diminish. \subsection{\textsc{SynC}\xspace as a Feature Engineering Tool} To assess the performance of \textsc{SynC}\xspace as a feature engineering tool, we collaborate with a global automotive company (hereafter referred to as the "Client") that specializes in producing high-end cars to build a predictive model to better assist their sales team in identifying which of their current customers who have a leased vehicle are interested in buying the car in the next 6 months. This type of analysis is extremely important in marketing, as contacting customers can be both expensive (e.g., hiring sales agents to make calls) and dangerous (e.g., potentially leading to unhappy customers and therefore unsubscribing emails or services). Therefore building accurate propensity models can be extremely valuable. Our experiment contains three steps. 1) We work with the Client to identify internal sales data and relevant customer profiles such as residential postal code, age, gender, 2) we apply \textit{probabilistic matching} to join sampled data together with the Client's internal data to produce an augmented version of the training data, and 3) we run five machine learning models on both the original and the augmented data, and evaluate the effectiveness of \textsc{SynC}\xspace. \subsubsection{Data Description} \hfill\\ There are 7,834 customers who currently lease a specific model of car from the Client in Canada. Our Client is interested in predicting who are more likely to make a purchase in the next 6 months. In Table \ref{auto leasing data} shown in the Appendix, we attach an excerpt of the Client's sale records. For security reasons, names and emails are removed. To augment this dataset, the Client selects 30 variables from the Census, which included information they do not know but could be useful features. The variables includes, demographics (personal and family), financial situations and how they commute to work. We include an excerpt of the sampled individual data obtained by apply \textsc{SynC}\xspace to the Census in Table \ref{auto leasing data}; both datasets are available upon request. \subsubsection{Probabilistic Matching} \hfill\\ A challenge of \textsc{SynC}\xspace as a feature engineering tool is the fact that synthetic population is anonymous. In most applications, enterprise level data sources are individually identifiable through an identifier which may be unique to the company (e.g. customer ID for multiple products/divisions at one company) or multiple companies (e.g. cookie IDs which can be shared between multiple apps/websites). This makes merging different data sources very easy as the identifier can be used as the primary key. By construct, however, synthetic population individuals are model generated from anonymous data, and therefore cannot be joined by traditional means. Here we present an alternative method called \textit{Probabilistic Matching}. Because \textsc{SynC}\xspace produces anonymous information (i.e. data that cannot be attributed to a specific person, such as name, email address or ID), we use age, gender, ethnicity, and profession as good identifiers to the real population. In table 3 we show the first few customers supplied by our industry partner. We also provide the list of synthetically generated persons for postal code V3N1P5 in Appendix Table \ref{V3N1P5}, and use this as an example to demonstrate how probabilistic matching can be done on the first customer. Client data show that a 53 year old male, who lives in the area of V3N1P5 made a lease purchase. In this case, we have three indicative measurement for this customer - this buyer is \textit{53 years old}, \textit{male} and lives in \textit{V3N1P5} (an area in Burnaby, British Columbia, Canada). In our synthetic data, the closet match would be the tenth person, as two of the three indicators (postal code and genders) match precisely, and the last indicators matches closely (age of 54 vs. 53, which is a difference of 1 year). We can conclude that this customer, who leased an SUV of model type 3, is likely to be ethnically Chinese, an immigrant with a bachelor's degree, an income of between \$90k to \$99k and speaks 2 languages. \subsubsection{Method Evaluation} \hfill\\ We train 5 different classifiers on both the partner's data, as well as the augmented dataset to predict whether a customer buys the leased vehicle. We train Logistic Regression (LR), Decision Tree (DT) \cite{hu2019optimal}, Random Forest with 500 tress (RF) \cite{breiman2001random}, SVM with Radial Basis Kernel and 2-Layer Neural Network (NN). Standard grid search cross validation is used to ensure that the best hyperparameters are selected, and the models' performances are summarized in Table \ref{performance_classifier}. \begin{table}[!tp] \resizebox{\columnwidth}{!}{ \begin{tabular}{c|c|c|c|c|c} \hline & \textbf{LR} & \textbf{DT} & \textbf{RF} & \textbf{SVM} & \textbf{NN} \\ \hline \hline \textbf{Original Data} & 0.615 & 0.639 & 0.704 & 0.693 & 0.688 \\ \hline \textbf{Augmented Data} & \textbf{0.662} & \textbf{0.711} & \textbf{0.730} & \textbf{0.806} & \textbf{0.739} \\ \hline \end{tabular}} \caption{Comparisons of accuracy measures of 5 different classifiers trained on original and synthetic population augmented data} \label{performance_classifier} \end{table} In all five cases, augmented data produces a higher classification accuracy than the raw data from our industry parnter. Accuracy increases range from slightly over 2.5\% (RF) to as much as 11\% (SVM), with an average increase of 6.2\%. This increase is both technically significant, as well as practically meaningful, as the Client would easily apply this model to their business and achieve grow their sales. This case study has shown that Synthetic Population is an effective way to engineer additional features to situations where the original training data is limited. As explained in early sections, \textsc{SynC}\xspace takes coarse datasets and generate estimates of individuals that are likely to reside within the given postal code area. Although \textsc{SynC}\xspace does not produce real people, the generated "synthetic" residents both closely resembles the behaviours of true population and is also consistent with the available sources. We demonstrate that it is a viable data augmentation technique. \section{Conclusion and Future Directions} In this work, we propose a novel framework, \textsc{SynC}\xspace, for generating individual level data from aggregated data sources, using state-of-the-art machine learning and statistical methods. To show the proposed framework's effectiveness and boost reproducibility, we provide the code and data used in simulation studies described in Section \ref{sec:results_applications}. We also present a real-world business use case to demonstrate its data augmentation capabilities. As a first attempt to formalize the problem, we see multiple areas where future works can improve upon. First of all, our method relies on Gaussian copulae and this can be further extended by leveraging other families of copula models to better model the underlying dependency structures. Secondly, we use beta and log-normal distributions to approximate marginal distributions for categorical and continuous variables, respectively, and other families of distributions could be considered (e.g., the $\kappa$-generalized model \cite{clementi2016kappa} can be used for money related distributions). Lastly, a better similarity metric can be designed to assess generated data against its original input. \bibliographystyle{./bibliography/IEEEtran}
{'timestamp': '2020-09-22T02:18:27', 'yymm': '2009', 'arxiv_id': '2009.09471', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09471'}
arxiv
\section{Introduction} Adversarial Imitation Learning(AIL) algorithms \cite{gail} \cite{airl} \cite{dac} \cite{kuefler2017imitating} have been shown to achieve state of the art performance on a variety of imitation learning tasks. Performance of AIL algorithms have been primarily evaluated in two kinds of broad settings. The first kind of setting can be characterised as survival based environments. For example, environments in Mujoco like Hopper, Cheetah where the agent is rewarded to survive in the environment by remaining in a set of good states and penalized (by negative rewards or by termination) if it attains states other than these good states. For example, in Hopper the agent gets good rewards for hopping forward as fast as possible. If the agent gets into a set of `bad poses' the episode is terminated. The other setting can be characterised as ``task'' based environments where the agent is rewarded to complete a task (reaching a goal state, interacting with an object in the environment, dodging an obstacle) and so on. The episode terminates once the agent completes the task. However, there is another important setting which hasn't drawn much attention in the Imitation Learning community. The episode may also terminate when the agent has failed to perform the task in a task based scenario. For example, when the agent may alter the environment such that completing the task becomes impossible, such as breaking a glass that the agent was supposed to pick up. These are environments where the agent is rewarded to complete a task, i.e to reach a certain state in the shortest amount of time after which the episode is terminated, however, there are some additional bad terminal states, upon reaching which the episode terminates and the agent doesn't receive a reward. Most of the community has worked on environments which are either purely survival based or purely task based. However, to show that current reward functions are biased, we need to use more complex environments. To that end, we use different environments of the Gym-Minigrid\cite{minigrid} package. This package contains environments with single and multiple terminal states, which would be ideal to test if learning is hindered by the inherent biases in the reward function itself. Our experiments show that existing methods\cite{gail}\cite{dac} often get stuck in a suboptimal policy in task based environments with multiple terminal states. We provide a rough theoretical sketch of the underlying issues in these methods. We also propose a reward function which is able to achieve comparable results in task based environments with single terminal state and performs significantly better than existing methods in task based environments with multiple terminal states. \section{Related Work} Early works in Imitation Learning based on Inverse Reinforcement Learning \cite{irl} focus on recovering a reward function from expert demonstrations which is optimised using Reinforcement Learning. These methods are slow since they require solving the RL objective in the inner loop. From a practical standpoint, the intermediate step of recovering reward function is not really necessary when the goal is to only learn to imitate the expert. Recent works in Adversarial Imitation Learning \cite{gail} \cite{airl} \cite{infogail} \cite{bayesiangail} \cite{goalgail} focus on directly recovering the expert policy without the need for recovering the exact reward function. These methods alleviate the problem of distributional shift faced by some of the more traditional approaches like Behavior Cloning and its variants \cite{bco} \cite{dagger} \cite{rossbagnell} \cite{daume}. GAIL based methods are also very sample efficient than behavior cloning in terms of number of expert trajectories required to recover the expert policy. Although AIL methods have had a fair amount of success in various environments, recent work \cite{dac} has highlighted the implicit bias in the formulation of its reward function which results in degradation of performance in certain environments. The work in Discriminator-Actor-Critic \cite{dac} show how the reward function used in GAIL for training the agent is biased which leads to degradation of performance in certain environments. In GAIL, the agent focuses on how to maximize its rewards from the discriminator, which may not necessarily translate to following the expert policy. In task-based environments, the problem of implicit bias due to zero rewards for terminal states encourages the agent to stay in the environment to collect more positive rewards, hence ignoring the task. Their method worked on the survival based agents, as well as on task-based robotic environments. However, there are no results on the method's performance in task based environments with multiple terminal states. Our experiments show their formulation doesn't work well in such task based environments with multiple terminal states. To the best of our knowledge, \cite{dac} is the only work which explicitly addresses reward bias and proposes a way to solve it. \section{Background} \subsection{Generative Adversarial Imitation Learning} We make use of the GAIL\cite{gail} framework to learn the expert policy. In GAIL framework, to learn a robust reward function, a discriminator(D) is trained which acts like a binary classifier to differentiate between transitions from the expert and from the trained policy. The policy is trained using an on-policy RL algorithm, and it is rewarded for confusing the discriminator. \[ \max_\pi \min_{D} \Big[ E_{a\sim \pi(s)} [\log(D(s,a))] + E_{a \sim \pi_E(s)} [\log(1 - D(s,a))] + \lambda H(\pi) \Big] \tag{1} \label{eq:gail}\] where $\pi$ is the imitation learning policy, $H(\pi)$ is the entropy of the policy, $\pi_E$ is the expert policy and D(s, a) is the probability that the state-action pair is from the expert trajectory. GAIL does not aim to recover the true reward function, but rather tries to match the state occupancy measure of the expert and the agent. However, this does not guarantee that the expert trajectories are optimal with respect of the reward function output by the discriminator as we show in the later sections. \subsection{Survival Based and Task Based Environments} In survival based tasks, the agent gets a reward for staying in a set of "good states" and the episode terminates when the agent goes to a "bad state". Within the good states, different rewards may be provided to encourage the agent to stay within certain good states more than others. Some examples of these kinds of environments are the Mujoco environments like Hopper, Reacher etc. In task-based environments, the agent gets a reward for successfully completing a task, characterised by agent reaching a certain state in the environment. Additional rewards may be given for completing `subtasks' along the way. The agent may also be penalized for simply existing in the environment. This makes the agent complete the task as soon as possible to get maximum positive rewards from task completion and minimum survival penalty. Additional complexities might arise, if additionally the environment also has some other terminal states, which don't lead to completion of the task but lead to the termination of the episode or the agent essentially dying. In our work, we use 3 environments of this kind and show how existing approaches\cite{dac} \cite{gail} don't work on these environments and how our method tackles the biases. \subsection{Reward bias in GAIL} To train the imitation policy in the GAIL method, two kinds of discriminator reward are commonly used in literature \cite{gail} \cite{goalgail}: \begin{enumerate} \item \textbf{Positive Reward}: This reward is always positive and its value is $-\log(1 - D(s, a))$ \item \textbf{Negative Reward}: This reward is always negative and its value is $\log(D(s, a))$ \end{enumerate} However, both the reward functions have implicit biases which may hinder learning. They are explained in the following subsections. \begin{figure} \centering \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-Empty-Random-6x6-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-DoorKey-6x6-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-DistShift1-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-GoToDoor-6x6-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-RedBlueDoors-6x6-v0.png} \caption{Episode rewards for different environments and different GAIL reward functions. The positive rewards show a survival bias because they do not complete the task (leading to low reward). The negative rewards show a termination bias, and in the simpler environments, the agent learns to complete the task even without trajectories ($D=0.5$) only due to the reward bias.} \label{fig:notrajrewards} \end{figure} \subsubsection{Survival bias in positive rewards} In a task-based environment, providing non-negative rewards at every step may lead to survival bias and the agent may not complete the task and loop in the environment to collect more rewards. To show that survival bias is indeed an issue, we consider an ideal case. We consider an ``oracle discriminator'', which gives a positive reward $R$ when the agent performs the expert action for a given state, and 0 otherwise. In other words, the reward function of the discriminator is $R(s,a) = R$ if $a = \pi_E(s)$ and $R(s,a) = 0$ if $a \ne \pi_E(s)$. In practice, the discriminator reward is also bounded to prevent stability issues by using $R(s,a) = -\log(\max(\epsilon, 1 - D(s,a)))$ which has range $\Big[0, \log(\frac{1}{\epsilon})\Big]$. Now consider an expert trajectory of path length $p$. Since the discriminator will give a positive reward $R$ at each step in the expert trajectory, the total discounted reward of the expert trajectory is: \begin{align} R_E &= R + \gamma R + \ldots \gamma^{(p-1)} R = \frac{1 - \gamma^p}{1 - \gamma}R \end{align} Now consider a trajectory where the agent follows the expert trajectory for $p-1$ steps, and then loops between an expert action and non-expert action to survive for as long as possible. The total discounted reward for this trajectory is: \begin{align} R_{loop} &= R + \gamma R + \ldots \gamma^{(p-2)} R + 0 + \gamma^{(p)} R + 0 + \gamma^{(p+2)} R \ldots \\ &= \frac{1 - \gamma^{(p-1)}}{1-\gamma} R + \frac{\gamma^p}{1 - \gamma^2}R \end{align} For the agent to prefer this trajectory over the expert trajectory, $R_{loop}$ should be greater than $R_E$. This inequality will imply the following: \begin{align} \frac{1 - \gamma^{(p-1)}}{1-\gamma} R + \frac{\gamma^p}{1 - \gamma^2}R &\ge \frac{1 - \gamma^p}{1 - \gamma}R \\ \implies \frac{\gamma^p}{1 + \gamma} &\ge \gamma^{(p-1)} (1 - \gamma) \implies \gamma \ge 1 - \gamma^2 \end{align} which is true for $\gamma \ge 0.6180$. In practical scenarios, $\gamma \approx 1$, and hence, the agent can prefer to loop in the environment rather than following the expert trajectories. It is therefore evident as to why positive rewards might be unsuitable for task based environments. \subsubsection{Termination bias in Negative Rewards} Positive reward functions are prone to survival bias, and the next obvious choice of a reward function is $R(s,a) = \log(D(s,a))$. This reward function is always negative since $D(s,a) \in [0, 1]$. However, this reward function makes an agent prone to termination bias. In termination bias, the agent tends to end the episode as soon as possible to stop accruing more negative rewards. This may be beneficial for task based environments where the agent wants to complete the task as soon as possible. However, if there are faster ways to terminate an episode, the agent may be biased to do that instead of completing the task. In our experiments, we show that GAIL with the reward function $R(s,a) = \log(D(s,a))$ fails to learn the task when there are multiple termination conditions in the environment. \subsection{Discriminator Actor Critic} Both the survival and task based environments suffer from different problems but for the same reason - the reward for the terminal state is implicitly set to 0 in all these problems, which is why positive rewards become unsuitable for task based environments and negative rewards become unsuitable for survival based environments. To address the issue of implicit bias in the reward function of the GAIL, \cite{dac} propose learning rewards for absorbing state explicitly. Consider a trajectory of T time steps, let the reward for the terminal state i.e the Tth step be $R_T = R(s_T, a_T)$, in the standard GAIL setting as in Equation \ref{eq:gail}. In DAC, a new reward function for terminal state is defined $R_T = R(s_T, a_T) + \Sigma_{T + 1} ^ \infty \gamma ^{t - T}R(s_a, .)$ where $R(s_a, .)$ is learnt. This learnt reward for the terminal state removes the bias towards avoiding or transitioning to the terminal state. With this formulation, GAIL tries to match the state occupancy of the expert and agent for the terminal state as well, hence mitigating survivor bias. However, this modifies a finite-horizon environment into an infinite-horizon environment, and does not consider the scenario where the agent may terminate an episode in a multitude of different ways. There are a few other problems as well that the work does not address: \begin{enumerate} \item \textbf{Requires modifying the environment}: In the original implementation of DAC, wrappers are provided to augment the environment with an extra terminal state. However, this may not always be feasible as we may only have an immutable API to the environment. This may also be a problem in real environments. \item \textbf{Does not handle multiple terminal states}: In a task-based environment with multiple terminal states, the agent can terminate an episode in multiple ways, out of which only some may correspond to task completion, and this can hinder learning. If a large portion of the expected reward comes from being in the terminal state, then the agent may not distinguish between expert trajectories and other similar trajectories which terminate the episode, as long as the state occupancy of the terminal states match for the agent and the expert. \item \textbf{May be sample inefficient}: In the original DAC paper, the method is off-policy but it is compared with other on-policy algorithms, which is unfair. We suspected that DAC may be sample inefficient as compared to GAIL because DAC also has to match the state occupancy of the terminal state in addition to the existing states in the environment. For our experiments, we implement an on-policy version of DAC and observe that the method indeed is less sample efficient than GAIL. \end{enumerate} \subsection{Towards an unbiased reward function} \iffalse Positive rewards lead to `survival bias` in the environment, and the agent can never learn the task. Negative rewards, i.e $log(D)$ lead to `termination bias` in the environment, which may lead to suboptimal behavior when other termination conditions are provided. \fi We introduce the notation of "neutral reward functions" to denote reward functions that are real valued. For example, the reward function $R(D) = \log(D) - \log(1-D)$ has the range $(-\infty, \infty)$ for $D \in (0, 1)$ and is real-valued. Neutral reward functions can be unbiased because they can penalize looping behavior with negative rewards, effectively ``cancelling'' the positive reward that they acquired from previous loops (assuming that the expert doesn't loop itself). The reward function can also potentially overcome `termination bias' because the agent can collect as many positive rewards as possible by following the expert trajectories. To give an intuition of these claims, we show a similar theoretical sketch as before. Consider an oracle discriminator that gives reward $R$ when the agent takes the expert action $a$ to a state $s$, and gives a negative reward $-R$ otherwise (since the neutral reward function is a symmetric function $R(s, a) = \log(D(s,a)) -\log(1 - D(s,a))$ ). To ensure the agent learns to perform the task, the discriminator should assign the highest rewards to the expert trajectories. Consider an expert trajectory of length $p$. Similar to the previous example, assume that each state has only one expert action. The reward of the expert trajectory is: \begin{align} R_E = R + \gamma R + \ldots \gamma^{(p-1)}R = \frac{1 - \gamma^p}{1 - \gamma} R \label{eq:re_neutral} \end{align} The maximum reward for any other trajectory can be obtained by mimicking the expert till timestep $p-1$ to get positive rewards and do a non-expert action (to prevent the trajectory from becoming an expert trajectory). To recover from the negative reward just incurred, the agent performs an expert action. After this, it cannot perform an expert action again because that will complete the expert trajectory and the episode will terminate. So, if it wants to loop it will perform a non-expert action followed by an expert action and continue doing so. Hence the reward for this trajectory $loop$ is: \begin{align} R_{loop} &= R + \gamma R + \ldots \gamma^{(p-2)}R - \gamma^{(p-1)} R + \gamma^{p}R - \gamma^{p+1}R \ldots \\ &= \frac{1 - \gamma^{(p-1)}}{1 - \gamma}R - \frac{\gamma^{(p-1)}}{1 + \gamma}R \end{align} For an agent to prefer surviving rather than completing the expert trajectory, we need to have $R_{loop} \ge R_E$. This implies: \begin{align} \frac{1 - \gamma^{(p-1)}}{1 - \gamma}R - \frac{\gamma^{(p-1)}}{1 + \gamma}R &\ge \frac{1 - \gamma^p}{1 - \gamma} R \\ \implies \frac{\gamma^{(p-1)} - \gamma^p}{1 - \gamma} \le - \frac{\gamma^{(p-1)}}{1 + \gamma} \implies 1 \le \frac{-1}{1 + \gamma} \end{align} Which is impossible for a discounting factor $\gamma \in [0, 1]$. Hence, $R_{loop}$ will always be lesser than $R_E$ for an oracle discriminator, and the agent will always prefer following the expert trajectory. A similar argument can be made for neutral rewards overcoming termination bias. Consider the previous setup, but the agent tries to terminate the episode before completing the task. The expert reward is already in Equation \ref{eq:re_neutral}. To exhibit termination bias, the agent has to terminate the episode in at most $p$ steps, and the last action should be a non-expert action (if its an expert action, then the agent is exactly imitating the expert). Hence, the maximum reward the agent can accrue is : \begin{align} R_{term} = R + \gamma R + \ldots \gamma^{(p-2)}R - \gamma^{(p-1)}R \end{align} which is the same as $R_E$ for the first $p-1$ terms but the last term is a negative term whereas the last term of $R_E$ is a positive term. Since $R_E \ge R_{term}$, the agent will prefer the expert trajectory over some other shorter non-expert path. Hence, the neutral reward overcomes termination bias. \iffalse \subsection{Challenges for AIL in Survival based and Task based environments} In survival based tasks, note that the expected reward has to be positive for the agent to survive -- if the agent gets a negative expected reward, then the agent can simply die and terminate the episode to receive no further rewards. Therefore, choosing a positive reward function from the adversary makes sense in tasks where survival is the goal and that is the reason why MuJoCo environments converge to near-optimal expert policies with the reward function $R(s, a) = -\log(D(s, a))$. In task-based environments, a positive reward function would not work very well due to survival bias. In case of a positive reward, the agent can simply loop back and forth between state-action pairs and collect more rewards than it can by actually completing the task. As the discriminator penalizes those state-action pairs, the agent will find other state-action pairs to maximize its reward. In our experiments, we show that in every task-based environment, positive reward functions always lead to a loopy behavior and the agent never actually completes the task. \fi \subsection{Choice of Environment} \begin{wrapfigure}{l}{0.4\textwidth}\centering \includegraphics[width=0.19\textwidth]{envs/MiniGrid-Empty-Random-6x6-v0.png} \includegraphics[width=0.19\textwidth]{envs/MiniGrid-DoorKey-6x6-v0.png} \includegraphics[width=0.19\textwidth]{envs/MiniGrid-DistShift1-v0.png} \includegraphics[width=0.19\textwidth]{envs/MiniGrid-GoToDoor-6x6-v0.png} \includegraphics[width=0.39\textwidth]{envs/MiniGrid-RedBlueDoors-6x6-v0.png} \caption{Environments used in the paper. The top-left and top-middle environments terminate only on reaching the goal (green). The other environments can terminate through other conditions as well (mentioned in the paper). However, expert trajectories consist of goal-directed behaviors only.} \label{fig:envs} \vspace*{-38pt} \end{wrapfigure} To observe the limitations of the current methods used in adversarial imitation learning, we propose to use task based environments. However, task based environments with single terminal states will not be able to test the bias of the reward functions due to termination conditions. Hence, we propose to use environments from the Gym Minigrid package \cite{minigrid} with single and multiple termination conditions. We disable the \textit{Done} action to examine the bias of the agent only due to environmental termination conditions. To verify the effects of reward bias in a single termination condition, we choose the \textit{Empty} and \textit{DoorKey} environments. \begin{enumerate} \item In the \textit{Empty} environment, the agent starts at a random location in the grid and the episode terminates when the agent steps on the goal location (in green). \item In the \textit{DoorKey} environment, the agent starts in a room and has to pick up a key to open a locked door. The agent has to reach the goal on the other side of the locked door. \end{enumerate} Both these environments have only one termination condition - the agent has to reach the goal location. Methods like Discriminator-Actor-Critic \cite{dac} can learn a non-zero reward for the terminal condition which overcomes the survival bias of the positive reward function. GAIL with a negative reward can also learn to solve these tasks since they want to accumulate the maximum reward which would require termination of the episode as soon as possible. However, both of these methods can suffer from the same problem - multiple termination conditions. The negative reward will have a bias towards trajectories that terminate early to accumulate fewer negative rewards. The DAC baseline will not differentiate between different termination conditions (termination due to goal completion v/s termination due to other conditions) since the terminal state can potentially provide a large cumulative reward. To test this, we use three other environments within Gym Minigrid. They are: \begin{enumerate} \item \textit{RedBlueDoors}: In this environment, the task is to open a red door, followed by opening the blue door. The episode terminates when the blue door is opened regardless of whether the red door was opened or not. \item \textit{GoToDoor}: This environment is similar to the \textit{RedBlueDoors} environment but there are 4 doors of different colors, and the episode terminates when any door is opened. However, the task is considered to be completed only if the red door is opened. \item \textit{DistShiftv0}: In this environment, the agent has to cross a room with lava near the walls of the room (refer to Figure \ref{fig:envs}. The task is to reach the goal location and avoid the lava. The episode ends when the agent touches the lava or goal. \end{enumerate} These environments have termination conditions which will affect the variants of GAIL depending on the reward bias that they may have. We hypothesize that the inability of DAC to differentiate between terminal states would lead to suboptimal performance in each of these environments. \begin{figure} \centering \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-Empty-Random-6x6-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-DoorKey-6x6-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-DistShift1-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-GoToDoor-6x6-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-RedBlueDoors-6x6-v0.png} \caption{Comparison of performance of different GAIL variants. On-policy DAC is slow in terms of converging to the optimal policy, possibly due to unstable learning of the terminal state reward. In environments with non-goal terminal states, DAC and GAIL with negative rewards converge to suboptimal policies due to their respective biases.} \label{fig:rewards} \end{figure} \section{Experiments} \vspace{-5pt} Our expert is a trained PPO policy. We use 1000 rollouts from the expert policy to train our imitation learning agents for all our experiments. Each rollout has $\sim$10 state-action pairs, so the total number of state action pairs are comparable to \cite{babyai} and \cite{gail}. The locations and colors of the objects are also perturbed across episodes, so the agent has to generalize to the concept of objects rather than memorizing the goal locations. We use 3 CNN layers with Leaky ReLU activations to extract a state embedding of the environment as shown in Figure \ref{fig:arch} for all our experiments. We use PPO \cite{ppo} for on-policy optimisation of the GAIL reward function for all experiments. In each case, the policy network uses this state and returns probability of an action given a state. The policy network head is a 2-layered MLP with Leaky ReLU activations. The value network head is identical to the policy network as shown in Figure \ref{fig:arch}. We average all our results across 3 random seeds. The objective of our first experiment is to exhibit the implicit bias in the positive and negative reward functions. We compare the environment rewards achieved by the agents and the success rate for the 5 environments that we had mentioned earlier. For our second experiment, we compare the environment rewards and success rate of (i) DAC \cite{dac} (ii) Positive Reward (iii) Negative Reward (iv) Neutral Rewards in the five environments. \iffalse \begin{enumerate} \item \textbf{Positive Reward}: Uses $-log(1 - D)$ as the reward. In this we evaluate two scenarios one where D is being learnt and the other where D is set as a constant equal to 0.5. \item \textbf{Negative Reward}: Uses $log(D)$ as the reward. In this we evaluate two scenarios one where D is being learnt and the other where D is set as a constant equal to 0.5. \item \textbf{Neutral Reward}: Uses $log(D) - log(1 - D)$ as the reward. \item \textbf{DAC}: Learn reward for the absorbing state as proposed by Kostrikov et al\cite{dac}. \end{enumerate} \fi \section{Results} \vspace{-5pt} Figure \ref{fig:notrajrewards} shows reward curves for positive and negative rewards with and without learning the discriminator. The first two environments, \textit{Empty} and \textit{Doorkey} are able to attain expert like performance with negative rewards, which was expected as these are task based environments with single termination state. GAIL with positive reward is not able to learn the expert policy due to its survival bias (first two plots of the Figure \ref{fig:notrajrewards}). In case of \textit{Empty}, the agent is able to learn the task even without training the discriminator which shows that the negative reward function has a termination bias strong enough for task based environments. Similarly, for the \textit{DoorKey} environment, GAIL with negative reward starts to learn the task better than positive rewards even when the discriminator is not trained. However, in last three plots of Figure \ref{fig:notrajrewards}, where environments with multiple terminal states are used, termination bias is not enough to learn the task. Positive rewards fall into the survival bias and don't learn the task. An interesting observation is that the success rate of \textit{GoToDoor} with negative reward and no trajectories is 0.25 as shown in Figure \ref{fig:notrajrewards}. The termination bias makes the agent reach out to the nearest door to end the episode, which has a 25\% rate of being the red door. \begin{table}[htpb] \centering \begin{adjustwidth}{-1cm}{} \resizebox{1.1\textwidth}{!}{ \centering \begin{tabular}{|l|c|c|c|c|c|} \hline & \textbf{Empty} & \textbf{DoorKey} & \textbf{GoToDoor} & \textbf{RedBlueDoors} & \textbf{Distshift1} \\ \hline $R = -\log(1-D)$ & $0.03 \pm 0.15$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ \\ \hline $R = -\log(0.5)$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$\\ \hline $R = \log(D)$ & $\boldsymbol{1.00 \pm 0.00}$ & $\boldsymbol{1.00\pm 0.00}$ & $0.93 \pm 0.24$ & $0.83 \pm 0.37$ & $0.85 \pm 0.35$\\ \hline $R = \log(0.5)$ & $\boldsymbol{1.00 \pm 0.00}$ & 0.25 $\pm$ 0.43 & 0.38 $\pm$ 0.48 & 0.00 $\pm$ 0.00 & 0.65 $\pm$ 0.47\\ \hline DAC & $\boldsymbol{1.00 \pm 0.00}$ & 0.83 $\pm$ 0.37 & 0.26 $\pm$ 0.44 & 0.70 $\pm$ 0.45 & 0.76 $\pm$ 0.42 \\ \hline $R = \log(D) - \log(1-D)$ & {$\boldsymbol{1.00 \pm 0.00}$} & {$\boldsymbol{1.00 \pm 0.00}$} & {$\boldsymbol{0.97 \pm 0.15}$} & {$\boldsymbol{0.91 \pm 0.27}$} & {$\boldsymbol{0.97 \pm 0.15}$} \\ \hline \end{tabular} } \caption{Success rate of all learnt policies across 3 seeds. For each seed, 20 trajectories were recorded and the mean and variance is calculated across all trajectories.} \label{tab:perf} \end{adjustwidth} \end{table} In Figure \ref{fig:rewards}, we compare the performance of DAC, neutral rewards, negative and positive rewards. The success rate of the different methods is also summarized in Table \ref{tab:perf}. For \textit{Empty} and \textit{DoorKey} all methods except GAIL with positive rewards are able to learn the task. However, DAC is slower than other GAIL methods, and we hypothesize this is because DAC has to learn the reward for the terminal state as well. For the other three environments, termination bias hinders learning with negative rewards and DAC suffers in performance due to lack of distinction between terminal states. For \textit{GoToDoor}, \textit{DistShift} and \textit{RedBlueDoors}, DAC is not able to achieve high success rate showing its limitations in task based scenarios with multiple terminal states. Success rate of neutral reward is the highest and better than the negative reward showing its robustness to termination bias. Similarly, for other the other two task based environments with multiple terminal states, neutral reward significantly outperforms both DAC and negative reward. GAIL with neutral rewards is able to outperform all other methods, hence, is able to overcome both survival and termination bias. \section{Conclusion} \vspace{-5pt} In this work, we address the problem of reward bias in adversarial imitation learning. We explore two types of reward biases - survival bias and termination bias, and how different reward functions lead to these biases in the agent. Positive reward functions encourage survival bias, and negative reward functions encourage termination bias, and both these biases may hinder learning in a task-based environment. We show that real-valued reward functions are unbiased and can learn to overcome both survival and termination biases. Experiments show that this simple change of reward function enables the agent to imitate the expert on tasks with single and multiple termination conditions. \iffalse From our experiments, we are able to show that positive reward is not able to work well in task based environments. Negative rewards are able to learn the expert policy in task based environments with single terminal state, however, they are unable to attain expert performance in task based environments with multiple terminal state. DAC is slow to converge is not able to learn the expert policy in task based environments with multiple terminal states. Our proposed method using neutral rewards achieves expert performance in task based environments with single termination state as well multiple termination states. \fi \clearpage \section{Introduction} Adversarial Imitation Learning(AIL) algorithms \cite{gail} \cite{airl} \cite{dac} \cite{kuefler2017imitating} have been shown to achieve state of the art performance on a variety of imitation learning tasks. Performance of AIL algorithms have been primarily evaluated in two kinds of broad settings. The first kind of setting can be characterised as survival based environments. For example, environments in Mujoco like Hopper, Cheetah where the agent is rewarded to survive in the environment by remaining in a set of good states and penalized (by negative rewards or by termination) if it attains states other than these good states. For example, in Hopper the agent gets good rewards for hopping forward as fast as possible. If the agent gets into a set of `bad poses' the episode is terminated. The other setting can be characterised as ``task'' based environments where the agent is rewarded to complete a task (reaching a goal state, interacting with an object in the environment, dodging an obstacle) and so on. The episode terminates once the agent completes the task. However, there is another important setting which hasn't drawn much attention in the Imitation Learning community. The episode may also terminate when the agent has failed to perform the task in a task based scenario. For example, when the agent may alter the environment such that completing the task becomes impossible, such as breaking a glass that the agent was supposed to pick up. These are environments where the agent is rewarded to complete a task, i.e to reach a certain state in the shortest amount of time after which the episode is terminated, however, there are some additional bad terminal states, upon reaching which the episode terminates and the agent doesn't receive a reward. Most of the community has worked on environments which are either purely survival based or purely task based. However, to show that current reward functions are biased, we need to use more complex environments. To that end, we use different environments of the Gym-Minigrid\cite{minigrid} package. This package contains environments with single and multiple terminal states, which would be ideal to test if learning is hindered by the inherent biases in the reward function itself. Our experiments show that existing methods\cite{gail}\cite{dac} often get stuck in a suboptimal policy in task based environments with multiple terminal states. We provide a rough theoretical sketch of the underlying issues in these methods. We also propose a reward function which is able to achieve comparable results in task based environments with single terminal state and performs significantly better than existing methods in task based environments with multiple terminal states. \section{Related Work} Early works in Imitation Learning based on Inverse Reinforcement Learning \cite{irl} focus on recovering a reward function from expert demonstrations which is optimised using Reinforcement Learning. These methods are slow since they require solving the RL objective in the inner loop. From a practical standpoint, the intermediate step of recovering reward function is not really necessary when the goal is to only learn to imitate the expert. Recent works in Adversarial Imitation Learning \cite{gail} \cite{airl} \cite{infogail} \cite{bayesiangail} \cite{goalgail} focus on directly recovering the expert policy without the need for recovering the exact reward function. These methods alleviate the problem of distributional shift faced by some of the more traditional approaches like Behavior Cloning and its variants \cite{bco} \cite{dagger} \cite{rossbagnell} \cite{daume}. GAIL based methods are also very sample efficient than behavior cloning in terms of number of expert trajectories required to recover the expert policy. Although AIL methods have had a fair amount of success in various environments, recent work \cite{dac} has highlighted the implicit bias in the formulation of its reward function which results in degradation of performance in certain environments. The work in Discriminator-Actor-Critic \cite{dac} show how the reward function used in GAIL for training the agent is biased which leads to degradation of performance in certain environments. In GAIL, the agent focuses on how to maximize its rewards from the discriminator, which may not necessarily translate to following the expert policy. In task-based environments, the problem of implicit bias due to zero rewards for terminal states encourages the agent to stay in the environment to collect more positive rewards, hence ignoring the task. Their method worked on the survival based agents, as well as on task-based robotic environments. However, there are no results on the method's performance in task based environments with multiple terminal states. Our experiments show their formulation doesn't work well in such task based environments with multiple terminal states. To the best of our knowledge, \cite{dac} is the only work which explicitly addresses reward bias and proposes a way to solve it. \section{Background} \subsection{Generative Adversarial Imitation Learning} We make use of the GAIL\cite{gail} framework to learn the expert policy. In GAIL framework, to learn a robust reward function, a discriminator(D) is trained which acts like a binary classifier to differentiate between transitions from the expert and from the trained policy. The policy is trained using an on-policy RL algorithm, and it is rewarded for confusing the discriminator. \[ \max_\pi \min_{D} \Big[ E_{a\sim \pi(s)} [\log(D(s,a))] + E_{a \sim \pi_E(s)} [\log(1 - D(s,a))] + \lambda H(\pi) \Big] \tag{1} \label{eq:gail}\] where $\pi$ is the imitation learning policy, $H(\pi)$ is the entropy of the policy, $\pi_E$ is the expert policy and D(s, a) is the probability that the state-action pair is from the expert trajectory. GAIL does not aim to recover the true reward function, but rather tries to match the state occupancy measure of the expert and the agent. However, this does not guarantee that the expert trajectories are optimal with respect of the reward function output by the discriminator as we show in the later sections. \subsection{Survival Based and Task Based Environments} In survival based tasks, the agent gets a reward for staying in a set of "good states" and the episode terminates when the agent goes to a "bad state". Within the good states, different rewards may be provided to encourage the agent to stay within certain good states more than others. Some examples of these kinds of environments are the Mujoco environments like Hopper, Reacher etc. In task-based environments, the agent gets a reward for successfully completing a task, characterised by agent reaching a certain state in the environment. Additional rewards may be given for completing `subtasks' along the way. The agent may also be penalized for simply existing in the environment. This makes the agent complete the task as soon as possible to get maximum positive rewards from task completion and minimum survival penalty. Additional complexities might arise, if additionally the environment also has some other terminal states, which don't lead to completion of the task but lead to the termination of the episode or the agent essentially dying. In our work, we use 3 environments of this kind and show how existing approaches\cite{dac} \cite{gail} don't work on these environments and how our method tackles the biases. \subsection{Reward bias in GAIL} To train the imitation policy in the GAIL method, two kinds of discriminator reward are commonly used in literature \cite{gail} \cite{goalgail}: \begin{enumerate} \item \textbf{Positive Reward}: This reward is always positive and its value is $-\log(1 - D(s, a))$ \item \textbf{Negative Reward}: This reward is always negative and its value is $\log(D(s, a))$ \end{enumerate} However, both the reward functions have implicit biases which may hinder learning. They are explained in the following subsections. \begin{figure} \centering \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-Empty-Random-6x6-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-DoorKey-6x6-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-DistShift1-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-GoToDoor-6x6-v0.png} \includegraphics[width=0.32\textwidth]{notrajrewards/MiniGrid-RedBlueDoors-6x6-v0.png} \caption{Episode rewards for different environments and different GAIL reward functions. The positive rewards show a survival bias because they do not complete the task (leading to low reward). The negative rewards show a termination bias, and in the simpler environments, the agent learns to complete the task even without trajectories ($D=0.5$) only due to the reward bias.} \label{fig:notrajrewards} \end{figure} \subsubsection{Survival bias in positive rewards} In a task-based environment, providing non-negative rewards at every step may lead to survival bias and the agent may not complete the task and loop in the environment to collect more rewards. To show that survival bias is indeed an issue, we consider an ideal case. We consider an ``oracle discriminator'', which gives a positive reward $R$ when the agent performs the expert action for a given state, and 0 otherwise. In other words, the reward function of the discriminator is $R(s,a) = R$ if $a = \pi_E(s)$ and $R(s,a) = 0$ if $a \ne \pi_E(s)$. In practice, the discriminator reward is also bounded to prevent stability issues by using $R(s,a) = -\log(\max(\epsilon, 1 - D(s,a)))$ which has range $\Big[0, \log(\frac{1}{\epsilon})\Big]$. Now consider an expert trajectory of path length $p$. Since the discriminator will give a positive reward $R$ at each step in the expert trajectory, the total discounted reward of the expert trajectory is: \begin{align} R_E &= R + \gamma R + \ldots \gamma^{(p-1)} R = \frac{1 - \gamma^p}{1 - \gamma}R \end{align} Now consider a trajectory where the agent follows the expert trajectory for $p-1$ steps, and then loops between an expert action and non-expert action to survive for as long as possible. The total discounted reward for this trajectory is: \begin{align} R_{loop} &= R + \gamma R + \ldots \gamma^{(p-2)} R + 0 + \gamma^{(p)} R + 0 + \gamma^{(p+2)} R \ldots \\ &= \frac{1 - \gamma^{(p-1)}}{1-\gamma} R + \frac{\gamma^p}{1 - \gamma^2}R \end{align} For the agent to prefer this trajectory over the expert trajectory, $R_{loop}$ should be greater than $R_E$. This inequality will imply the following: \begin{align} \frac{1 - \gamma^{(p-1)}}{1-\gamma} R + \frac{\gamma^p}{1 - \gamma^2}R &\ge \frac{1 - \gamma^p}{1 - \gamma}R \\ \implies \frac{\gamma^p}{1 + \gamma} &\ge \gamma^{(p-1)} (1 - \gamma) \implies \gamma \ge 1 - \gamma^2 \end{align} which is true for $\gamma \ge 0.6180$. In practical scenarios, $\gamma \approx 1$, and hence, the agent can prefer to loop in the environment rather than following the expert trajectories. It is therefore evident as to why positive rewards might be unsuitable for task based environments. \subsubsection{Termination bias in Negative Rewards} Positive reward functions are prone to survival bias, and the next obvious choice of a reward function is $R(s,a) = \log(D(s,a))$. This reward function is always negative since $D(s,a) \in [0, 1]$. However, this reward function makes an agent prone to termination bias. In termination bias, the agent tends to end the episode as soon as possible to stop accruing more negative rewards. This may be beneficial for task based environments where the agent wants to complete the task as soon as possible. However, if there are faster ways to terminate an episode, the agent may be biased to do that instead of completing the task. In our experiments, we show that GAIL with the reward function $R(s,a) = \log(D(s,a))$ fails to learn the task when there are multiple termination conditions in the environment. \subsection{Discriminator Actor Critic} Both the survival and task based environments suffer from different problems but for the same reason - the reward for the terminal state is implicitly set to 0 in all these problems, which is why positive rewards become unsuitable for task based environments and negative rewards become unsuitable for survival based environments. To address the issue of implicit bias in the reward function of the GAIL, \cite{dac} propose learning rewards for absorbing state explicitly. Consider a trajectory of T time steps, let the reward for the terminal state i.e the Tth step be $R_T = R(s_T, a_T)$, in the standard GAIL setting as in Equation \ref{eq:gail}. In DAC, a new reward function for terminal state is defined $R_T = R(s_T, a_T) + \Sigma_{T + 1} ^ \infty \gamma ^{t - T}R(s_a, .)$ where $R(s_a, .)$ is learnt. This learnt reward for the terminal state removes the bias towards avoiding or transitioning to the terminal state. With this formulation, GAIL tries to match the state occupancy of the expert and agent for the terminal state as well, hence mitigating survivor bias. However, this modifies a finite-horizon environment into an infinite-horizon environment, and does not consider the scenario where the agent may terminate an episode in a multitude of different ways. There are a few other problems as well that the work does not address: \begin{enumerate} \item \textbf{Requires modifying the environment}: In the original implementation of DAC, wrappers are provided to augment the environment with an extra terminal state. However, this may not always be feasible as we may only have an immutable API to the environment. This may also be a problem in real environments. \item \textbf{Does not handle multiple terminal states}: In a task-based environment with multiple terminal states, the agent can terminate an episode in multiple ways, out of which only some may correspond to task completion, and this can hinder learning. If a large portion of the expected reward comes from being in the terminal state, then the agent may not distinguish between expert trajectories and other similar trajectories which terminate the episode, as long as the state occupancy of the terminal states match for the agent and the expert. \item \textbf{May be sample inefficient}: In the original DAC paper, the method is off-policy but it is compared with other on-policy algorithms, which is unfair. We suspected that DAC may be sample inefficient as compared to GAIL because DAC also has to match the state occupancy of the terminal state in addition to the existing states in the environment. For our experiments, we implement an on-policy version of DAC and observe that the method indeed is less sample efficient than GAIL. \end{enumerate} \subsection{Towards an unbiased reward function} \iffalse Positive rewards lead to `survival bias` in the environment, and the agent can never learn the task. Negative rewards, i.e $log(D)$ lead to `termination bias` in the environment, which may lead to suboptimal behavior when other termination conditions are provided. \fi We introduce the notation of "neutral reward functions" to denote reward functions that are real valued. For example, the reward function $R(D) = \log(D) - \log(1-D)$ has the range $(-\infty, \infty)$ for $D \in (0, 1)$ and is real-valued. Neutral reward functions can be unbiased because they can penalize looping behavior with negative rewards, effectively ``cancelling'' the positive reward that they acquired from previous loops (assuming that the expert doesn't loop itself). The reward function can also potentially overcome `termination bias' because the agent can collect as many positive rewards as possible by following the expert trajectories. To give an intuition of these claims, we show a similar theoretical sketch as before. Consider an oracle discriminator that gives reward $R$ when the agent takes the expert action $a$ to a state $s$, and gives a negative reward $-R$ otherwise (since the neutral reward function is a symmetric function $R(s, a) = \log(D(s,a)) -\log(1 - D(s,a))$ ). To ensure the agent learns to perform the task, the discriminator should assign the highest rewards to the expert trajectories. Consider an expert trajectory of length $p$. Similar to the previous example, assume that each state has only one expert action. The reward of the expert trajectory is: \begin{align} R_E = R + \gamma R + \ldots \gamma^{(p-1)}R = \frac{1 - \gamma^p}{1 - \gamma} R \label{eq:re_neutral} \end{align} The maximum reward for any other trajectory can be obtained by mimicking the expert till timestep $p-1$ to get positive rewards and do a non-expert action (to prevent the trajectory from becoming an expert trajectory). To recover from the negative reward just incurred, the agent performs an expert action. After this, it cannot perform an expert action again because that will complete the expert trajectory and the episode will terminate. So, if it wants to loop it will perform a non-expert action followed by an expert action and continue doing so. Hence the reward for this trajectory $loop$ is: \begin{align} R_{loop} &= R + \gamma R + \ldots \gamma^{(p-2)}R - \gamma^{(p-1)} R + \gamma^{p}R - \gamma^{p+1}R \ldots \\ &= \frac{1 - \gamma^{(p-1)}}{1 - \gamma}R - \frac{\gamma^{(p-1)}}{1 + \gamma}R \end{align} For an agent to prefer surviving rather than completing the expert trajectory, we need to have $R_{loop} \ge R_E$. This implies: \begin{align} \frac{1 - \gamma^{(p-1)}}{1 - \gamma}R - \frac{\gamma^{(p-1)}}{1 + \gamma}R &\ge \frac{1 - \gamma^p}{1 - \gamma} R \\ \implies \frac{\gamma^{(p-1)} - \gamma^p}{1 - \gamma} \le - \frac{\gamma^{(p-1)}}{1 + \gamma} \implies 1 \le \frac{-1}{1 + \gamma} \end{align} Which is impossible for a discounting factor $\gamma \in [0, 1]$. Hence, $R_{loop}$ will always be lesser than $R_E$ for an oracle discriminator, and the agent will always prefer following the expert trajectory. A similar argument can be made for neutral rewards overcoming termination bias. Consider the previous setup, but the agent tries to terminate the episode before completing the task. The expert reward is already in Equation \ref{eq:re_neutral}. To exhibit termination bias, the agent has to terminate the episode in at most $p$ steps, and the last action should be a non-expert action (if its an expert action, then the agent is exactly imitating the expert). Hence, the maximum reward the agent can accrue is : \begin{align} R_{term} = R + \gamma R + \ldots \gamma^{(p-2)}R - \gamma^{(p-1)}R \end{align} which is the same as $R_E$ for the first $p-1$ terms but the last term is a negative term whereas the last term of $R_E$ is a positive term. Since $R_E \ge R_{term}$, the agent will prefer the expert trajectory over some other shorter non-expert path. Hence, the neutral reward overcomes termination bias. \iffalse \subsection{Challenges for AIL in Survival based and Task based environments} In survival based tasks, note that the expected reward has to be positive for the agent to survive -- if the agent gets a negative expected reward, then the agent can simply die and terminate the episode to receive no further rewards. Therefore, choosing a positive reward function from the adversary makes sense in tasks where survival is the goal and that is the reason why MuJoCo environments converge to near-optimal expert policies with the reward function $R(s, a) = -\log(D(s, a))$. In task-based environments, a positive reward function would not work very well due to survival bias. In case of a positive reward, the agent can simply loop back and forth between state-action pairs and collect more rewards than it can by actually completing the task. As the discriminator penalizes those state-action pairs, the agent will find other state-action pairs to maximize its reward. In our experiments, we show that in every task-based environment, positive reward functions always lead to a loopy behavior and the agent never actually completes the task. \fi \subsection{Choice of Environment} \begin{wrapfigure}{l}{0.4\textwidth}\centering \includegraphics[width=0.19\textwidth]{envs/MiniGrid-Empty-Random-6x6-v0.png} \includegraphics[width=0.19\textwidth]{envs/MiniGrid-DoorKey-6x6-v0.png} \includegraphics[width=0.19\textwidth]{envs/MiniGrid-DistShift1-v0.png} \includegraphics[width=0.19\textwidth]{envs/MiniGrid-GoToDoor-6x6-v0.png} \includegraphics[width=0.39\textwidth]{envs/MiniGrid-RedBlueDoors-6x6-v0.png} \caption{Environments used in the paper. The top-left and top-middle environments terminate only on reaching the goal (green). The other environments can terminate through other conditions as well (mentioned in the paper). However, expert trajectories consist of goal-directed behaviors only.} \label{fig:envs} \vspace*{-38pt} \end{wrapfigure} To observe the limitations of the current methods used in adversarial imitation learning, we propose to use task based environments. However, task based environments with single terminal states will not be able to test the bias of the reward functions due to termination conditions. Hence, we propose to use environments from the Gym Minigrid package \cite{minigrid} with single and multiple termination conditions. We disable the \textit{Done} action to examine the bias of the agent only due to environmental termination conditions. To verify the effects of reward bias in a single termination condition, we choose the \textit{Empty} and \textit{DoorKey} environments. \begin{enumerate} \item In the \textit{Empty} environment, the agent starts at a random location in the grid and the episode terminates when the agent steps on the goal location (in green). \item In the \textit{DoorKey} environment, the agent starts in a room and has to pick up a key to open a locked door. The agent has to reach the goal on the other side of the locked door. \end{enumerate} Both these environments have only one termination condition - the agent has to reach the goal location. Methods like Discriminator-Actor-Critic \cite{dac} can learn a non-zero reward for the terminal condition which overcomes the survival bias of the positive reward function. GAIL with a negative reward can also learn to solve these tasks since they want to accumulate the maximum reward which would require termination of the episode as soon as possible. However, both of these methods can suffer from the same problem - multiple termination conditions. The negative reward will have a bias towards trajectories that terminate early to accumulate fewer negative rewards. The DAC baseline will not differentiate between different termination conditions (termination due to goal completion v/s termination due to other conditions) since the terminal state can potentially provide a large cumulative reward. To test this, we use three other environments within Gym Minigrid. They are: \begin{enumerate} \item \textit{RedBlueDoors}: In this environment, the task is to open a red door, followed by opening the blue door. The episode terminates when the blue door is opened regardless of whether the red door was opened or not. \item \textit{GoToDoor}: This environment is similar to the \textit{RedBlueDoors} environment but there are 4 doors of different colors, and the episode terminates when any door is opened. However, the task is considered to be completed only if the red door is opened. \item \textit{DistShiftv0}: In this environment, the agent has to cross a room with lava near the walls of the room (refer to Figure \ref{fig:envs}. The task is to reach the goal location and avoid the lava. The episode ends when the agent touches the lava or goal. \end{enumerate} These environments have termination conditions which will affect the variants of GAIL depending on the reward bias that they may have. We hypothesize that the inability of DAC to differentiate between terminal states would lead to suboptimal performance in each of these environments. \begin{figure} \centering \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-Empty-Random-6x6-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-DoorKey-6x6-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-DistShift1-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-GoToDoor-6x6-v0.png} \includegraphics[width=0.32\textwidth]{rewards/MiniGrid-RedBlueDoors-6x6-v0.png} \caption{Comparison of performance of different GAIL variants. On-policy DAC is slow in terms of converging to the optimal policy, possibly due to unstable learning of the terminal state reward. In environments with non-goal terminal states, DAC and GAIL with negative rewards converge to suboptimal policies due to their respective biases.} \label{fig:rewards} \end{figure} \section{Experiments} \vspace{-5pt} Our expert is a trained PPO policy. We use 1000 rollouts from the expert policy to train our imitation learning agents for all our experiments. Each rollout has $\sim$10 state-action pairs, so the total number of state action pairs are comparable to \cite{babyai} and \cite{gail}. The locations and colors of the objects are also perturbed across episodes, so the agent has to generalize to the concept of objects rather than memorizing the goal locations. We use 3 CNN layers with Leaky ReLU activations to extract a state embedding of the environment as shown in Figure \ref{fig:arch} for all our experiments. We use PPO \cite{ppo} for on-policy optimisation of the GAIL reward function for all experiments. In each case, the policy network uses this state and returns probability of an action given a state. The policy network head is a 2-layered MLP with Leaky ReLU activations. The value network head is identical to the policy network as shown in Figure \ref{fig:arch}. We average all our results across 3 random seeds. The objective of our first experiment is to exhibit the implicit bias in the positive and negative reward functions. We compare the environment rewards achieved by the agents and the success rate for the 5 environments that we had mentioned earlier. For our second experiment, we compare the environment rewards and success rate of (i) DAC \cite{dac} (ii) Positive Reward (iii) Negative Reward (iv) Neutral Rewards in the five environments. \iffalse \begin{enumerate} \item \textbf{Positive Reward}: Uses $-log(1 - D)$ as the reward. In this we evaluate two scenarios one where D is being learnt and the other where D is set as a constant equal to 0.5. \item \textbf{Negative Reward}: Uses $log(D)$ as the reward. In this we evaluate two scenarios one where D is being learnt and the other where D is set as a constant equal to 0.5. \item \textbf{Neutral Reward}: Uses $log(D) - log(1 - D)$ as the reward. \item \textbf{DAC}: Learn reward for the absorbing state as proposed by Kostrikov et al\cite{dac}. \end{enumerate} \fi \section{Results} \vspace{-5pt} Figure \ref{fig:notrajrewards} shows reward curves for positive and negative rewards with and without learning the discriminator. The first two environments, \textit{Empty} and \textit{Doorkey} are able to attain expert like performance with negative rewards, which was expected as these are task based environments with single termination state. GAIL with positive reward is not able to learn the expert policy due to its survival bias (first two plots of the Figure \ref{fig:notrajrewards}). In case of \textit{Empty}, the agent is able to learn the task even without training the discriminator which shows that the negative reward function has a termination bias strong enough for task based environments. Similarly, for the \textit{DoorKey} environment, GAIL with negative reward starts to learn the task better than positive rewards even when the discriminator is not trained. However, in last three plots of Figure \ref{fig:notrajrewards}, where environments with multiple terminal states are used, termination bias is not enough to learn the task. Positive rewards fall into the survival bias and don't learn the task. An interesting observation is that the success rate of \textit{GoToDoor} with negative reward and no trajectories is 0.25 as shown in Figure \ref{fig:notrajrewards}. The termination bias makes the agent reach out to the nearest door to end the episode, which has a 25\% rate of being the red door. \begin{table}[htpb] \centering \begin{adjustwidth}{-1cm}{} \resizebox{1.1\textwidth}{!}{ \centering \begin{tabular}{|l|c|c|c|c|c|} \hline & \textbf{Empty} & \textbf{DoorKey} & \textbf{GoToDoor} & \textbf{RedBlueDoors} & \textbf{Distshift1} \\ \hline $R = -\log(1-D)$ & $0.03 \pm 0.15$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ \\ \hline $R = -\log(0.5)$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$ & $0.00\pm 0.00$\\ \hline $R = \log(D)$ & $\boldsymbol{1.00 \pm 0.00}$ & $\boldsymbol{1.00\pm 0.00}$ & $0.93 \pm 0.24$ & $0.83 \pm 0.37$ & $0.85 \pm 0.35$\\ \hline $R = \log(0.5)$ & $\boldsymbol{1.00 \pm 0.00}$ & 0.25 $\pm$ 0.43 & 0.38 $\pm$ 0.48 & 0.00 $\pm$ 0.00 & 0.65 $\pm$ 0.47\\ \hline DAC & $\boldsymbol{1.00 \pm 0.00}$ & 0.83 $\pm$ 0.37 & 0.26 $\pm$ 0.44 & 0.70 $\pm$ 0.45 & 0.76 $\pm$ 0.42 \\ \hline $R = \log(D) - \log(1-D)$ & {$\boldsymbol{1.00 \pm 0.00}$} & {$\boldsymbol{1.00 \pm 0.00}$} & {$\boldsymbol{0.97 \pm 0.15}$} & {$\boldsymbol{0.91 \pm 0.27}$} & {$\boldsymbol{0.97 \pm 0.15}$} \\ \hline \end{tabular} } \caption{Success rate of all learnt policies across 3 seeds. For each seed, 20 trajectories were recorded and the mean and variance is calculated across all trajectories.} \label{tab:perf} \end{adjustwidth} \end{table} In Figure \ref{fig:rewards}, we compare the performance of DAC, neutral rewards, negative and positive rewards. The success rate of the different methods is also summarized in Table \ref{tab:perf}. For \textit{Empty} and \textit{DoorKey} all methods except GAIL with positive rewards are able to learn the task. However, DAC is slower than other GAIL methods, and we hypothesize this is because DAC has to learn the reward for the terminal state as well. For the other three environments, termination bias hinders learning with negative rewards and DAC suffers in performance due to lack of distinction between terminal states. For \textit{GoToDoor}, \textit{DistShift} and \textit{RedBlueDoors}, DAC is not able to achieve high success rate showing its limitations in task based scenarios with multiple terminal states. Success rate of neutral reward is the highest and better than the negative reward showing its robustness to termination bias. Similarly, for other the other two task based environments with multiple terminal states, neutral reward significantly outperforms both DAC and negative reward. GAIL with neutral rewards is able to outperform all other methods, hence, is able to overcome both survival and termination bias. \section{Conclusion} \vspace{-5pt} In this work, we address the problem of reward bias in adversarial imitation learning. We explore two types of reward biases - survival bias and termination bias, and how different reward functions lead to these biases in the agent. Positive reward functions encourage survival bias, and negative reward functions encourage termination bias, and both these biases may hinder learning in a task-based environment. We show that real-valued reward functions are unbiased and can learn to overcome both survival and termination biases. Experiments show that this simple change of reward function enables the agent to imitate the expert on tasks with single and multiple termination conditions. \iffalse From our experiments, we are able to show that positive reward is not able to work well in task based environments. Negative rewards are able to learn the expert policy in task based environments with single terminal state, however, they are unable to attain expert performance in task based environments with multiple terminal state. DAC is slow to converge is not able to learn the expert policy in task based environments with multiple terminal states. Our proposed method using neutral rewards achieves expert performance in task based environments with single termination state as well multiple termination states. \fi \clearpage
{'timestamp': '2020-09-22T02:18:19', 'yymm': '2009', 'arxiv_id': '2009.09467', 'language': 'en', 'url': 'https://arxiv.org/abs/2009.09467'}
arxiv